2. 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, también contiene una referencia
del lenguaje, explicaciones de algunas de las características importantes de PHP otra información
suplementaria.
Este manual se puede conseguir en diferentes formatos en » http://www.php.net/download-docs.php. Más
información sobre como este manual es desarrollado puede encontrarse en el apéndice 'Sobre este
manual'. Si está interesado en la Historia de PHP, visite el capítulo correspondiente.
Authors and Contributors
We highlight the currently most active people on front page of the manual, but there are many more
contributors who currently help in our work or have provided a great amount of help to the project in the
past. There are a lot of unnamed people who help out with user notes on manual pages, which continually
get included in the references, the work of whom we are also very thankful for. All of the lists provided
below are in alphabetical order.
Authors and Editors
The following contributors should be recognized for the impact they have made and/or continue to make
by adding content to the manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig
Bakken, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall,
Simone Cortesi, Peter Cowburn, Daniel Egeberg, 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, Kalle Sommer Nielsen, Yasuo
Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas
Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, Michael Wallner, Lars
Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Gabor Hojtsy,
Hartmut Holzgraefe and Egon Schmid.
User Note Maintainers
The currently most active maintainers are: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda and
Maciek Sokolewicz.
These people have also put a lot of effort into managing user notes: 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,
Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson,
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 and Jeroen van Wolffelaar.
•
Prefacio
3. Conceptos Básicos
Introducción
Table of Contents
•
•
¿Qué es PHP?
¿Qué se puede hacer con PHP?
¿Qué es PHP?
PHP (acrónimo de PHP: Hypertext Preprocessor) es un lenguaje de código abierto muy popular
especialmente adecuado para desarrollo web y que puede ser incrustado en HTML.
Una respuesta corta y concisa, pero, ¿qué significa realmente? Un ejemplo nos aclarará las cosas:
Example #1 Un ejemplo introductorio
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hola, ¡soy un script PHP!";
?>
</body>
</html>
En lugar de usar muchos comandos para mostar HTML (como en C o Perl), páginas PHP contienen
HTML con código incluido en el mismo que hace "algo" (en este caso, mostrar "Hola ¡soy un script
PHP!). El código PHP está entre medio de etiquetas de comienzo y final especiales<?php y ?> que nos
permitirán entrar y salir del "modo PHP".
Lo que distingue a PHP de algo lado-cliente como Javascript, es que el código es ejecutado en el servidor,
generando HTML y enviándolo al cliente. El cliente recibirá los resultados de ejecutar el script, 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 y entonces no hay manera
que los usuarios puedan saber que tienes debajo de la manga.
4. 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á centrado en programación de scripts en lado-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? o vaya directo al tutorial de introducción si solamente está interesado en programación web.
¿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 principalmente tres campos en los que se usan scripts en PHP.
•
•
•
Scripts del lado-servidor. Este es el campo más tradicional y el principal foco de trabajo. Se
necesitan tres cosas para que esto funcione. El intérprete PHP (CGI módulo), un servidor web y un
navegador. Es necesario hacer funcionar el servidor, con PHP instalado. El resultado del programa
PHP se puede obtener a través del navegador, conectándose con el servidor web. Consultar la
sección Instrucciones de instalación para más información.
Scripts en la línea de comandos. Puede crear un script PHP y correrlo sin necesidad de un servidor
web o navegador. Solamente necesita el intérprete PHP para usarlo de esta manera. Este tipo de
uso es ideal para scripts ejecutados regularmente desde cron (en *nix o Linux) o el Planificador de
tareas (en Windows). Estos scripts también pueden ser usados para tareas simples de
procesamiento de texto. Consultar la sección Usos de PHP en la línea de comandos para más
información.
Escribir aplicaciones de interfaz gráfica. Probablemente PHP no sea el lenguaje más apropiado
para escribir aplicaciones gráficas, pero si conoce bien PHP, y quisiera utilizar algunas
características avanzadas en programas clientes, puede utilizar PHP-GTK para escribir dichos
programas. También es posible escribir aplicaciones independientes de una plataforma. PHP-GTK
es una extensión de PHP, no disponible en la distribución principal. Si está interesado en PHPGTK, puedes visitar las » páginas web del proyecto.
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 P.O.O. están implementadaS en PHP 4, muchas
bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) están escritas usando íntegramente
P.O.O. PHP 5 soluciona los puntos flacos de P.O.O en PHP 4 e introduce soporte completo para objectos.
Con PHP no se encuentra limitado a resultados en HTML. Entre las habilidades de PHP se incluyen:
creación de imágenes, archivos PDF e incluso películas Flash (usando libswf y Ming) sobre la marcha.
Tambié puede presentar otros resultados, como XHTML y cualquier otro tipo de ficheros XML. PHP
5. puede autogenerar éstos archivos y almacenarlos en el sistema de archivos en vez de presentarlos en la
pantalla, creando un caché en el lado-servidor para contenido dinámico.
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 increíblemente simple con PHP.
Las siguientes bases de datos están soportadas actualmente:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Adabas D
dBase
Empress
FilePro (solo lectura)
Hyperwave
IBM DB2
Informix
Ingres
InterBase
FrontBase
mSQL
Direct MS-SQL
MySQL
ODBC
Oracle (OCI7 y OCI8)
Ovrimos
PostgreSQL
SQLite
Solid
Sybase
Velocis
Unix dbm
También tenemos abstracción de base de datos (llamada PDO) 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.
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 e interactuar usando cualquier otro protocolo. 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, PHP 4 soportama los estándares SAX y DOM y también Puede utilizar la extensión
XSLT para transformar documentos XML. PHP 5 estandariza todas las extensiones XML en una sólida
base de libxml2 y extiende las características establecer añadir SimpleXML y soporte para XMLReader.
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í.
6. Un tutorial sencillo
Table of Contents
•
•
•
•
•
•
What do I need?
Su primera página con PHP
Algo útil
Uso de Formularios
Using old code with new versions of PHP
¿Y ahora qué?
A continuación, nos gustaría mostrate las bases de PHP en un corto y sencillo tutorial. Este documento
explica cómo crear páginas web dinámicas con PHP, aunque PHP no solamente es capaz de crear páginas
web. Consulte la sección titulada ¿Qué se puede hacer con PHP? para más información.
Las páginas web que usan PHP se tratan igual que páginas HTML comunes y corrientes, y se pueden
crear o editar de la misma manera que normalmente crea páginas HTML.
What do I need?
En este manual asumimos que cuenta con un servidor que soporta PHP y que todos los archivos con la
extensión .php son usados 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 los analizará por usted. No hay necesidad de compilar nada o instalar otras
herramientas. Mírelo de esta manera, los archivos PHP son tan simples como archivos de HTML con el
añadido de una nueva familia de etiquetas que permiten todo tipo 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 más información acerca de compañías
de hospedaje que soportan PHP.
Digamos que quiere ahorrar preciado ancho de banda y programar en local. En este caso, querrá instalar
un servidor web, como » Apache, y por supuesto » PHP. Lo más seguro es que también quiera instalar
una base de datos como » MySQL.
Instálelos de forma independientemente o bien puede elegir una manera más sencilla. Nuestro manual
contiene Instrucciones de instalación de PHP (asumiendo que tiene algún tipo de servidor web ya
configurado). En el caso que tenga problemas con la instalación, sugerimos que haga sus preguntas en
nuestra » lista de correo de instalación. Si elige la manera más sencilla, entonces » localice paquete preconfigurado para su sistema operativo, incluyendo MacOSX, Linux y Windows. En Linux, quizá
encuentra que » rpmfind y » PBone le son de ayuda para encontrar los RPMs. Para encontrar paquetes
para Debian quizá quiera visitar » apt-get.
7. Su primera página con PHP
Comienze por crear un archivo llamado hola.php y póngalo en el "directorio raíz" (DOCUMENT_ROOT)
con el siguiente contenido:
Example #1 Nuestro primer script PHP: hola.php
<html>
<head>
<title>Ejemplo PHP</title>
</head>
<body>
<?php echo '<p>Hola Mundo</p>'; ?>
</body>
</html>
Utilice su navegador web para acceder al archivo en su servidor, con la URL terminando en /hola.php. Si
está programando localmente este URL será 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. Si todo está
configurado correctamente, el fichero será analizado por PHP y el siguiente contenido aparecerá en su
navegador:
<html>
<head>
<title>Ejemplo PHP</title>
</head>
<body>
<p>Hola mundo</p>
</body>
</html>
Este script es extremadamente simple y no es necesario usar PHP para crear una página como esta. Lo
único que muestra es: Hola mundo usando la función de PHP echo(). El fichero no debe ser ejecutable o
especial de ninguna forma. El servidor reconoce que este fichero debe ser interpretado por PHP porque
estamos usando la extensión ".php", el cuál está configurado para enviarlo a PHP. Piensa como si fuera
un fichero HTML normal el cual tiene una serie de etiquetas especiales disponibles con las que puedes
hacer muchas cosas interesantes.
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 usando el capítulo titulado Instalación en el
manual. Si está trabajando localmente, lea también el capítulo dedicado a la instalación para asegurarse de
que todo esté configurado apropiadamente. Asegúrese que está accediendo al fichero vía http a través del
servidor para mostrar el resultado. Si está abriendo el archivo desde el sistema de archivos, entonces
probablemente no estará siendo analizado por PHP. Si el problema persiste no dude en usar alguna de las
múltiples opciones de » Soporte de PHP.
El objetivo de este ejemplo es demostrar cómo puede usar el formato especial de 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: Anotación los avances de línea
Los avances de línia tienen poco sentido en HTML, igualmente sigue siendo buena idea hacer
que el código HTML se vea limpio y bien, poniendo avances de línea. PHP automáticamente
eliminará los avances de línea puestos inmediatamente después de cerrar ?>. Esto puede ser
8. muy útil si pone muchos bloques de PHP o incluye ficheros que contienen PHP que no se
supone que deban mostarar nada. Al mismo tiempo, puede resultar un poco confuso. Se puede
poner un espacio después de cerrar ?> para forzar el mostrar un espacio y un avance de línea ,
o se puede poner un avance de línea explícitamente en el último echo o print dentro de tu
bloque en PHP.
Note: Anotación 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: Anotación acerca de los procesadores de texto
Los procesadores de texto como StarOffice Writer, 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 texto sin formato o PHP no será
capaz de leer y ejecutar el script.
Note: Una nota acerca del "Bloc de Notas de Windows"
Si escribe sus archivos PHP usando el "Bloc de Notas de Windows", debe asegurarse de que
sus archivos sean guardados con la extensión .php (El Bloc de Notas automáticamente añade
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 algo de tiempo para revisar esta
información.
Example #2 Obtener la información del sistema desde PHP
<?php phpinfo(); ?>
Algo útil
Hagamos ahora algo que puede ser más útil. Vamos a comprobar qué clase de navegador está utilizando
el usuario. 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 especial reservada por PHP que contiene toda la
información del servidor web. Es conocida como Superglobal. Consulte el manual en su
sección titulada Superglobales para más información. Éstas variables especiales fueron
introducidas en la versión » 4.1.0 de PHP. Antes podíamos usar las arrays $HTTP_*_VARS,
9. tales como $HTTP_SERVER_VARS. Aunque éstas han sido marcadas como obsoletas, tales
arrays todavía existen. (También puede echar un vistazo a las notas relacionadas con el código
antiguo.)
To display this variable, you can simply do:
Example #1 Imprimir una variable (Elemento array)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
Un ejemplo del resultado de esta secuencia de comandos sería:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Hay muchos tipos de variables en PHP. En el ejemplo anterior imprimimos una array. Las arrays pueden
ser muy útiles.
$_SERVER es simplemente una variable que se encuentra disponible automáticamente 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 ejemplo de la sección anterior.
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 único echo. Por ejemplo, si quisiéramos detectar el uso de Internet
Explorer, haríamos algo así:
Example #2 Ejemplo usando estructuras de control y functiones
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
echo 'Está usando Internet Explorer.<br />';
}
?>
Un ejemplo del resultado de esta secuencia de comandos sería:
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 parte del manual.
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. En este caso anterior estamos buscando 'MSIE' (llamado
aguja) dentro de $_SERVER['HTTP_USER_AGENT'] (llamado pajar). Si la cadena fue encontrada, la
función devolverá la posición de la aguja relativa al inicio del pajar. De lo contrario devolverá FALSE. Si
no devuelve FALSE, la declaración if se evalúa a TRUE y el código adentro de las llaves {} es ejecutado.
De lo contrario, el código no será ejecutado. Tómese la libertad de crear ejemplos similares usando if,
else, 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.
10. Podemos continuar y demostrar cómo puede saltar adentro y afuera del modo PHP en el medio de un
bloque de código:
Example #3 Mezcla de los modos HTML y PHP
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() debe haber devuelto no falso</h3>
<p>Está usando Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() debió devolver algo diferente de falso</h3>
<p>No está usando Internet Explorer</p>
<?php
}
?>
Un ejemplo del resultado de la secuencia de comandos podría ser:
<h3>strpos() debe haber devuelto falso</h3>
<p>Está usando Internet Explorer</p>
En vez de usar una sentencia PHP echo para demostrar algo, saltamos fuera del código PHP y escribimos
solamente HTML. Este es un punto muy importante y potente que debemos observar aquí, y es que la
fluidez lógica de la secuencia de comandos permanece intacta. Sólamente las partes donde hay bloques
HTML serán enviadas al visor dependiendo del resultado que strstr() devuelva. En otras palabras, si la
cadena MSIE fue encontrada o no.
Uso de Formularios
Otra de las características más importantes de PHP es que gestiona formularios 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 lea la sección del manual titulada Variables fuera de PHP
para más información y ejemplos sobre cómo usar formularios HTML con PHP. Observemos un ejemplo:
Example #1 A simple HTML form
<form action="accion.php" method="post">
<p>Su nombre: <input type="text" name="nombre" /></p>
<p>Su edad: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
No hay nada especial en este formularo, es solamente HTML sin ninguna clase de etiquetas especiales de
ningún tipo. Cuando el usario rellena éste formulario y oprime el botón Submit, una página titulada
action.php es llamada. En este archivo encontrará algo así:
Example #2 Printing data from our form
Hola <?php echo htmlspecialchars($_POST['nombre']); ?>.
11. Usted tiene <?php echo (int)$_POST['edad']; ?> años de edad.
Un ejemplo del resultado de esta secuencia de comandos puede ser:
Hola José. Usted tiene 22 años de edad.
Aparte de las funciones htmlspecialchars() y (int), debería ser obvio de que hace el código.
htmlspecialchars() se asegura que todos los caracteres que son especiales en html sean codificados
adecuadamente de manera que nadie pueda inyectar etiquetas HTML o Javascript en tu página web. El
campo edad, como sabemos que es un número, podemos convertirlo en un integer que automáticamente
se deshará de cualquier carácter no numérico. También puede hacer lo mismo con PHP con la extensión
filter Las variables $_POST['nombre'] y $_POST['edad'] son establecidas automáticamente por PHP.
Anteriormente hemos usado la superglobal $_SERVER y ahora estamos apunto de introducirte la
superglobal $_POST que contiene todos los datos del POST. Dese cuenta que el método de nuestro
formulario es POST. Si usa el método fuera GET entoces los datos del formulario estarían en la
superglobal $_GET. en lugar de POST. En su lugar también puedes usar la superglobal $_REQUEST, si
no le importa el tipo de datos enviados desde el formulario. Contiene toda la información de GET, POST
y COOKIE. Vea también la función import_request_variables().
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well
supported HTML forms for quite some time. While working with XForms is not for beginners, you might
be interested in them. We also have a short introduction to handling data received from XForms in our
features section.
Using old code with new versions of PHP
Ahora que PHP ha crecido y se ha convertido en un lenguaje popular, hay muchos más repositorios y
librerias que contienen código que puede reusar. Los desarrolladores de PHP han tratado en toda medida
que sea compatible con versiones anteriores, es decir, si una secuencia de comandos fue escrita para una
versión antigua en principio funcionaría (idealmente) sin ningún cambio en una versión reciente de PHP.
A la práctica, usualmente algunos cambios son necesarios.
Dos de los cambios mas importantes que afectan el código viejo son:
•
•
La desaparición de las antiguas arrays $HTTP_*_VARS (que usualmente son usadas como
globales al interior de una función o método). Las siguientes variables superglobales que fueron
introducidas en la versión » 4.1.0 de PHP. Son: $_GET, $_POST, $_COOKIE, $_SERVER,
$_FILES, $_ENV, $_REQUEST, y $_SESSION. Las antiguas $HTTP_*_VARS, como
$HTTP_POST_VARS, todavía existen. A partir de PHP 5.0.0, las arrays de tipo long variables
predefinidas se pueden desactivar con la directiva register_long_arrays .
Las variables externas ya no son registradas globalmente de forma automática, por defecto. En
otras palabras, a partir de PHP » 4.2.0, la directiva PHP register_globals está off por defecto en
php.ini. El método preferido para obtener acceso a éstos valores es por medio de las variables
superglobales mencionadas anteriormente. Antiguas secuencias de comandos, libros y tutoriales
antiguos puede que asuman que ésta directiva es está definida como on. Si es así, puede usar, por
ejemplo, $id desde la URL http://www.example.com/foo.php?id=42. Por otra parte, no importa si
el valor de la directiva es on u off, $_GET['id'] está siempre disponible.
Para más información relacionada con estos cambios, puede ver la sección sobre variables predefinidas y
los enlaces que hay dentro.
12. ¿Y ahora qué?
Con sus nuevos conocimientos debería ser capaz de entender la mayoría del manual y de los diversos
scripts de ejemplo disponibles en los archivos. Puede encontrar otros ejemplos en la sección de enlaces de
php.net: » http://www.php.net/links.php.
Para ver varias presentaciones que muestra más acerca de lo que puede hacer PHP, visite los diferentes
sitios con material relacionado a las conferencias realizadas: » http://talks.php.net/
•
•
Introducción
• ¿Qué es PHP?
• ¿Qué se puede hacer con PHP?
Un tutorial sencillo
• What do I need?
• Su primera página con PHP
• Algo útil
• Uso de Formularios
• Using old code with new versions of PHP
• ¿Y ahora qué?
Instalación y configuración
Consideraciones generales de instalación
Antes de empezar la instalación, primero se necesita saber para que se quiere utilizar PHP. Exiten tres
campos principales donde se puede utilizar PHP tal y como se describe en la sección: ¿Qué se puede
hacer con PHP?
•
•
•
Aplicaciones web y sitios web (scripting en el lado servidor)
Scripting en la línea de comandos
Aplicaciones de Escritorio (GUI)
Para la primera forma mencionada, que es la más común, se necesitan tres cosas: PHP, un servidor web y
un navegador web. Seguramente ya dispone del navegador web y dependiendo del el sistema operativo,
quizá ya tiene un servidor web (p.e.j. Apache en Linux y MacOS X; IIS en Windows). Posiblemente esté
alquilando espacio web en una empresa. De esta forma, no se necesita instalar nada, solo tiene que
escribir sus scripts PHP, subirlos al servidor que está alquiando y ver los resultados en su navegador.
En caso de configurar el servidor y PHP por su cuenta, existen dos opciones para el método de conexión
de PHP con el servidor. Para muchos tipos servidores PHP tiene un módulo de interfaz directo (también
llamado SAPI). Incluídos los servidores Apache, Microsoft Internet Information Server, Netscape y
13. iPlanet. Otros muchos servidores tienen soporte para ISAPI, el módulo de interfaz de Microsoft
(OmniHTTPd por ejemplo). Si PHP no tiene un módulo de soporte para su servidor web, siempre puede
usarlo como GCI o FastGCI. Esto significa configurar el servidor para usar el CGI ejecutable de PHP
para procesar cada una de las peticiones a ficheros PHP en el servidor.
Si también está interesado en usar PHP bajo la línea de comandos (p.e.j. escribir que autogeneran
imágenes de forma offline, o procesar ficheros de texto dependiendo de según que argumentos se le pasa),
para este tipo de scripts necesitarás que sea ejecutado en la línea de comandos. Para más información, leer
la sección sobre escribir aplicaciones para la línea de comandos. En este caso, no se necesita servidor o
navegador.
Con PHP también se pueden escribir aplicaciones de escritorio GUI usando la extensión PHP-GTK
extension. No tiene nada que ver con escribir páginas web, ya que no se muestra ningún HTML, pero
gestiona ventanas y objetos con el. Para más información acerca de PHP-GTK, por favor » visita el sitio
dedicado a esta extensión. PHP-GTK no está incluido en la distribución oficial de PHP.
A partir de ahora, esta sección trata de la configuración de PHP para servidores web de Unix y Windows
con módulos de interfaz de servidor o como ejecutables CGI. También se puede encontrar información
sobre ejecutables en la línea de comandos ejecutables en las siguientes secciones.
El código fuente y las distribuciones binarias para Windows pueden encontrarse en » http://www.php.net/
downloads.php. Recomendamos ejegir un » mirror que esté cerca de usted para descargar las
distribuciones.
Installation on Unix systems
Table of Contents
•
•
•
•
•
•
•
•
•
•
•
Apache 1.3.x on Unix systems
Apache 2.x on Unix systems
Lighttpd 1.4 on Unix systems
Caudium
fhttpd related notes
Sun, iPlanet and Netscape servers on Sun Solaris
CGI and command line setups
Notas de instalación específicas para HP-UX
OpenBSD installation notes
Solaris specific installation tips
Notas de instalación en Debian GNU/Linux
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.
14. 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:
•
•
•
•
•
•
Basic Unix skills (being able to operate "make" and a C compiler)
An ANSI C compiler
flex: Version 2.5.4
bison: Version 1.28 (preferred), 1.35, or 1.75
A web server
Any module specific components (such as GD, PDF libs, etc.)
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.
Apache 1.3.x on Unix systems
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.
2.
3.
4.
5.
6.
7.
8.
9.
gunzip apache_xxx.tar.gz
tar -xvf apache_xxx.tar
gunzip php-xxx.tar.gz
tar -xvf php-xxx.tar
cd apache_xxx
./configure --prefix=/www --enable-module=so
make
make install
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
15. 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-development /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-production, 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.
2.
3.
4.
gunzip -c apache_1.3.x.tar.gz | tar xf cd apache_1.3.x
./configure
cd ..
16. 5.
6.
7.
8.
9.
gunzip -c php-5.x.y.tar.gz | tar xf cd php-5.x.y
./configure --with-mysql --with-apache=../apache_1.3.x
make
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-development /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
17. 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 --activatemodule=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:
User nobody
Group "#-1"
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.
Note: Make sure you specify the installed version of apxs when using --withapxs=/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.
Apache 2.x on Unix systems
This section contains notes and hints specific to Apache 2.x installs of PHP on Unix systems.
Warning
We do not recommend using a threaded MPM in production with Apache 2. Use the prefork MPM, which
is the default MPM with Apache 2.0 and 2.2. For information on why, read the related FAQ entry on
using Apache2 with a threaded MPM
The » Apache Documentation is the most authoritative source of information on the Apache 2.x server.
More information about installation options for Apache may be found there.
The most recent version of Apache HTTP Server may be obtained from » Apache download site, and a
fitting PHP version from the above mentioned places. This quick guide covers only the basics to get
started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version
numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN'
should be replaced with the specific version of Apache being used.
18. There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for
choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is
available to you. However, the instructions here will work for either 2.0 or 2.2.
1. Obtain the Apache HTTP server from the location listed above, and unpack it:
gzip -d httpd-2_x_NN.tar.gz
tar -xf httpd-2_x_NN.tar
2. Likewise, obtain and unpack the PHP source:
gunzip php-NN.tar.gz
tar -xf php-NN.tar
3. Build and install Apache. Consult the Apache install documentation for more details on building
Apache.
cd httpd-2_x_NN
./configure --enable-so
make
make install
4. Now you have Apache 2.x.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
5. Now, configure and build PHP. This is where you customize PHP with various options, like which
extensions will be enabled. Run ./configure --help for a list of available options. In our example
we'll do a simple configure with Apache 2 and MySQL support.
If you built Apache from source, as described above, the below example will match your path for
apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs
accordingly. Note that some distros may rename apxs to apxs2.
cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
make
make install
If you decide to change your configure options after installation, you'll need to re-run the
configure, make, and make install 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.
6. Setup your php.ini
cp php.ini-development /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 5.
19. If you instead choose php.ini-production, be certain to read the list of changes within, as they
affect how PHP behaves.
7. 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.
LoadModule php5_module modules/libphp5.so
8. 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
.php 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 handled by the php source filter, and displayed as syntaxhighlighted source code, use this:
<FilesMatch ".phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
mod_rewrite may be used To allow any arbitrary .php file to be displayed as syntax-highlighted
source code, without having to rename or copy it to a .phps file:
RewriteEngine On
RewriteRule (.*.php)s$ $1 [H=application/x-httpd-php-source]
The php source filter should not be enabled on production systems, where it may expose
confidential or otherwise sensitive information embedded in source code.
9. 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.
Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM,
when Apache is built. This is done by adding the following option to the argument passed to ./configure,
in step 3 above:
20. --with-mpm=worker
This should not be undertaken without being aware of the consequences of this decision, and having at
least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules
discusses MPMs in a great deal more detail.
Note: The Apache MultiViews FAQ discusses using multiviews with PHP.
Note: To build a multithreaded version of Apache, the target system must support threads. In
this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this
configuration, not all extensions will be available. The recommended setup is to build Apache
with the default prefork MPM-Module.
Lighttpd 1.4 on Unix systems
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
PHP 5.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).
Letting Lighttpd spawn php processes
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
21. 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).
Spawning with spawn-fcgi
Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.
Spawning php-cgi
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"
Connecting to remote FCGI instances
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 ))
)
22. Caudium
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
PHP4.so. Also make sure that
caudium/server/lib/[pike-version]/PHP4.so
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.
fhttpd related notes
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.
Sun, iPlanet and Netscape servers on Sun Solaris
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
23. 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.
1. Install the following packages from » http://www.sunfreeware.com/ or another download site:
•
autoconf-2.13
•
automake-1.4
•
bison-1_25-sol26-sparc-local
•
flex-2_5_4a-sol26-sparc-local
•
gcc-2_95_2-sol26-sparc-local
•
gzip-1.2.4-sol26-sparc-local
•
m4-1_4-sol26-sparc-local
•
make-3_76_1-sol26-sparc-local
•
mysql-3.23.24-beta (if you want mysql support)
•
perl-5_005_03-sol26-sparc-local
•
tar-1.13 (GNU tar)
2. Make sure your path includes the proper directories
PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system
export PATH.
3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
4. tar xvf php-x.x.x.tar
5. Change to your extracted PHP directory: cd ../php-x.x.x
6. 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
7. Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some
additional configuration steps.
Configuration Instructions for Sun/iPlanet/Netscape
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/.
1. Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php
2. 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.
24. 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"]
(PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your
web server config directory.
3. 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>
(PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example
you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For
boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g.
zlib.output_compression=1 instead of zlib.output_compression="On"
4. 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>
After that you can configure a directory in the Administration server and assign it the style xhttpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming
files to .html.
5. 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>
6. To use PHP Authentication on a single directory, add the following:
<Object ppath="d:pathtoauthenticateddir*">
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").
25. CGI environment and recommended modifications in php.ini
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
Special use for error pages or self-made directory listings (PHP >= 4.3.3)
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...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with
yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script
can get the HTTP status code with $_SERVER['ERROR_TYPE'].
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...]
For both error and directory listing pages the original URI and translated URI are in the variables
$_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].
Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)
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!!!
26. CGI and command line setups
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.
Warning
Al usar el modo CGI, su 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.
Testing
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.
Using Variables
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'.
Notas de instalación específicas para HP-UX
Esta sección contiene notas y consejos específicos para instalar PHP sobre sistemas HP-UX.
Existen dos opciones principales para instalar PHP sobre sistemas HP-UX. Ya sea compilarlo, o instalar
un binario precompilado.
Los paquetes oficiales precompilados se localizan aquí: » http://software.hp.com/
Hasta que esta sección del manual sea reescrita, la documentación acerca de compilar PHP (y las
extensiones relacionadas) sobre sistemas HP-UX ha sido removida. Por ahora, favor de considerar la
lectura de los siguientes recursos externos: » Building Apache and PHP on HP-UX 11.11
27. OpenBSD installation notes
This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.
Using Binary Packages
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 php4imap-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.
Using Ports
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.
Common Problems
•
•
The default install of Apache runs inside a » chroot(2) jail, which will restrict PHP scripts to
accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for
PHP session files to be stored, or use an alternative session backend. In addition, database sockets
need to be placed inside the jail or listen on the localhost interface. If you use network functions,
some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into
/var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot
directories, so no special modification is needed there. More information on the OpenBSD Apache
is available in the » OpenBSD FAQ.
The OpenBSD 3.6 package for the » gd extension requires XFree86 to be installed. If you do not
28. wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz
package instead.
Older Releases
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).
Solaris specific installation tips
This section contains notes and hints specific to installing PHP on Solaris systems.
Required software
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:
•
•
•
•
•
•
•
•
•
•
•
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
In addition, you will need to install (and possibly compile) any additional software specific to your
configuration, such as Oracle or MySQL.
Using Packages
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
Notas de instalación en Debian GNU/Linux
Esta sección contiene notas y consejos específicos para instalar PHP sobre » Debian GNU/Linux.
Mientras que las instrucciones para construir PHP sobre Unix se aplican a Debian también, esta página
del manual contiene información específica para otras opciones, tales como utilizar ya sea los comandos
29. apt-get o aptitude. En esta página del manual estos dos comandos se pueden utilizar indistintamente.
Utilizando APT
Primero, nótese que otros paquetes relacionados podrían ser deseables como libapache2-mod-php5 para
integración con Apache 2, y php-pear para PEAR.
Segundo, antes de instalar un paquete, es sensato asegurarse de que la lista de paquetes está al día.
Típicamente, esto se realiza ejecutando el comando apt-get update.
Example #1 Ejemplo de Instalación en Debian con Apache 2
# apt-get install php5-common libapache2-mod-php5 php5-cli
APT instalará automáticamente el módulo PHP 5 para Apache 2 junto con todas sus dependencias, y
luego lo activará. Apache debería reiniciarse para que los cambios tengan efecto. Por ejemplo:
Example #2 Deteniendo e iniciando Apache una vez que PHP está instalado
# /etc/init.d/apache2 stop
# /etc/init.d/apache2 start
Un mejor control de la configuración
En la sección anterior, PHP se instaló únicamente con los módulos principales. Es muy probable que se
deseen módulos adicionales, tales como MySQL, cURL, GD, etc. Estos también pueden ser instalados vía
el comando apt-get.
Example #3 Métodos para listar paquetes relacionados con PHP 5
# apt-cache search php5
# aptitude search php5
# aptitude search php5 |grep -i mysql
Los ejemplos mostrarán una gran cantidad de paquetes incluyendo varios específicos a PHP como php5cgi, php5-cli y php5-dev. Determine cuales son necesarios e instálelos como cualquier otro ya sea con
apt-get o aptitude. Y ya que Debian realiza revisión de dependencias, preguntará por ellos, así que por
ejemplo para instalar MySQL y cURL:
Example #4 Instalar PHP con MySQL, cURL
# apt-get install php5-mysql php5-curl
APT agregará automáticamente las líneas apropiadas a los diferentes ficheros relacionados con php.ini
como /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. y dependiendo de la extensión, le agregará
registros similares a extension=foo.so. De cualquier manera, reiniciar el servidor web (como es Apache)
es requerido antes de que estos cambios tengan efecto.
Problemas Frecuentes
•
•
Si los scripts de PHP no se están interpretando por el servidor web, entonces es probable que PHP
no haya sido agregado al fichero de configuración del servidor web, que en Debian puede ser /etc/
apache2/apache2.conf o algo semejante. Véase el manual de Debian para mayores detalles.
Si una extensión fue aparentemente instalada y aún así las funciones no aparecen definidas,
30. •
asegurar de que el fichero ini apropiado está siendo cargado y/o que el servidor web fue reiniciado
después de la instalación.
Hay dos comandos básicos para instalar paquetes en Debian (y otras variantes de linux): apt-get y
aptitude. Pero, explicar las sutiles diferencias entre estos comandos va más allá del alcance de este
manual.
Installation on Mac OS X
Table of Contents
•
•
•
•
Using Packages
Using the bundled PHP
Compiling for OS X Server
Installing for Apache on MacOS X Client
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.
Using Packages
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:
•
•
•
•
MacPorts: » http://www.macports.org/
Entropy: » http://www.entropy.ch/software/macosx/php/
Fink: » http://www.finkproject.org/
Homebrew: » http://github.com/mxcl/homebrew
Using the bundled PHP
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
31. 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:
1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/
apache2/httpd.conf Using Finder or Spotlight to find this file may prove difficult as by default it's
private and owned by the root user.
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 /private/etc/apache2/httpd.conf
Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents
the Ctrl key.
Note: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP
and Apache. As such, the Apache configuration file on legacy machines may be
/etc/httpd/httpd.conf.
2. 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 php5_module libexec/httpd/libphp5.so
# AddModule mod_php5.c
Notice the location/path. When building PHP in the future, the above files should be replaced or
commented out.
3. 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_php5.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>
Note: Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which
case the above instructions will differ slightly by changing 5's to 4's.
4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf.
Typically index.php and index.html are used. By default index.php is enabled because it's also in
the PHP check shown above. Adjust accordingly.
5. Set the php.ini location or use the default A typical default location on Mac OS X is
32. /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used,
PHP will use all default values. See also the related FAQ on finding php.ini.
6. Locate or set the DocumentRoot This is the root directory for all the web files. Files in this
directory are served from the web server so the PHP files will parse as PHP before outputting
them to the browser. A typical default path is /Library/WebServer/Documents but this can be set
to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is
/Users/yourusername/Sites
7. Create a phpinfo() file
The phpinfo() function will display information about PHP. Consider creating a file in the
DocumentRoot with the following PHP code:
<?php phpinfo(); ?>
8. Restart Apache, and load the PHP file created above To restart, either execute sudo apachectl
graceful in the shell or stop/start the "Personal Web Server" option in the OS X System
Preferences. By default, loading local files in the browser will have an URL like so:
http://localhost/info.php Or using the DocumentRoot in the user directory is another option and
would end up looking like: http://localhost/~yourusername/info.php
The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up
the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP
version of this PHP binary. A call to phpinfo() will also reveal this information.
Compiling for OS X Server
Mac OS X Server install
1. Get the latest distributions of Apache and PHP.
2. Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr
--localstatedir=/var
--mandir=/usr/share/man
--libexecdir=/System/Library/Apache/Modules
--iconsdir=/System/Library/Apache/Icons
-includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers
--enable-shared=max
--enable-module=most
--target=apache
3. If you want the compiler to do some optimization, you may also want to add this line:
setenv OPTIM=-O2
4. Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr
--sysconfdir=/etc
--localstatedir=/var
--mandir=/usr/share/man
--with-xml
--with-apache=/src/apache_1.3.12
33. If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --withapache string, put in the path to your apache source directory, for example /src/apache_1.3.12.
5. Type make and make install. This will add a directory to your Apache source directory under
src/modules/php4.
6. Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr
--localstatedir=/var
--mandir=/usr/share/man
--libexecdir=/System/Library/Apache/Modules
--iconsdir=/System/Library/Apache/Icons
-includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers
--enable-shared=max
--enable-module=most
--target=apache
--activate-module=src/modules/php4/libphp4.a
You may get a message telling you that libmodphp4.a is out of date. If so, go to the
src/modules/php4 directory inside your Apache source directory and run this command: ranlib
libmodphp4.a. Then go back to the root of the Apache source directory and run the above
configure command again. That'll bring the link table up to date. Run make and make install
again.
7. Copy and rename the php.ini-development file to your bin directory from your PHP 4 source
directory: cp php.ini-development /usr/local/bin/php.ini or (if your don't
have a local directory) cp php.ini-development /usr/bin/php.ini.
Installing for Apache on MacOS X Client
The following instructions will help you install a PHP module for the Apache web server included in
MacOS X using the MacOS GUI. This version includes MySQL, PostgreSQL, and iODBC database
support, cURL, GD, PDFLib, LDAP, and more. These instructions are graciously provided by » Marc
Liyanage.
Warning
Be sure you know what you're doing before advancing beyond this point! You can cause irreparable harm
to your Apache installation otherwise.
Note: These instructions will only work with the original Apache web server as shipped by
Apple. If you re-built or upgraded your Apache, you will have to build your own PHP
module.
To install:
1. For Apache 1.3, download: http://www2.entropy.ch/download/entropyphp-5.2.4-1.tar.gz
2. For Apache 2, download: wget http://www2.entropy.ch/download/entropyphp-5.2.4-1-apache2.tar.gz
3. Unpack the compressed .tar.gz file, but DO NOT USE StuffIt Expander. Instead, use Apple's
BOMArchiveHelper or the command line.
34. 4. Double-click the installer package and follow the directions of the installer application.
That's all! PHP should now be up and running. You can test it by dropping a file named test.php into your
Sites folder in your home directory. Into that file, write this line: <?php phpinfo() ?>.
Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with
information about the PHP module.
Installation on Windows systems
Table of Contents
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Windows Installer (PHP 5.1.0 and earlier)
Windows Installer (PHP 5.2 and later)
Manual Installation Steps
ActiveScript
Microsoft IIS
Microsoft IIS 5.1 and IIS 6.0
Microsoft IIS 7.0 and later
Apache 1.3.x en Microsoft Windows
Apache 2.x on Microsoft Windows
Sun, iPlanet and Netscape servers on Microsoft Windows
OmniHTTPd Server
Sambar Server on Microsoft Windows
Xitami on Microsoft Windows
Building from source
Installation of extensions on Windows
Command Line PHP on Microsoft Windows
This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit
platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32.
Windows 95 is no longer supported as of PHP 4.3.0.
Note: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.
Note: Windows 95 is no longer supported as of PHP 4.3.0.
There are two main ways to install PHP for Windows: either manually or by using the installer.
If you have Microsoft Visual Studio, you can also build PHP from the original source code.
Once you have PHP installed on your Windows system, you may also want to load various extensions for
added functionality.
Warning
There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we
believe that using one of the official windows packages from » http://www.php.net/downloads.php is the
35. best choice to have your system secure and optimized.
Windows Installer (PHP 5.1.0 and earlier)
The Windows PHP installer is available from the downloads page at »
http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it
configures the web server as well. The installer does not include any extra external PHP extensions
(php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.
Note: While the Windows installer is an easy way to make PHP work, it is restricted in many
aspects as, for example, the automatic setup of extensions is not supported. Use of the
installer isn't the preferred method for installing PHP.
First, install your selected HTTP (web) server on your system, and make sure that it works.
Run the executable installer and follow the instructions provided by the installation wizard. Two types of
installation are supported - standard, which provides sensible defaults for all the settings it can, and
advanced, which asks questions as it goes along.
The installation wizard gathers enough information to set up the php.ini file, and configure certain web
servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll
need to configure it manually.
Once the installation has completed, the installer will inform you if you need to restart your system,
restart the server, or just start using PHP.
Warning
Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better
go on the manual way, and set every option carefully. This automatically working setup gives you an
instantly working PHP installation, but it is not meant to be used on online servers.
Windows Installer (PHP 5.2 and later)
The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix
Toolkit (» http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL
extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.
First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed
with one of the following install types.
Normal Install
Run the MSI installer and follow the instructions provided by the installation wizard. You will be
prompted to select the Web Server you wish to configure first, along with any configuration details
needed.
You will then be prompted to select which features and extensions you wish to install and enable. By
36. selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger
whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you
will be able to install all sub-features of the included feature ( for example by selecting this options for the
feature "PDO" you will install all PDO Drivers ).
Warning
It is not recommended to install all extensions by default, since many other them require dependencies
from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be
triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after
installation.
The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web
servers to use PHP. The installer will currently configure IIS, Apache, Xitami, and Sambar Server; if you
are using a different web server you'll need to configure it manually.
Silent Install
The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP
easily. To use silent mode:
msiexec.exe /i php-VERSION-win32-install.msi /q
You can control the install directory by passing it as a parameter to the install. For example, to install to
e:php:
msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:php
You can also use the same syntax to specify the Apache Configuration Directory (APACHEDIR), the
Sambar Server directory (SAMBARDIR), and the Xitami Server directory (XITAMIDIR).
You can also specify what features to install. For example, to install the mysqli extension and the CGI
executable:
msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli
The current list of Features to install is as follows:
MainExecutable - php.exe executable ( no longer available as of PHP 5.2.10/5.3.0; it
is now included by default )
ScriptExecutable - php-win.exe executable
ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2,2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
iis4FastCGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
netserve - NetServe Web Server CGI executable
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
37. Manual - PHP Manual in CHM Format
For more information on installing MSI installers from the command line, visit »
http://msdn.microsoft.com/en-us/library/aa367988.aspx
Upgrading PHP with the Install
To upgrade, run the installer either graphically or from the command line as normal. The installer will
read your current install options, remove your old installation, and reinstall PHP with the same options as
before. It is recommended that you use this method of keeping PHP updated instead of manually
replacing the files in the installation directory.
Manual Installation Steps
This section contains instructions for manually installing and configuring PHP on Microsoft Windows.
For the instructions on how to use PHP installer to setup and configure PHP and a web server on
Windows refer to Windows Installer (PHP 5.2 and later).
Selecting and downloading the PHP distribution package
Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are
several different versions of the zip package - chose the version that is suitable for the web server being
used:
•
If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread
Safe;
•
If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.
Note: VC9 Versions are compiled with the Visual Studio 2008 compiler and have
improvements in performance and stability. The VC9 versions require you to have the »
Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.
The PHP package structure and content
Unpack the content of the zip archive into a directory of your choice, for example C:PHP. The directory
and file structure extracted from the zip will look as below:
Example #1 PHP 5 package structure
c:php
|
+--dev
| |
| |-php5ts.lib
|
+--ext
| |
| |-php_bz2.dll
| |
-- php5.lib in non thread safe version
-- extension DLLs for PHP
38. | |-php_cpdf.dll
| |
| |-...
|
+--extras
|
+--pear
|
|
|-go-pear.bat
|
|-...
|
|-php-cgi.exe
|
|-php-win.exe
prompt
|
|-php.exe
|
|-...
|
|-php.ini-development
|
|-php.ini-production
|
|-php5apache2_2.dll
|
|-php5apache2_2_filter.dll
|
|-...
|
|-php5ts.dll
version)
|
|-...
-- empty
-- initial copy of PEAR
-- PEAR setup script
-- CGI executable
-- executes scripts without an opened command
-- Command line PHP executable (CLI)
-- default php.ini settings
-- recommended php.ini settings
-- does not exist in non thread safe version
-- does not exist in non thread safe version
-- core PHP DLL ( php5.dll in non thread safe
Below is the list of the modules and executables included in the PHP zip distribution:
•
go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.
•
php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.
•
php-win.exe - the PHP executable for executing PHP scripts without using a command line
window (for example PHP applications that use Windows GUI).
•
php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).
•
php5apache2_2.dll - Apache 2.2.X module.
•
php5apache2_2_filter.dll - Apache 2.2.X filter.
Changing the php.ini file
After the php package content has been extracted, copy the php.ini-production into php.ini in the same
folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that
will require additional configuration steps as described in PHP Configuration.
The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in.
Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these
39. are optional. There are many other directives that may be relevant to your environment - refer to the list
of php.ini directives for more information.
Required directives:
•
extension_dir = <path to extension directory> - The extension_dir needs to point to the directory
where PHP extensions files are stored. The path can be absolute (i.e. "C:PHPext") or relative (i.e.
".ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.
•
extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding
"extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.
•
log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a
service (i.e. syslog) and works in conjunction with the error_log directive below. When running
under IIS, the log_errors should be enabled, with a valid error_log.
•
error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative
path to the file where PHP errors should be logged. This file needs to be writable for the web
server. The most common places for this file are in various TEMP directories, for example
"C:inetpubtempphp-errors.log".
•
cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security
facility required by many other web servers. However, enabling it under IIS will cause the PHP
engine to fail on Windows.
•
cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI
implementation needs this set.
•
fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of
the calling client. This allows IIS to define the security context that the request runs under.
•
fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any
messages of any class are treated by FastCGI as error conditions which will cause IIS to generate
an HTTP 500 exception.
Optional directives
•
max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend
executing any given script. The default for this is 30 seconds. Increase the value of this directive if
PHP application take long time to execute.
•
memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The
default is 128, which is fine for most PHP applications. Some of the more complex ones might
need more.
•
display_errors = Off - This directive tells PHP whether to include any error messages in the
stream that it returns to the Web server. If this is set to "On", then PHP will send whichever
classes of errors that you define with the error_reporting directive back to web server as part of
the error stream. For security reasons it is recommended to set it to "Off" on production servers in
order not to reveal any security sensitive information that is often included in the error messages.
•
open_basedir = <paths to directories, separated by semicolon>, e.g.
openbasedir="C:inetpubwwwroot;C:inetpubtemp". This directive specified the directory paths
where PHP is allowed to perform file system operations. Any file operation outside of the
specified paths will result in an error. This directive is especially useful for locking down the PHP
installation in shared hosting environments to prevent PHP scripts from accessing any files outside
40. of the web site's root directory.
•
upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an
uploaded file and post data respectively. The values of these directives should be increased if PHP
applications need to perform large uploads, such as for example photos or video files.
PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP.
Choose a web server from the table of contents.
In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script.
See Command Line PHP on Microsoft Windows for further details.
ActiveScript
This section contains notes specific to the ActiveScript installation.
ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant
host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet
control.
As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. A DLL for this PECL extension
is currently unavailable. See also the building on Windows section.
Note: You should read the manual installation steps first!
After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the
main PHP folder (e.g. C:php).
After having all the files needed, you must register the DLL on your system. To achieve this, open a
Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing
something like cd C:php. To register the DLL just type regsvr32 php5activescript.dll.
To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and
type:
<job id="test">
<script language="PHPScript">
$WScript->Echo("Hello World!");
</script>
</job>
Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.
Note: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should
replace 'PHPScript' with 'ActivePHP' in the above example.
Note: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same
directory as the .exe that caused it to load. You should create php-activescript.ini and place it
in that folder, if you wish to load extensions, etc.