© Copyright 1997 - 2004 por el Grupo de documentación de PHP. Este manual puede ser distribuido solamente bajo los términos y condiciones definidos en la "Licencia de Publicación Abierta" (Open Publication License) version 1.0 ó posterior. Una copia de la Licencia de Publicación Abierta es distribuida con este manual, la última versión se encuentra disponible en » ???.
La distribución de versiones modificadas de este documento está prohibida sin el permiso explícito del titular de este copyright.
La distribución de la documentación ó cualquier derivado de la misma, en cualquier tipo de formato escrito, está prohibido a menos que se obtenga permiso del titular de este copyright.
Si estais interesados en redistribuir o publicar este documento en parte o completo, y teneis preguntas sobre ello, ponerse en contacto con los titulares de los derechos en » doc-license@lists.php.net. Esta direccion pertenece a una lista de correo y se archiva, siendo el acceso publico.
La sección 'Extendiendo PHP 4.0' de este manual es copyright © 2000 por Zend Technologies, Ltd. Esta sección puede ser distribuida solamente bajo los términos y condiciones de la "Licencia de Publicación Abierta", versión 1.0 ó posterior (la última versión se encuentra disponible en » ???).
PHP, acrónimo de "PHP: Hypertext Preprocessor", es un lenguaje "Open Source" interpretado de alto nivel, especialmente pensado para desarrollos web y el cual puede ser embebido en páginas HTML. La mayoría de su sintaxis es similar a C, Java y Perl y es fácil de aprender. La meta de este lenguaje es permitir escribir a los creadores de páginas web, páginas dinámicas de una manera rápida y fácil, aunque se pueda hacer mucho más con PHP.
Este manual contiene principalmente una referencia de funciones PHP, tambien contiene una referencia del lenguaje, explicaciones de caracteristicas importantes de PHP y alguna información suplementaria.
Este manual se puede conseguir en diferentes formatos en » http://www.php.net/docs.php. Más información sobre como este manual es desarrollado puede encontrarse en el apéndice 'Sobre este manual'. Si estais interesados en la Historia de PHP, visitar el capítulo correspondiente.
Actualmente presentamos a los colaboradores mas activos en la portada del manual. Esto no quiere decir que no existan mas colaboradores que tambien trabajan en el manual o que hayan ayudado de manera activa en un pasado. Existen tambien muchas personas que ayudan con sus notas de usuarios a los cuales le estamos infinitamente agradecidos. Todas las listas estan en orden alfabetico.
Los siguientes colaboradores han ayudado ó ayudan de manera muy activa en la creación de contenidos para el manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar, y Andrei Zmievski.
Los siguientes colaboradores han ayudado de manera muy activa en la elaboración del manual: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe, y Egon Schmid.
Encargados de mantenimiento más activos: Friedhelm Betz, Etienne Kneuss, Nuno Lopes, Hannes Magnusson, Felipe Pena, y Maciek Sokolewicz.
Estas persones han ayudado mucho en el pasaso en el mantenimiento de las Notas de usuarios: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles, y Jeroen van Wolffelaar.
PHP (acrónimo de "PHP: Hypertext Preprocessor") es un lenguaje de "código abierto" interpretado, de alto nivel, embebido en páginas HTML y ejecutado en el servidor.
Una respuesta corta y concisa, pero, ¿qué significa realmente? Un ejemplo nos aclarará las cosas:
Example #1 Un ejemplo introductorio
<html>
<head>
<title>Ejemplo</title>
</head>
<body>
<?php
echo "Hola, ¡soy un script PHP!";
?>
</body>
</html>
Puede apreciarse que no es lo mismo que un script escrito en otro lenguaje de programación como Perl o C -- En vez de escribir un programa con muchos comandos para crear una salida en HTML, escribimos el código HTML con cierto código PHP embebido (incluido) en el mismo, que producirá cierta salida (en nuestro ejemplo, producirá un texto). El código PHP se incluye entre etiquetas especiales de comienzo y final que nos permitirán entrar y salir del modo PHP.
Lo que distingue a PHP de la tecnología Javascript, la cual se ejecuta en la máquina cliente, es que el código PHP es ejecutado en el servidor. Si tuviésemos un script similar al de nuestro ejemplo en nuestro servidor, el cliente solamente recibiría el resultado de su ejecución en el servidor, sin ninguna posibilidad de determinar qué código ha producido el resultado recibido. El servidor web puede ser incluso configurado para que procese todos los archivos HTML con PHP.
Lo mejor de usar PHP es que es extremadamente simple para el principiante, pero a su vez, ofrece muchas características avanzadas para los programadores profesionales. No sienta miedo de leer la larga lista de características de PHP, en poco tiempo podrá empezar a escribir sus primeros scripts.
Aunque el desarrollo de PHP está concentrado en la programación de scripts en el lado del servidor, se puede utilizar para muchas otras cosas. Siga leyendo y descubra más sobre PHP en la sección ¿Qué se puede hacer con PHP?.
PHP puede hacer cualquier cosa que se pueda hacer con un script CGI, como procesar la información de formularios, generar páginas con contenidos dinámicos, o enviar y recibir cookies. Y esto no es todo, se puede hacer mucho más.
Existen tres campos en los que se usan scripts escritos en PHP.
PHP puede ser utilizado en cualquiera de los principales sistemas operativos del mercado, incluyendo Linux, muchas variantes Unix (incluyendo HP-UX, Solaris y OpenBSD), Microsoft Windows, Mac OS X, RISC OS y probablemente alguno más. PHP soporta la mayoría de servidores web de hoy en día, incluyendo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape e iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene módulos disponibles para la mayoría de los servidores, para aquellos otros que soporten el estándar CGI, PHP puede usarse como procesador CGI.
De modo que, con PHP tiene la libertad de elegir el sistema operativo y el servidor de su gusto. También tiene la posibilidad de usar programación procedimental o programación orientada a objetos. Aunque no todas las características estándar de la programación orientada a objetos están implementadas en la versión actual de PHP, muchas bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) están escritas íntegramente usando programación orientada a objetos.
Con PHP no se encuentra limitado a resultados en HTML. Entre las habilidades de PHP se incluyen: creación de imágenes, archivos PDF y películas Flash (usando libswf y Ming) sobre la marcha. Tambié puede presentar otros resultados, como XHTM y archivos XML. PHP puede autogenerar éstos archivos y almacenarlos en el sistema de archivos en vez de presentarlos en la pantalla.
Quizás la característica más potente y destacable de PHP es su soporte para una gran cantidad de bases de datos. Escribir un interfaz vía web para una base de datos es una tarea simple con PHP. Las siguientes bases de datos están soportadas actualmente:
También contamos con una extensión DBX de abstracción de base de datos que permite usar de forma transparente cualquier base de datos soportada por la extensión. Adicionalmente, PHP soporta ODBC (el Estándar Abierto de Conexión con Bases de Datos), asi que puede conectarse a cualquier base de datos que soporte tal estándar.
- Adabas D
- dBase
- Empress
- FilePro (read-only)
- Hyperwave
- IBM DB2
- Informix
- Ingres
- InterBase
- FrontBase
- mSQL
- Direct MS-SQL
- MySQL
- ODBC
- Oracle (OCI7 and OCI8)
- Ovrimos
- PostgreSQL
- Solid
- Sybase
- Velocis
- Unix dbm
PHP también cuenta con soporte para comunicarse con otros servicios usando protocolos tales como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos otros. También se pueden crear sockets puros. PHP soporta WDDX para el intercambio de datos entre lenguajes de programación en web. Y hablando de interconexión, PHP puede utilizar objetos Java de forma transparente como objetos PHP Y la extensión de CORBA puede ser utilizada para acceder a objetos remotos.
PHP tiene unas características muy útiles para el procesamiento de texto, desde expresiones regulares POSIX extendidas o tipo Perl hasta procesadores de documentos XML. Para procesar y acceder a documentos XML, soportamos los estándares SAX y DOM. Puede utilizar la extensión XSLT para transformar documentos XML.
Si usa PHP en el campo del comercio electrónico, encontrará muy útiles las funciones Cybercash, CyberMUT, VeriSign Payflow Pro y CCVS para sus programas de pago.
Para terminar, contamos con muchas otras extensiones muy interesantes, las funciones del motor de búsquedas mnoGoSearch, funciones para pasarelas de IRC, utilidades de compresión (gzip, bz2),, conversión de calendarios, traducción .....
Como puede apreciar, esta página no es suficiente para enumerar todas las características y beneficios que PHP ofrece. Consulte las secciones Instalación de PHP y Referencia de las funciones para una explicación de las extensiones mencionadas aquí.
A continuación, le introduciremos a PHP en un pequeño y sencillo manual. Este documento explica cómo crear páginas web dinámicas para Internet con PHP, aunque PHP no solamente está diseñado para la creación de éstas. Consulte la sección titulada ¿Qué se puede hacer con PHP? para más información.
Las páginas web que utilizan PHP son tratadas como páginas de HTML comunes y corrientes, y puede crearlas y editarlas de la misma manera que lo hace con documentos normales de HTML.
En este manual vamos a asumir que usted cuenta con un servidor que soporta PHP y que todos los archivos con la extensión .php son manejados por PHP. En la mayoría de servidores, ésta es la extensión que toman los archivos PHP por defecto, pero pregunte al administrador de su servidor para estar seguro. Si su servidor soporta PHP, entonces no necesita hacer nada, solamente crear sus archivos .php y guardarlos en su directorio web, y el servidor, como por arte de magia, los analizará para usted. No hay necesidad de compilar nada, tampoco tiene necesidad de instalar otras herramientas. Mírelo de esta manera, estos archivos de PHP son tan simples como archivos de HTML con una nueva familia de etiquetas que le permiten una gran cantidad de cosas. La mayoría de las compañías de hospedaje de páginas web ofrecen el soporte que necesita para usar PHP, pero si por alguna razón ellos no lo hacen, considere leer la sección titulada » Recursos PHP para mas información acerca de compañías de hospedaje que soportan PHP
Digamos que usted tiene limitado acceso a internet y se encuentra programando localmente. En este caso, querrá instalar un servidor de web como Apache, y » PHP. Lo más seguro es que también quiera instalar una base de datos como » MySQL. Puede instalar estos productos individualmente o simplemente » localizar un paquete pre-configurado que automáticamente instale todos estos productos con solamente unos movimientos de su ratón. Es muy fácil instalar un servidor web con soporte para PHP en cualquier sistemas operativo, incluyendo Linux y Windows. En Linux, » rpmfind y » PBone le ayudarán a encontrar un RPM.
Comienze por crear un archivo llamado hola.php y colocarle en el "directorio raíz" (DOCUMENT_ROOT) con el siguiente contenido:
Example #1 Nuestro primer script PHP: hola.php
<html>
<head>
<title>Ejemplo de PHP</title>
</head>
<body>
<?php echo "<p>Hola Mundo</p>"; ?>
</body>
</html>
Utilice su navegador web para acceder al archivo, con la URL terminando en "/hola.php". Si está programando localmente este URL lucirá algo como http://localhost/hola.php o http://127.0.0.1/hola.php pero esto depende de la configuración de su servidor web. Aunque este tema está fuera del alcance de este tutorial, también puede ver las directivas DocumentRoot y ServerName en la configuración de su servidor (en Apache, esto es httpd.conf). Si todo está configurado correctamente, el archivo será analizado por PHP y el siguiente contenido aparecerá en su navegador:
<html> <head> <title>Ejemplo de PHP</title> </head> <body> <p>Hola Mundo</p> </body> </html>
Note que esto no es como los scripts de CGI. El archivo no necesita ninguna clase especial de permisos para ser ejecutado. Piense en ellos como si fueran archivos HTML con un conjunto muy especial de etiquetas disponibles, y que hacen muchas cosas interesantes.
Este programa es extremadamente simple, y no necesita usar PHP para crear una página como ésta. Todo lo que hace es mostrar: Hola Mundo usando la sentencia echo().
Si ha intentado usar este ejemplo, y no produjo ningún resultado, preguntando si deseaba descargar el archivo, o mostró todo el archivo como texto, lo más seguro es que PHP no se encuentra habilitado en su servidor. Pídale a su administrador que active esta función por usted, o use el capítulo titulado Instalación en el manual. Si está trabajando localmente, lea también el capítulo dedicado a la instalación, y asegúrese de que todo esté configurado apropiadamente. Si el problema continúa, por favor use una de las muchas opciones para obtener » ayuda con PHP.
El objetivo de este ejemplo es demostrar cómo puede usar las etiquetas PHP. En este ejemplo usamos <?php para indicar el inicio de la etiqueta PHP. Después indicamos la sentencia y abandonamos el modo PHP usando ?>. Puede salir de PHP y regresar cuantas veces lo desee usando este método. Para más información, puede leer la sección en el manual titulada Sintaxis básica de PHP.
Note: Una nota acerca de editores de texto
Hay muchos editores de texto y Entornos Integrados de Desarrollo (IDE por sus siglas en Inglés) que puede usar para crear, editar, y organizar archivos PHP. Puede encontrar una lista parcial de éstos en » Lista de editores de PHP. Si desea recomendar un editor, por favor visite la página mencionada anteriormente, y comunique su recomendación a las personas encargadas del mantenimiento para que lo incluyan en la lista. Contar con un editor que resalte la sintaxis de PHP puede ser de mucha ayuda.
Note: Una nota acerca de los procesadores de palabras
Los procesadores de palabras como "StarOffice", "Microsoft word" y "Abiword" no son buenas opciones para editar archivos de PHP. Si desea usar uno de éstos programas para probar sus scripts, primero debe asegurarse de guardar el documento en formato de "Texto" puro, o PHP no será capaz de ejecutar el script.
Note: Una nota acerca del "Bloc de Notas de Windows"
Si desea escribir sus archivos PHP usando el "Bloc de Notas de Windows" o en algún otro editor de texto para Windows necesita asegurarse de que sus archivos sean guardados con la extensión .php (la mayoría de editores de texto en Windows automáticamente tratarán de añadir la extensión .txt a los archivos a menos que tome los siguientes pasos para prevenirlo). Cuando guarde sus archivos y el programa le pregunte qué nombre le desea dar al archivo, use comillas para indicar el nombre (es decir, "hola.php"). Una alternativa es, en la lista de opciones "Archivos de Texto *.txt", seleccionar la opción "Todos los archivos *.*". Aquí puede escribir el nombre del archivo sin las comillas.
Ahora que ha creado un pequeño script de PHP que funciona correctamente, es hora de trabajar con el script de PHP más famoso; vamos a hacer una llamada a la función phpinfo() para obtener información acerca de su sistema y configuración como las variables predefinidas disponibles, los módulos utilizados por PHP, y las diferentes opciones de configuración. Tomemos unos segundos para revisar esta información.
Hagamos ahora algo que puede ser más útil. Vamos a chequear qué clase de navegador web utiliza. Para hacerlo, vamos a consultar la información que el navegador nos envía como parte de su petición HTTP. Esta información es guardada en una variable. Las variables siempre comienzan con un signo de dólar ("$") en PHP. La variable que vamos a utilizar en esta situación es $_SERVER["HTTP_USER_AGENT"].
Note: $_SERVER es una variable reservada por PHP que contiene toda la información del servidor web. Es conocida como Autoglobal (o Superglobal). Consulte el manual en su sección titulada Autoglobales para mas información. Éstas son variables especiales que fueron introducidas en la versión » 4.1.0 de PHP. Antes podíamos usar las matrices $HTTP_*_VARS, tales como $HTTP_SERVER_VARS. Aunque éstas han sido marcadas como obsoletas, tales matrices todavía existen. (También puede echar un vistazo a las notas relacionadas con el código antiguo.)
Para poder ver esta variable solo necesita:
Example #1 Impresión de una variable (elemento de la matriz)
<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>
Un ejemplo de los resultados de este programa sería:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Hay muchos tipos de variables en PHP. En el ejemplo anterior imprimimos una matriz. Las matrices pueden ser muy útiles.
$_SERVER es simplemente una variable que se encuentra disponible automáticamente para usted en PHP. Puede encontrar una lista en la sección titulada Variables Reservadas del manual, o puede generar una lista completa creando un archivo como el presentado a continuación:
Example #2 Consultar todas las variables predefinidas con phpinfo()
<?php phpinfo(); ?>
Si abre este archivo con su navegador, puede ver una página con información acerca de PHP, junto a una lista de todas las variables que puede usar.
Puede usar más de un declaración PHP dentro de una etiqueta PHP, y crear pequeños segmentos de código que pueden hacer más que un "echo". Por ejemplo, si quisiéramos detectar el uso de "Internet Explorer", haríamos algo así:
Example #3 Ejemplos de uso de estructuras de control y funciones
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
echo "Está usando Internet Explorer<br />";
}
?>
Un ejemplo de los resultado del script puede ser:
Está usando Internet Explorer<br />
A continuación introduciremos un par de conceptos nuevos. Tenemos una declaración "if". Si está familiarizado con la sintaxis básica del lenguaje "C", esto se vera lógico, Pero si no entiende "C", u otros lenguajes de programación donde encuentra la sintaxis usada anteriormente, probablemente debería conseguir un libro que le introduzca mejor a PHP, y lea los primeros capítulos, o también puede ver la parte del manual titulada Referencia del lenguaje. Puedes encontrar una lista de libros sobre PHP en » http://www.php.net/books.php.
El segundo concepto que introducimos fue la función llamada strstr(). strstr() es una función integrada de PHP que busca un cadena dentro de otra cadena más larga. En el caso anterior estamos buscando "MSIE" dentro de $_SERVER["HTTP_USER_AGENT"]. Si la cadena fue encontrada, la función devolverá verdadero ("TRUE"), la declaración "if" se evalúa a verdadero ("TRUE") y el código adentro de las llaves {} es ejecutado. De otra manera no resulta ejecutado. Tómese la libertad de crear ejemplos similares usando "if", "else" ("de otra manera"), y otras funciones como strtoupper() y strlen(). Cada página del manual contiene ejemplos que puede usar. Si no está seguro sobre el modo de uso éstas funciones, es recomendable que lea las páginas del manual tituladas Cómo leer una definición de función y la sección relacionada a Funciones en PHP
Podemos continuar y demostrar cómo puede saltar adentro y afuera del modo PHP en el medio de un bloque de código.
Example #4 Mezcla de los modos HTML y PHP
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
?>
<h3>strstr debe haber devuelto verdadero</h3>
<center><b>Está usando Internet Explorer</b></center>
<?php
} else {
?>
<h3>strstr debió devolver falso</h3>
<center><b>No está usando Internet Explorer</b></center>
<?php
}
?>
Un ejemplo de los resultados de este script puede ser:
<h3>strstr debe haber devuelto verdadero </h3> <center><b>Está usando Internet Explorer</b></center>
En vez de usar una sentencia PHP "echo" para demostrar algo, saltamos fuera del código PHP y escribimos HTML puro. Este es un punto muy importante y potente que debemos observar aquí, y es que la fluidez lógica del script está intacta. Sólamente las partes donde hay HTML serán enviadas a su navegador dependiendo de los resultados que strstr() devuelve (si fue verdadero [TRUE], o falso [FALSE]). En otras palabras, si la cadena MSIE fue encontrada o no.
Otra de las características de PHP es que gestiona formularios de HTML. El concepto básico que es importante entender es que cualquier elemento de los formularios estará disponible automáticamente en su código PHP. Por favor refiérase a la sección titulada Variables fuera de PHP en el manual para más información y ejemplos sobre cómo usar formularios HTML con PHP. Observemos un ejemplo:
Example #1 Un formulario HTML sencillo
<form action="accion.php" method="POST"> Su nombre: <input type="text" name="nombre" /> Su edad: <input type="text" name="edad" /> <input type="submit"> </form>
No hay nada especial en este formularo, es HTML limpio sin ninguna clase de etiquetas desconocidas. Cuando el cliente llena éste formulario y oprime el botón etiquetado "Submit", una página titulada accion.php es llamada. En este archivo encontrará algo así:
Example #2 Procesamiento de información de nuestro formulario HTML
Hola <?php echo $_POST["nombre"]; ?>.
Tiene <?php echo $_POST["edad"]; ?> años
Un ejemplo del resultado de este script podría ser:
Hola José.
Tiene 22 años
Es aparentemente obvio lo que hace. No hay mucho más que decir al respecto. Las variables $_POST["nombre"] y $_POST["edad"] son definidas automáticamente por PHP. Hace un momento usamos la variable autoglobal $_SERVER, ahora hemos introducido autoglobal $_POST, que contiene toda la información enviada por el método POST. Fíjese en el atributo method en nuestro formulario; es POST. Si hubiéramos usado GET, entonces nuestra información estaría en la variable autoglobal $_GET. También puede utilizar la autoglobal $_REQUEST si no le importa el origen de la petición. Ésta variable contiene una mezcla de información GET, POST y COOKIE. También puede ver la función import_request_variables().
Ahora que PHP ha crecido y se ha convertido en un lenguaje popular, hay muchos más recursos que contienen código que puede reusar en sus propios programas. Por lo general, las personas que se encargan del desarrollo de PHP tratan de que el lenguaje sea compatible con versiones anteriores, para que los programas escritos con versiones antiguas continúen funcionando cuando instale una nueva versión de PHP. En un mundo perfecto, nunca necesitaría modificar su código para hacerlo funcionar con versiones nuevas del lenguaje; pero, como todos sabemos, este no es un mundo perfecto, y usualmente son necesarios los cambios en su código.
Dos de los cambios mas importantes que afectan el código viejo son:
Con lo que hemos visto, puede entender la mayor parte del manual, y también los ejemplos que están disponibles en los archivos. También puede encontrar otros ejemplos en los diferentes sitios de php.net en la sección de enlaces: » http://www.php.net/links.php.
Para ver una presentación que muestra más acerca de lo que puede hacer PHP, visite los diferentes sitios con material relacionado a las conferencias realizadas: » http://conf.php.net/ y » http://talks.php.net/.
Antes de instalar PHP, necesitais saber porque quereis utilizarlo. Existen tres campos principales en donde PHP se puede usar, tal y como se describe en la sección Qué se puede hacer con PHP?:
El primero es el más tradicional y el principal campo de trabajo. Se necesitan tres cosas para que funcione. El analizador PHP (CGI ó módulo), un servidor web y un navegador. Dependiendo de la versión de sistema operativo que utiliceis, probablemente tengais un servidor web (p.ej: Apache en Linux y MacOS X ó IIS en Windows). También se puede alquilar espacio web en una empresa que ofrezca este servicio. De esta manera no se necesita instalar nada, solamente escribir los scripts PHP, subirlos al espacio alquilado y ver el resultado en vuestro navegador.
Teneis dos maneras de utilizar PHP, si instalais vosotros el servidor y PHP. Existen módulos directos (también llamados SAPI) para muchos servidores web, como Apache, Microsoft Internet Information Server, Netscape e iPlanet. Muchos otros servidores soportan ISAPI, (p.ej.:OmniHTTPd). Si PHP no soporta un módulo para tu servidor web, siempre se puede usar como binario CGI. Esto significa que el servidor se configura para usar el ejecutable para linea de comandos de PHP en el procesado de peticiones de ficheros PHP.
Si estais interesados en usar PHP desde la linea de comandos (p.ej.: para generar imagenes offline ó procesar ficheros de textos, etc) necesitais el ejecutable para linea de comandos. Para más información, lea la sección Usando PHP desde la línea de comandos. En este caso no se necesita ni servidor web, ni navegador.
Con PHP tambien se puede escribir aplicaciones gráficas usando la extensión PHP-GTK. Esta es una forma totalmente distinta de utilizar PHP que cuando se utiliza para escribir páginas web, ya que no se genera código HTML sino que se trabaja con ventanas y objetos dentro de las mismas. Para más información sobre PHP-GTK, visitar » las páginas dedicadas a esta extensión. PHP-GTK no se incluye en la distribución oficial de PHP.
A partir de ahora, esta sección tratará sobre la configuración de PHP con servidores web, en Unix y Windows, tanto como módulo, como binario CGI.
PHP, el código fuente y distribuciones binarias para Windows se pueden encontrar en » http://www.php.net/. Recomendamos utilizar un » servidor espejo cerca de donde esteis para bajaros la versión de PHP que querais.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Example #1 Installation Instructions (Apache Shared Module Version) for PHP
1. gunzip apache_xxx.tar.gz 2. tar -xvf apache_xxx.tar 3. gunzip php-xxx.tar.gz 4. tar -xvf php-xxx.tar 5. cd apache_xxx 6. ./configure --prefix=/www --enable-module=so 7. make 8. make install 9. cd ../php-xxx 10. Now, configure your PHP. This is where you customize your PHP with various options, like which extensions will be enabled. Do a ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 1 and MySQL support. Your path to apxs may differ from our example. ./configure --with-mysql --with-apxs=/www/bin/apxs 11. make 12. make install If you decide to change your configure options after installation, you only need to repeat the last three steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed. Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more. 13. Setup your php.ini file: cp php.ini-dist /usr/local/lib/php.ini You may edit your .ini file to set PHP options. If you prefer your php.ini in another location, use --with-config-file-path=/some/path in step 10. If you instead choose php.ini-recommended, be certain to read the list of changes within, as they affect how PHP behaves. 14. Edit your httpd.conf to load the PHP module. The path on the right hand side of the LoadModule statement must point to the path of the PHP module on your system. The make install from above may have already added this for you, but be sure to check. For PHP 4: LoadModule php4_module libexec/libphp4.so For PHP 5: LoadModule php5_module libexec/libphp5.so 15. And in the AddModule section of httpd.conf, somewhere under the ClearModuleList, add this: For PHP 4: AddModule mod_php4.c For PHP 5: AddModule mod_php5.c 16. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse the .php extension as PHP. You could have any extension(s) parse as PHP by simply adding more, with each separated by a space. We'll add .phtml to demonstrate. AddType application/x-httpd-php .php .phtml It's also common to setup the .phps extension to show highlighted PHP source, this can be done with: AddType application/x-httpd-php-source .phps 17. Use your normal procedure for starting the Apache server. (You must stop and restart the server, not just cause the server to reload by using a HUP or USR1 signal.)
Alternatively, to install PHP as a static object:
Example #2 Installation Instructions (Static Module Installation for Apache) for PHP
1. gunzip -c apache_1.3.x.tar.gz | tar xf - 2. cd apache_1.3.x 3. ./configure 4. cd .. 5. gunzip -c php-5.x.y.tar.gz | tar xf - 6. cd php-5.x.y 7. ./configure --with-mysql --with-apache=../apache_1.3.x 8. make 9. make install 10. cd ../apache_1.3.x 11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a (The above line is correct! Yes, we know libphp5.a does not exist at this stage. It isn't supposed to. It will be created.) 12. make (you should now have an httpd binary which you can copy to your Apache bin dir if it is your first install then you need to "make install" as well) 13. cd ../php-5.x.y 14. cp php.ini-dist /usr/local/lib/php.ini 15. You can edit /usr/local/lib/php.ini file to set PHP options. Edit your httpd.conf or srm.conf file and add: AddType application/x-httpd-php .php
Note: Replace php-5 by php-4 and php5 by php4 in PHP 4.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Example #3 Example commands for restarting Apache
1. Several Linux and SysV variants: /etc/rc.d/init.d/httpd restart 2. Using apachectl scripts: /path/to/apachectl stop /path/to/apachectl start 3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl: /path/to/httpsdctl stop /path/to/httpsdctl start 4. Using mod_ssl, or another SSL server, you may want to manually stop and start: /path/to/apachectl stop /path/to/apachectl startssl
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
./configure --with-apxs --with-pgsql
This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.
./configure --with-apxs --with-pgsql=shared
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
./configure --with-apache=/path/to/apache_source --with-pgsql
This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.
./configure --with-apache=/path/to/apache_source --with-pgsql=shared
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.
Note: Apache's default httpd.conf currently ships with a section that looks like this:
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.User nobody Group "#-1"
Note: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
No usar Apache 2.0 y PHP en un sistema en produccion, tanto en Unix como en Windows. Consultar la FAQ
You are highly encouraged to take a look at the » Apache Documentation to get a basic understanding of the Apache 2.0 Server.
Note: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at » http://www.php.net/downloads.php.
- the latest stable development version. Get the source code » http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows » http://snaps.php.net/win32/php5-win32-latest.zip.
- a prerelease version downloadable from » http://qa.php.net/.
- you have always the option to obtain PHP through » anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Download the most recent version of » Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.
Example #1 Installation Instructions (Apache 2 Shared Module Version)
1. gzip -d httpd-2_0_NN.tar.gz 2. tar xvf httpd-2_0_NN.tar 3. gunzip php-NN.tar.gz 4. tar -xvf php-NN.tar 5. cd httpd-2_0_NN 6. ./configure --enable-so 7. make 8. make install Now you have Apache 2.0.NN available under /usr/local/apache2, configured with loadable module support and the standard MPM prefork. To test the installation use your normal procedure for starting the Apache server, e.g.: /usr/local/apache2/bin/apachectl start and stop the server to go on with the configuration for PHP: /usr/local/apache2/bin/apachectl stop. 9. cd ../php-NN 10. Now, configure your PHP. This is where you customize your PHP with various options, like which extensions will be enabled. Do a ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support. Your path to apxs may differ, in fact, the binary may even be named apxs2 on your system. ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql 11. make 12. make install If you decide to change your configure options after installation, you only need to repeat the last three steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed. Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more. 13. Setup your php.ini cp php.ini-dist /usr/local/lib/php.ini You may edit your .ini file to set PHP options. If you prefer having php.ini in another location, use --with-config-file-path=/some/path in step 10. If you instead choose php.ini-recommended, be certain to read the list of changes within, as they affect how PHP behaves. 14. Edit your httpd.conf to load the PHP module. The path on the right hand side of the LoadModule statement must point to the path of the PHP module on your system. The make install from above may have already added this for you, but be sure to check. For PHP 4: LoadModule php4_module modules/libphp4.so For PHP 5: LoadModule php5_module modules/libphp5.so 15. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse .php files as PHP. Instead of only using the Apache AddType directive, we want to avoid potentially dangerous uploads and created files such as exploit.php.jpg from being executed as PHP. Using this example, you could have any extension(s) parse as PHP by simply adding them. We'll add .phtml to demonstrate. <FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch> Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and .phtml files to be executed as PHP, but nothing else, we'd use this: <FilesMatch "\.ph(p[2-6]?|tml)$"> SetHandler application/x-httpd-php </FilesMatch> And to allow .phps files to be executed as PHP source files, add this: <FilesMatch "\.phps$"> SetHandler application/x-httpd-php-source </FilesMatch> 16. Use your normal procedure for starting the Apache server, e.g.: /usr/local/apache2/bin/apachectl start - OR - service httpd restart
Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree. If you wish to build a multithreaded version of Apache2, you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Before doing so, please beware the consequences and have at least a fair understand of what the implications. For more information, read the Apache documentation regarding » MPM-Modules.
Note: If you want to use content negotiation, read the Apache MultiViews FAQ.
Note: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.
Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.
Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP5.3, but for older versions configure php with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).
To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.
Example #1 Partial lighttpd.conf
server.modules += ( "mod_fastcgi" ) fastcgi.server = ( ".php" => (( "socket" => "/tmp/php.socket", "bin-path" => "/usr/local/bin/php-cgi", "bin-environment" => ( "PHP_FCGI_CHILDREN" => "16", "PHP_FCGI_MAX_REQUESTS" => "10000" ), "min-procs" => 1, "max-procs" => 1, "idle-timeout" => 20 )) )
The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).
Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.
It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.
Example #2 Spawning FastCGI Responders
#!/bin/sh # Location of the php-cgi binary PHP=/usr/local/bin/php-cgi # PID File location PHP_PID=/tmp/php.pid # Binding to an address #FCGI_BIND_ADDRESS=10.0.1.1:10000 # Binding to a domain socket FCGI_BIND_ADDRESS=/tmp/php.sock PHP_FCGI_CHILDREN=16 PHP_FCGI_MAX_REQUESTS=10000 env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \ PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \ $PHP -b $FCGI_BIND_ADDRESS & echo $! > "$PHP_PID"
Fastcgi instances can be spawned on multiple remote machines in order to scale applications.
Example #3 Connecting to remote php-fastcgi instances
fastcgi.server = ( ".php" => (( "host" => "10.0.0.2", "port" => 1030 ), ( "host" => "10.0.0.3", "port" => 1030 )) )
PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.
Example #1 Caudium Installation Instructions
1. Make sure you have Caudium installed prior to attempting to install PHP 4. For PHP 4 to work correctly, you will need Pike 7.0.268 or newer. For the sake of this example we assume that Caudium is installed in /opt/caudium/server/. 2. Change directory to php-x.y.z (where x.y.z is the version number). 3. ./configure --with-caudium=/opt/caudium/server 4. make 5. make install 6. Restart Caudium if it's currently running. 7. Log into the graphical configuration interface and go to the virtual server where you want to add PHP 4 support. 8. Click Add Module and locate and then add the PHP 4 Script Support module. 9. If the documentation says that the 'PHP 4 interpreter isn't available', make sure that you restarted the server. If you did check /opt/caudium/logs/debug/default.1 for any errors related to <filename>PHP4.so</filename>. Also make sure that <filename>caudium/server/lib/[pike-version]/PHP4.so</filename> is present. 10. Configure the PHP Script Support module if needed.
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
Note: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.
To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.
Note: Support for fhttpd is no longer available as of PHP 4.3.0.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from » http://www.sunfreeware.com/ or another download site:
export PATH
.
gunzip php-x.x.x.tar.gz
(if you have a .gz dist,
otherwise go to 4).
tar xvf php-x.x.x.tar
cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object>
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object>
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object>
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object>
Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Note: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
The default is to build PHP as a CGI program. This creates a command line interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.
Al usar el modo CGI, vuestro servidor esta expuesto a diferentes ataques. Por favor, leer la sección Seguridad con CGI para aprender como defenderse de estos ataques.
As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.
If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.
Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems.
There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.
Official pre-compiled packages are located here: » http://software.hp.com/
Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11
This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.
Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.
The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Example #1 OpenBSD Package Install Example
# pkg_add php4-core-4.3.8.tgz # /usr/local/sbin/phpxs -s # cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini (add in mysql) # pkg_add php4-mysql-4.3.8.tgz # /usr/local/sbin/phpxs -a mysql (add in imap) # pkg_add php4-imap-4.3.8.tgz # /usr/local/sbin/phpxs -a imap (remove mysql as a test) # pkg_delete php4-mysql-4.3.8 # /usr/local/sbin/phpxs -r mysql (install the PEAR libraries) # pkg_add php4-pear-4.3.8.tgz
Read the » packages(7) manual page for more information about binary packages on OpenBSD.
You can also compile up PHP from source using the » ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.
Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.
While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.
PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.
If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at » http://www.apt-get.org/. One of the results found should be » Dotdeb. This unofficial repository is maintained by » Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :
Example #1 The two Dotdeb related lines
deb http://packages.dotdeb.org stable all deb-src http://packages.dotdeb.org stable all
The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.
Now that everything is in place, you can use the following example to install Apache and PHP:
Example #2 Debian Install Example with Apache 1.3
# apt-get install libapache-mod-php4
APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :
Example #3 Stopping and starting Apache once PHP 4 is installed
# /etc/init.d/apache stop # /etc/init.d/apache start
In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).
Example #4 Getting the list of PHP additional packages
# dpkg -l 'php4-*'
As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.
If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:
Example #5 Install PHP with MySQL, cURL and GD
# apt-get install php4-mysql php4-curl php4-gd
APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).
Example #6 These lines activate MySQL, cURL and GD into PHP
extension=mysql.so extension=curl.so extension=gd.so
You'll only have to stop/start Apache as previously to activate the modules.
Example #7 This line activates PHP 4 into Apache
# Include /etc/apache/conf.d/
This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:
PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).
Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.
The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:
Note: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /etc/httpd/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.
With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):
# LoadModule php4_module libexec/httpd/libphp4.so # AddModule mod_php4.c
Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)
Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.
<IfModule mod_php4.c> # If php is turned on, we respect .php and .phps files. AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps # Since most users will want index.php to work we # also automatically enable index.php <IfModule mod_dir.c> DirectoryIndex index.html index.php </IfModule> </IfModule>
The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:
<?php phpinfo(); ?>