Anda di halaman 1dari 70

Introduccin

Qu es PHP?
PHP (acrnimo de PHP: Hypertext Preprocessor) es un lenguaje de cdigo 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), pginas PHP contienen HTML con cdigo incluido en el mismo que hace "algo" (en este caso, mostrar "Hola soy un script PHP!). El cdigo PHP est entre medio de etiquetas de comienzo y final especiales<?php y ?> que nos permitirn entrar y salir del "modo PHP". Lo que distingue a PHP de algo lado-cliente como Javascript, es que el cdigo es ejecutado en el servidor, generando HTML y envindolo al cliente. El cliente recibir los resultados de ejecutar el script, sin ninguna posibilidad de determinar qu cdigo 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. Lo mejor de usar PHP es que es extremadamente simple para el principiante, pero a su vez, ofrece muchas caractersticas avanzadas para los programadores profesionales. No sienta miedo de leer la larga lista de caractersticas de PHP, en poco tiempo podr empezar a escribir sus primeros scripts. Aunque el desarrollo de PHP est centrado en programacin de scripts en ladoservidor, se puede utilizar para muchas otras cosas. Siga leyendo y descubra ms sobre PHP en la seccin Qu se puede hacer con PHP? o vaya directo al tutorial de introduccin si solamente est interesado en programacin web.

Qu se puede hacer con PHP?


PHP puede hacer cualquier cosa que se pueda hacer con un script CGI, como procesar la informacin de formularios, generar pginas con contenidos dinmicos, o enviar y recibir cookies. Y esto no es todo, se puede hacer mucho ms. Existen principalmente tres campos en los que se usan scripts en PHP. Scripts del lado-servidor. Este es el campo ms tradicional y el principal foco de trabajo. Se necesitan tres cosas para que esto funcione. El intrprete PHP (CGI mdulo), un servidor web y un navegador. Es necesario hacer funcionar el servidor, con PHP instalado. El resultado del programa PHP se puede obtener a travs del navegador, conectndose con el servidor web. Consultar la seccin Instrucciones de instalacin para ms informacin. Scripts en la lnea de comandos. Puede crear un script PHP y correrlo sin necesidad de un servidor web o navegador. Solamente necesita el intrprete 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 tambin pueden ser usados para tareas simples de procesamiento de texto. Consultar la seccin Usos de PHP en la lnea de comandos para ms informacin. Escribir aplicaciones de interfaz grfica. Probablemente PHP no sea el lenguaje ms apropiado para escribir aplicaciones grficas, pero si conoce bien PHP, y quisiera utilizar algunas caractersticas avanzadas en programas clientes, puede utilizar PHP-GTK para escribir dichos programas. Tambin es posible escribir aplicaciones independientes de una plataforma. PHP-GTK es una extensin de PHP, no disponible en la distribucin principal. Si est interesado en PHP-GTK, puedes visitar las pginas 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 ms. PHP soporta la mayora de servidores web de hoy en da, incluyendo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape e iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene mdulos disponibles para la mayora de los servidores, para aquellos otros que soporten el estndar 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. Tambin tiene la posibilidad de usar programacin procedimental o programacin orientada a objetos. Aunque no todas las caractersticas estndar de la programacin P.O.O. estn implementadaS en PHP 4, muchas bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) estn 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: creacin de imgenes, archivos PDF e incluso pelculas Flash (usando libswf y Ming) sobre la marcha. Tambi puede presentar otros resultados, como XHTML y cualquier otro tipo de ficheros XML. PHP 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 dinmico.

Quizs la caracterstica ms potente y destacable de PHP es su soporte para una gran cantidad de bases de datos. Escribir un interfaz va web para una base de datos es una tarea increblemente simple con PHP. Las siguientes bases de datos estn 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

Tambin tenemos abstraccin de base de datos (llamada PDO) que permite usar de forma transparente cualquier base de datos soportada por la extensin. Adicionalmente, PHP soporta ODBC (el Estndar Abierto de Conexin con Bases de Datos), asi que puede conectarse a cualquier base de datos que soporte tal estndar. PHP tambin cuenta con soporte para comunicarse con otros servicios usando protocolos tales como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos otros. Tambin se pueden crear sockets puros e interactuar usando cualquier otro protocolo. PHP soporta WDDX para el intercambio de datos entre lenguajes de programacin en web. Y hablando de interconexin, PHP puede utilizar objetos Java de forma transparente como objetos PHP Y la extensin de CORBA puede ser utilizada para acceder a objetos remotos. PHP tiene unas caractersticas 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 estndares SAX y DOM y tambin Puede utilizar la extensin XSLT para transformar documentos XML. PHP 5 estandariza todas las extensiones XML en una slida base de libxml2 y extiende las caractersticas establecer aadir SimpleXML y soporte para XMLReader. Para terminar, contamos con muchas otras extensiones muy interesantes, las funciones del motor de bsquedas mnoGoSearch, funciones para pasarelas de IRC, utilidades de compresin (gzip, bz2), conversin de calendarios, traduccin .... Como puede apreciar, esta pgina no es suficiente para enumerar todas las caractersticas y beneficios que PHP ofrece. Consulte las secciones Instalacin de

PHP y Referencia de las funciones para una explicacin de las extensiones mencionadas aqu.

Un tutorial sencillo
Table of Contents
Qu necesito? Su primera pgina con PHP Algo til Uso de Formularios Usando cdigo antiguo en nuevas versiones de PHP Y ahora qu?

A continuacin, nos gustara mostrate las bases de PHP en un corto y sencillo tutorial. Este documento explica cmo crear pginas web dinmicas con PHP, aunque PHP no solamente es capaz de crear pginas web. Consulte la seccin titulada Qu se puede hacer con PHP? para ms informacin. Las pginas web que usan PHP se tratan igual que pginas HTML comunes y corrientes, y se pueden crear o editar de la misma manera que normalmente crea pginas HTML.

Qu necesito?
En este manual asumimos que cuenta con un servidor que soporta PHP y que todos los archivos con la extensin .php son usados por PHP. En la mayora de servidores, sta es la extensin 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. Mrelo de esta manera, los archivos PHP son tan simples como archivos de HTML con el aadido de una nueva familia de etiquetas que permiten todo tipo de cosas. La mayora de las compaas de hospedaje de pginas web ofrecen el soporte que necesita para usar PHP, pero si por alguna razn ellos no lo hacen, considere leer la seccin titulada Recursos PHP para ms informacin acerca de compaas 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 ms seguro es que tambin quiera instalar una base de datos como MySQL. Instlelos de forma independientemente o bien puede elegir una manera ms sencilla. Nuestro manual contiene Instrucciones de instalacin de PHP (asumiendo que tiene algn tipo de servidor web ya configurado). En el caso que tenga problemas con la instalacin, sugerimos que haga sus preguntas en nuestra lista de correo de instalacin. Si elige la manera ms sencilla, entonces localice paquete pre-configurado 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 aptget.

Su primera pgina con PHP


Comienze por crear un archivo llamado hola.php y pngalo en el "directorio raz" (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 configuracin 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 pgina como esta. Lo nico que muestra es: Hola mundo usando la funcin 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 extensin ".php", el cul 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 ningn resultado, preguntando si deseaba descargar el archivo, o mostr todo el archivo como texto, lo ms seguro es que PHP no se encuentra habilitado en su servidor. Pdale a su administrador que active esta funcin usando el captulo titulado Instalacin en el manual. Si est trabajando localmente, lea tambin el captulo dedicado a la instalacin para asegurarse de que todo est configurado apropiadamente. Asegrese que est accediendo al fichero va http a travs 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 mltiples opciones de Soporte de PHP. El objetivo de este ejemplo es demostrar cmo puede usar el formato especial de las etiquetas PHP. En este ejemplo usamos <?php para indicar el inicio de la etiqueta PHP. Despus indicamos la sentencia y abandonamos el modo PHP usando ?>. Puede salir de PHP y regresar cuantas veces lo desee usando este mtodo. Para

ms informacin, puede leer la seccin en el manual titulada Sintaxis bsica de PHP. Note: sobre los avances de lnea Los avances de lnia tienen poco sentido en HTML, igualmente sigue siendo buena idea hacer que el cdigo HTML se vea limpio y bien, poniendo avances de lnea. PHP automticamente eliminar los avances de lnea puestos inmediatamente despus de cerrar ?>. Esto puede ser 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 despus de cerrar ?> para forzar el mostrar un espacio y un avance de lnea , o se puede poner un avance de lnea explcitamente en el ltimo echo o print dentro de tu bloque en PHP. Note: acerca de editores de texto Hay muchos editores de texto y Entornos Integrados de Desarrollo (IDE por sus siglas en Ingls) 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 pgina mencionada anteriormente, y comunique su recomendacin 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: 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: 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 extensin .php (El Bloc de Notas automticamente aade la extensin .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 opcin "Todos los archivos *.*". Aqu puede escribir el nombre del archivo sin las comillas. Ahora que ha creado un pequeo script de PHP que funciona correctamente, es hora de trabajar con el script de PHP ms famoso; vamos a hacer una llamada a la funcin phpinfo() para obtener informacin acerca de su sistema y configuracin como las variables predefinidas disponibles, los mdulos utilizados por PHP, y las diferentes opciones de configuracin. Tomemos algo de tiempo para revisar esta informacin. Example #2 Obtener la informacin del sistema desde PHP <?php phpinfo(); ?>

Algo til
Hagamos ahora algo que puede ser ms til. Vamos a comprobar qu clase de navegador est utilizando el usuario. Para hacerlo, vamos a consultar la informacin que el navegador nos enva como parte de su peticin HTTP. Esta informacin es guardada en una variable. Las variables siempre comienzan con un signo de dlar ("$") en PHP. La variable que vamos a utilizar en esta situacin es $_SERVER['HTTP_USER_AGENT']. Note: $_SERVER es una variable especial reservada por PHP que contiene toda la informacin del servidor web. Es conocida como Superglobal. Consulte el manual en su seccin titulada Superglobales para ms informacin. stas variables especiales fueron introducidas en la versin 4.1.0 de PHP. Antes podamos usar las arrays $HTTP_*_VARS, tales como $HTTP_SERVER_VARS. Aunque stas han sido marcadas como obsoletas, tales arrays todava existen. (Tambin puede echar un vistazo a las notas relacionadas con el cdigo antiguo.) Para mostrar esta variable, se puede simplemente hacer: Example #1 Imprimir una variable (Elemento array) <?php echo $_SERVER['HTTP_USER_AGENT']; ?> Un ejemplo del resultado de esta secuencia de comandos sera: 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 automticamente en PHP. Puede encontrar una lista en la seccin titulada Variables Reservadas del manual, o puede generar una lista completa creando un archivo como el ejemplo de la seccin anterior. Puede usar ms de un declaracin PHP dentro de una etiqueta PHP, y crear pequeos segmentos de cdigo que pueden hacer ms que un nico echo. Por ejemplo, si quisiramos detectar el uso de Internet Explorer, haramos 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 sera: Est usando Internet Explorer.<br /> A continuacin introduciremos un par de conceptos nuevos. Tenemos una declaracin if. Si est familiarizado con la sintaxis bsica del lenguaje C, esto se vera lgico, Pero si no entiende C, u otros lenguajes de programacin donde encuentra la sintaxis usada anteriormente, probablemente debera conseguir un

libro que le introduzca mejor a PHP, y lea los primeros captulos, o tambin puede ver la parte del manual titulada Referencia del lenguaje parte del manual. El segundo concepto que introducimos fue la funcin llamada strstr(). strstr() es una funcin 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 funcin devolver la posicin de la aguja relativa al inicio del pajar. De lo contrario devolver FALSE. Si no devuelve FALSE, la declaracin if se evala a TRUE y el cdigo adentro de las llaves {} es ejecutado. De lo contrario, el cdigo no ser ejecutado. Tmese la libertad de crear ejemplos similares usando if, else, y otras funciones como strtoupper() y strlen(). Cada pgina del manual contiene ejemplos que puede usar. Si no est seguro sobre el modo de uso stas funciones, es recomendable que lea las pginas del manual tituladas Cmo leer una definicin de funcin y la seccin relacionada a Funciones en PHP. Podemos continuar y demostrar cmo puede saltar adentro y afuera del modo PHP en el medio de un bloque de cdigo: 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 podra 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 cdigo PHP y escribimos solamente HTML. Este es un punto muy importante y potente que debemos observar aqu, y es que la fluidez lgica de la secuencia de comandos permanece intacta. Slamente las partes donde hay bloques HTML sern 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 caractersticas ms importantes de PHP es que gestiona formularios HTML. El concepto bsico que es importante entender es que cualquier elemento de los formularios estar disponible automticamente en su cdigo PHP. Por favor lea la seccin del manual titulada Variables fuera de PHP para ms informacin y ejemplos sobre cmo 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 ningn tipo. Cuando el usario rellena ste formulario y oprime el botn Submit, una pgina titulada action.php es llamada. En este archivo encontrar algo as: Example #2 Printing data from our form Hola <?php echo htmlspecialchars($_POST['nombre']); ?>. Usted tiene <?php echo (int)$_POST['edad']; ?> aos de edad. Un ejemplo del resultado de esta secuencia de comandos puede ser: Hola Jos. Usted tiene 22 aos de edad. Aparte de las funciones htmlspecialchars() y (int), debera ser obvio de que hace el cdigo. 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 pgina web. El campo edad, como sabemos que es un nmero, podemos convertirlo en un integer que automticamente se deshar de cualquier carcter no numrico. Tambin puede hacer lo mismo con PHP con la extensin filter Las variables $_POST['nombre'] y $_POST['edad'] son establecidas automticamente 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 mtodo de nuestro formulario es POST. Si usa el mtodo fuera GET entoces los datos del formulario estaran en la superglobal $_GET. en lugar de POST. En su lugar tambin puedes usar la superglobal $_REQUEST, si no le importa el tipo de datos enviados desde el formulario. Contiene toda la informacin de GET, POST y COOKIE. Vea tambin la funcin 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.

Usando cdigo antiguo en nuevas versiones de PHP Last updated: Fri, 16 Jul 2010
User Contributed Notes

Algo til

Uso de Formularios arnel_milan at hotmail dot com 29-Mar-2008 05:27 I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below : <form action="blah.php" method="POST"> <table> <tr> <td>Name:</td> <td><input type="text" name="name"></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="Submit_btn" id="Submit_btn" value="Send"> </td> </tr> </table> </form> This very simple code triggers the "Not Acceptable Error" on PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server. However to fix this below is the right code: <form action="blah.php" method="POST"> <table> <tr> <td>Name:</td> <td><input type="text" name="name"></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="Submitbtn" id="Submit_btn" value="Send"> </td> </tr> </table> </form> The only problem that took me hours to find out is the "_" in the Submit Button. Hope this help!

Usando cdigo antiguo en nuevas versiones de PHP


Ahora que PHP ha crecido y se ha convertido en un lenguaje popular, hay muchos ms repositorios y librerias que contienen cdigo 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 versin antigua en principio funcionara (idealmente) sin ningn cambio en una versin reciente de PHP. A la prctica, usualmente algunos cambios son necesarios. Dos de los cambios mas importantes que afectan el cdigo viejo son: La desaparicin de las antiguas arrays $HTTP_*_VARS (que usualmente son usadas como globales al interior de una funcin o mtodo). Las siguientes

variables superglobales que fueron introducidas en la versin 4.1.0 de PHP. Son: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, y $_SESSION. Las antiguas $HTTP_*_VARS, como $HTTP_POST_VARS, todava 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 automtica, 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 mtodo 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 ms informacin relacionada con estos cambios, puede ver la seccin sobre variables predefinidas y los enlaces que hay dentro

Y ahora qu?
Con sus nuevos conocimientos debera ser capaz de entender la mayora del manual y de los diversos scripts de ejemplo disponibles en los archivos. Puede encontrar otros ejemplos en la seccin de enlaces de php.net: http://www.php.net/links.php. Para ver varias presentaciones que muestra ms acerca de lo que puede hacer PHP, visite los diferentes sitios con material relacionado a las conferencias realizadas: http://talks.php.net/

INSTALACIN Y CONFIGURACIN

Consideraciones generales de instalacin


Antes de empezar la instalacin, 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 seccin: Qu se puede hacer con PHP? Aplicaciones web y sitios web (scripting en el lado servidor) Scripting en la lnea de comandos Aplicaciones de Escritorio (GUI)

Para la primera forma mencionada, que es la ms comn, 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 mtodo de conexin de PHP con el servidor. Para muchos tipos servidores PHP tiene un mdulo de interfaz directo (tambin llamado SAPI). Includos los servidores Apache, Microsoft Internet Information Server, Netscape y iPlanet. Otros muchos servidores tienen soporte para ISAPI, el mdulo de interfaz de Microsoft (OmniHTTPd por ejemplo). Si PHP no tiene un mdulo 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 tambin est interesado en usar PHP bajo la lnea de comandos (p.e.j. escribir que autogeneran imgenes de forma offline, o procesar ficheros de texto dependiendo de segn que argumentos se le pasa), para este tipo de scripts necesitars que sea ejecutado en la lnea de comandos. Para ms informacin, leer la seccin sobre escribir aplicaciones para la lnea de comandos. En este caso, no se necesita servidor o navegador. Con PHP tambin se pueden escribir aplicaciones de escritorio GUI usando la extensin PHP-GTK extension. No tiene nada que ver con escribir pginas web, ya que no se muestra ningn HTML, pero gestiona ventanas y objetos con el. Para ms informacin acerca de PHP-GTK, por favor visita el sitio dedicado a esta extensin. PHP-GTK no est incluido en la distribucin oficial de PHP. A partir de ahora, esta seccin trata de la configuracin de PHP para servidores web de Unix y Windows con mdulos de interfaz de servidor o como ejecutables CGI. Tambin se puede encontrar informacin sobre ejecutables en la lnea de comandos ejecutables en las siguientes secciones. El cdigo 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.

Esta seccin le guiar a travs de la configuracin general e instalacin de PHP sobre sistemas Unix. Asegrese de investigar cualquier seccin especfica a su plataforma o servidor web antes de comenzar el proceso. Tal como el manual lo esboza en la seccin Consideraciones generales de instalacin, se est tratando principalmente con configuraciones de PHP centradas en web en esta seccin, aunque tambin se cubrir el preparar PHP para usarse en lnea de comando. Existen varias maneras de instalar PHP para la plataforma Unix, ya sea con un proceso de compilar y configurar, o a travs de varios mtodos pre-empaquetados. Esta documentacin est enfocada principalmente alrededor del proceso de compilar y configurar PHP. Muchos sistemas estilo Unix tienen algn tipo de sistema de instalacin de paquetes. Esto puede ayudar en preparar una configuracin standard, pero si se requiere tener un conjunto diferente de caractersticas (tales como un servidor seguro, o un manejador diferente de base de datos), podra ser necesario construir PHP y/o el servidor web. Si no se est familiarizado con la construccin y el compilado de su propio software, vale la pena revisar para ver si alguien ya ha construido una versin empaquetada de PHP con las caractersticas que se necesitan. Conocimientos y software necesarios para compilar: Habilidades bsicas en Unix (se capaz de operar "make" y un compilador de C) Un compilador ANSI C flex: Versin 2.5.4 bison: Versin 1.28 (preferente), 1.35, o 1.75 Un servidor web Cualquier componente especfico para mdulos (tales como GD, PDF libreras, etc.)

El proceso inicial de preparacin y configuracin de PHP es controlado por el uso de las opciones de lnea de comando del script configure. Es posible obtener una lista de todas las opciones disponibles junto con una descripcin corta ejecutando ./configure --help. El manual documenta las diferentes opciones por separado. Se encontrarn las opciones principales en el apndice, mientras que las diferentes opciones especficas de las extensiones se describen en las pginas de referencia. Cuando PHP est configurado, se est listo para compilar el mdulo y/o ejecutables. El comando make debera hacerse cargo de esto. Si falla y no se puede encontrar el porque, vase la seccin de problemas.

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. gunzip apache_xxx.tar.gz 2. tar -xvf apache_xxx.tar 3. gunzip php-xxx.tar.gz 4. tar -xvf php-xxx.tar 5. cd apache_xxx 6. ./configure --prefix=/www --enable-module=so 7. make 8. make install 9. cd ../php-xxx 10. Now, configure your PHP. This is where you customize your PHP with various options, like which extensions will be enabled. Do a ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 1 and MySQL support. Your path to apxs may differ from our example. ./configure --with-mysql --with-apxs=/www/bin/apxs 11. make 12. make install If you decide to change your configure options after installation, you only need to repeat the last three steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed. Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more. 13. Setup your php.ini file: cp php.ini-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. LoadModule php5_module libexec/libphp5.so 15. And in the AddModule section of httpd.conf, somewhere under the ClearModuleList, add this: AddModule mod_php5.c 16. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse the .php extension as PHP. You could have any extension(s) parse as PHP by simply adding more, with each separated by a space. We'll add .phtml to demonstrate.

AddType application/x-httpd-php .php .phtml It's also common to setup the .phps extension to show highlighted PHP source, this can be done with: AddType application/x-httpd-php-source .phps 17. Use your normal procedure for starting the Apache server. (You must stop and restart the server, not just cause the server to reload by using a HUP or USR1 signal.) Alternatively, to install PHP as a static object: Example #2 Installation Instructions (Static Module Installation for Apache) for PHP 1. gunzip -c apache_1.3.x.tar.gz | tar xf 2. cd apache_1.3.x 3. ./configure 4. cd .. 5. 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 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 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 libphp5.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function. ./configure --with-apache=/path/to/apache_source --with-pgsql This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary. 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. 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: 2. gzip -d httpd-2_x_NN.tar.gz 3. tar -xf httpd-2_x_NN.tar 4. Likewise, obtain and unpack the PHP source: 5. gunzip php-NN.tar.gz 6. tar -xf php-NN.tar 7. Build and install Apache. Consult the Apache install documentation for more details on building Apache. 8. cd httpd-2_x_NN 9. ./configure --enable-so 10. make 11. make install 12. 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.: 13. /usr/local/apache2/bin/apachectl start and stop the server to go on with the configuration for PHP: /usr/local/apache2/bin/apachectl stop

14. 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. 15. Setup your php.ini 16. 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. If you instead choose php.ini-production, be certain to read the list of changes within, as they affect how PHP behaves. 17. 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 18. 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. 19. <FilesMatch \.php$> 20. 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 syntax-highlighted 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. 21. Use your normal procedure for starting the Apache server, e.g.: 22. /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:

--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 continuing.

Lighttpd trac to learn how to install Lighttpd properly before

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 --enablefastcgi. 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 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 )) )

User Contributed Notes

Lighttpd 1.4 on Unix systems Ant P.

10-Jun-2010 02:09
If PHP_FCGI_MAX_REQUESTS isn't given, the default value is 500. askroot at gmail dot com

07-Apr-2009 09:32
<-- Start --> #!/bin/bash /usr/bin/spawn-fcgi \

-s /var/run/lighttpd/php-fastcgi-kr.php.net.socket \ -f "/usr/bin/php-cgi -c /etc/php-kr.php.net.ini" \ -u lighttpd \ -g lighttpd \ -C 4 \ -P /var/run/spawn-fcgi-kr.php.net.pid \ -F 12 <-- End --> lighttpd 1.5 - Config <-- Start --> $HTTP["host"] =~ "^(www.)?kr.php.net" { server.document-root = "/home/kr.php.net" accesslog.filename = "/var/log/lighttpd/kr.php.net-access_log" index-file.names = ( "index.php", "index.html", "index.htm" ) url.access-deny = ( "~", ".inc", ".htaccess" ) server.error-handler-404 = "/error.php" alias.url = ( "/FAQ.php" => "/home/kr.php.net/manual/kr/faq.php", "/stats" => "/home/kr.php.net-stats" ) setenv.add-environment = ( "MIRROR_LANGUAGE" => "kr", "MIRROR_STATS" => "1" ) $HTTP["url"] =~ "\.php$" { proxy-core.balancer = "round-robin" proxy-core.allow-x-sendfile = "enable" proxy-core.protocol = "fastcgi" proxy-core.backends = ( "unix:/var/run/lighttpd/php-fastcgikr.php.net.socket" ) proxy-core.max-pool-size = 16 } } <-- End -->

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 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-xxxversion/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: 7. ./configure --with-mysql=/usr/local/mysql \ 8. --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc 9. 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/httpsservername/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): 2. type=magnus-internal/x-httpd-php exts=php 3. 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. 4. Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" 5. 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.

6. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf): 7. <Object name="default"> 8. . 9. . 10. . 11. .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines 12. Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] 13. . 14. . 15. </Object> (PHP >= 4.3.3) As additional parameters you can add some special php.inivalues, 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" 16. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory): 17. <Object name="x-httpd-php"> 18. ObjectType fn="force-type" type="magnus-internal/x-httpd-php" 19. Service fn=php4_execute [inikey=value inikey=value ...] 20. </Object> After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html. 21. 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: 22. <Object name="default"> 23. AuthTrans fn=php4_auth_trans 24. . 25. . 26. . 27. </Object> 28. To use PHP Authentication on a single directory, add the following: 29. <Object ppath="d:\path\to\authenticated\dir\*"> 30. AuthTrans fn=php4_auth_trans 31. </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").

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!!!

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 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-xxxversion/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: 7. ./configure --with-mysql=/usr/local/mysql \ 8. --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc 9. 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/httpsservername/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): 2. type=magnus-internal/x-httpd-php exts=php 3. 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. 4. Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" 5. 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. 6. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf): 7. <Object name="default"> 8. . 9. . 10. . 11. .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines 12. Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] 13. . 14. . 15. </Object> (PHP >= 4.3.3) As additional parameters you can add some special php.inivalues, 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" 16. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory): 17. <Object name="x-httpd-php"> 18. ObjectType fn="force-type" type="magnus-internal/x-httpd-php" 19. Service fn=php4_execute [inikey=value inikey=value ...] 20. </Object> After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

21. 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: 22. <Object name="default"> 23. AuthTrans fn=php4_auth_trans 24. . 25. . 26. . 27. </Object> 28. To use PHP Authentication on a single directory, add the following: 29. <Object ppath="d:\path\to\authenticated\dir\*"> 30. AuthTrans fn=php4_auth_trans 31. </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").

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!!!

Notas de instalacin especficas para HP-UX


Esta seccin contiene notas y consejos especficos 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 seccin del manual sea reescrita, la documentacin 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

OpenBSD installation notes


This section contains notes and hints specific to installing PHP on 3.6.

OpenBSD

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 php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini. Example #1 OpenBSD Package Install Example # pkg_add php4-core-4.3.8.tgz # /usr/local/sbin/phpxs -s # cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini (add in mysql) # pkg_add php4-mysql-4.3.8.tgz # /usr/local/sbin/phpxs -a mysql (add in imap) # pkg_add php4-imap-4.3.8.tgz # /usr/local/sbin/phpxs -a imap (remove mysql as a test) # pkg_delete php4-mysql-4.3.8 # /usr/local/sbin/phpxs -r mysql (install the PEAR libraries) # pkg_add php4-pear-4.3.8.tgz Read the packages(7) manual page for more information about binary packages on OpenBSD.

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 subpackages 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 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 sugerencias especficas de instalacin


Esta seccin contiene notas y sugerencias especficas para la instalacin de PHP en sistemas Solaris.

Software necesario
La instalacion Solaris carece con frecuencia de los compiladores de C y sus herramientas relacionadas. Lea las preguntas frecuentes para obtener informacin sobre porqu usar versiones GNU de algunas de estas herramientas. El software requerido es el siguiente: gcc (recomendado, otros compiladores de C pueden trabajar) make flex bison m4 autoconf automake perl gzip tar GNU sed

Adems, usted tendr que instalar (y posiblemente compilar) cualquier software adicional especfico para la configuracin, tales como Oracle o MySQL.

Empleo de paquetes
Se puede simplificar el procesao de intalacin de Solarismediante el uso de pkgadd para instalar la mayora de sus componentes necesarios.

Notas de instalacin en Debian GNU/Linux


Esta seccin contiene notas y consejos especficos para instalar PHP sobre Debian GNU/Linux. Warning No se ofrece soporte de builds no oficiales de terceros. Cualquier bug debe ser informado al equipo de Debian a no ser que puedan reproducirse usando los ltimos builds de nuestra zona de descargas. Mientras que las instrucciones para construir PHP sobre Unix se aplican a Debian tambin, esta pgina del manual contiene informacin especfica para otras opciones, tales como utilizar ya sea los comandos apt-get o aptitude. En esta pgina del manual estos dos comandos se pueden utilizar indistintamente.

Utilizando APT
Primero, ntese que otros paquetes relacionados podran ser deseables como libapache2-mod-php5 para integracin 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 da. Tpicamente, esto se realiza ejecutando el comando apt-get update. Example #1 Ejemplo de Instalacin en Debian con Apache 2 # apt-get install php5-common libapache2-mod-php5 php5-cli APT instalar automticamente el mdulo PHP 5 para Apache 2 junto con todas sus dependencias, y luego lo activar. Apache debera 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 configuracin


En la seccin anterior, PHP se instal nicamente con los mdulos principales. Es muy probable que se deseen mdulos adicionales, tales como MySQL, cURL, GD, etc. Estos tambin pueden ser instalados va el comando apt-get. Example #3 Mtodos para listar paquetes relacionados con PHP 5 # apt-cache search php5 # aptitude search php5 # aptitude search php5 |grep -i mysql

Los ejemplos mostrarn una gran cantidad de paquetes incluyendo varios especficos a PHP como php5-cgi, php5-cli y php5-dev. Determine cuales son necesarios e instlelos como cualquier otro ya sea con apt-get o aptitude. Y ya que Debian realiza revisin 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 automticamente las lneas 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 extensin, 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 estn interpretando por el servidor web, entonces es probable que PHP no haya sido agregado al fichero de configuracin del servidor web, que en Debian puede ser /etc/apache2/apache2.conf o algo semejante. Vase el manual de Debian para mayores detalles. Si una extensin fue aparentemente instalada y an as las funciones no aparecen definidas, asegurar de que el fichero ini apropiado est siendo cargado y/o que el servidor web fue reiniciado despus de la instalacin. Hay dos comandos bsicos para instalar paquetes en Debian (y otras variantes de linux): apt-get y aptitude. Pero, explicar las sutiles diferencias entre estos comandos va ms all del alcance de este manual.

Instalacin en Mac OS X

Solaris sugerencias especficas de instalacin

Last updated: Fri, 16 Jul 2010

User Contributed Notes

Notas de instalacin en Debian GNU/Linux juraj at jurajsplayground dot com

09-May-2009 12:59
On Ubuntu (since 7.04), rather do: sudo tasksel install lamp-server Details: https://help.ubuntu.com/community/ApacheMySQLPHP tranzbit at yahoo dot com

02-May-2009 08:59

On Ubuntu: sudo apt-get install apache2 php5 mysql-client-5.0 mysql-server-5.0 phpmyadmin libapache2-mod-php5 libapache2-mod-auth-mysql php5-mysql then restart the computer/start mysql manually From:

http://ubuntuforums.org/showthread.php?t=186492
John Fisher

09-Feb-2007 12:53
With Apache2 and Php4 under Debian Sarge there is an extra configuration file : /etc/apache2/sites-available/default This file is not clearly documented, at least not for noobs, in Apache docs. It overrides the conf file in the way you expect the /etc/apache2/conf.d/apache2-doc to do according to the README. Add ExecCGI to it to get rid of "Options ExecCGI is off in this directory" errors. Ben A.

18-Dec-2005 06:53
Although there are no PHP 5 packages for Debian 3.1 (aka "stable" or "sarge"), there are currently PHP 5 packages for "testing"/"etch" and "unstable"/"sid". Installation works the same way. Also, the same process can be used for Ubuntu, but note that some of the packages may be in the "universe" section instead of "main". jimmychan at example dot com

24-Oct-2005 05:01
If you are using Debian 3.1 It is total, the php.ini is under /etc/php4/apache2 Since Debian 3.1 default apache is 2.0.x version, this one just said how to change the php.ini under apache 1.3.x If you need enable the ext. need manaul edit php.ini, and comment out # of what the ext. that you want to enable Of course, you much first install the ext. first by like that apt-get install php4-gd php4-mysql ......

INSTALACIN EN SISTEMAS WINDOWS

Esta seccin se aplica a Windows 98/Me y Windows NT/2000/XP/2003. PHP no funciona en plataformas de 16 bits, como Windows 3.1 y, a veces nos referimos a las plataformas soportadas por Windows como Win32. Windows 95 ya no se admite a partir de PHP 4.3.0. Note: Windows 98/ME/NT4 ya no se admite a partir de PHP 5.3.0. Note: Windows 95 ya no se admite a partir de PHP 4.3.0. Hay dos maneras principales de instalar PHP para Windows: de forma manual o mediante el instalador. Si tiene Microsoft Visual Studio, tambin puede construir PHP desde el cdigo fuente original. Una vez que haya instalado PHP en su sistema Windows, tambin puede querer cargar varias extensiones para mayor funcionalidad. Warning Hay varios instaladores todo-en-uno a travs de Internet, pero ninguno de esos son avalados por la PHP.net, ya que creemos que usando uno de los paquetes oficiales de Windows de http://www.php.net/downloads.php es la mejor opcin para que el sistema este seguro y optimizado.

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 selecting "Will be installed on local hard drive" in the dropdown 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 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 | | | +--ext | | | | | | | +--extras | -- empty | |-php_bz2.dll | |-php_cpdf.dll | |-... -- extension DLLs for PHP | |-php5ts.lib -- php5.lib in non thread safe version

+--pear | | |-go-pear.bat | |-... | |-php-cgi.exe | |-php-win.exe command prompt | |-php.exe | |-... | |-php.ini-development | |-php.ini-production | |-php5apache2_2.dll version | |-php5apache2_2_filter.dll version | |-... | |-php5ts.dll safe version) | |-...

-- initial copy of PEAR

-- PEAR setup script

-- CGI executable

-- executes scripts without an opened

-- Command line PHP executable (CLI)

-- default php.ini settings

-- recommended php.ini settings

-- does not exist in non thread safe

-- does not exist in non thread safe

-- core PHP DLL ( php5.dll in non thread

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 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:\PHP\ext") 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:\inetpub\temp\phperrors.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:\inetpub\wwwroot;C:\inetpub\temp". 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 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
Esta seccin contiene notas especficas de la instalacin ActiveScript. ActiveScript es slo para Windows una SAPI que le permite el uso de script PHP en cualquier host ActiveScript compatible, como Windows Script Host, ASP/ASP.NET, Windows Script Components o Control Scriptlet. A partir de PHP 5.0.1, ActiveScript se ha trasladado a el repositorio PECL. No hay una DLL disponible para esta extensin PECL actualmente. Vea tambin la seccin Compilando en Windows. Note: Usted debe leer primero el Manual de instalacin paso a paso

Despus de instalar PHP, debe descargar el ActiveScript DLL (php5activescript.dll) y colocarlo en el directorio principal de PHP (e.g. C:\php). Despus de tener todos los ficheros necesarios, debe registrar el DLL en el sistema. Para ello, abra una ventana del smbolo del sistema (que se encuentra en el del men inicio). A continuacin, vaya al directorio de PHP escribiendo algo as como cd C:\php. Para registrar el DLL simplemente escriba regsvr32 php5activescript.dll. Para probar si el ActiveScript est trabajando, se crea un nuevo fichero, llamado test.wsf (La extensin es muy importante) y escriba: <job id="test"> <script language="PHPScript"> $WScript->Echo("Hola Mundo!"); </script> </job> Guarde y haga doble clic en el fichero. Si usted recibe una pequea ventana diciendo "Hola Mundo!" ha terminado. Note: En PHP 4, el motor fue nombrado "ActivePHP', as que si est usando PHP 4, se debe reemplazar 'PHPScript' por 'ActivePHP' en el ejemplo anterior. Note: ActiveScript no utiliza el fichero predeterminado php.ini . En su lugar, se ver slo en el mismo directorio que el .exe que causaba la carga. Se debe crear php-activescript.ini y colocarlo en esa carpeta, si desea cargar las extensiones, etc

User Contributed Notes

ActiveScript maflorez at cognox dot com 15-Oct-2006 05:43 Other option is this: Copy this text, save with extension .reg and execute. ***** Begin of file don't include Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\.phs] @="PHPScript" [HKEY_CLASSES_ROOT\PHPScript] @="PHPScript" "EditFlags"=dword:00000000 "AlwaysShowExt"="" "BrowserFlags"=dword:00000008 [HKEY_CLASSES_ROOT\PHPScript\shell] @="Run" [HKEY_CLASSES_ROOT\PHPScript\shell\Run] [HKEY_CLASSES_ROOT\PHPScript\shell\Run\command] @="wscript.exe //E:PHPScript \"%1\" \"%2\""

[HKEY_CLASSES_ROOT\PHPScript\shell\Run\ddeexec] [HKEY_CLASSES_ROOT\PHPScript\shell\Run\ddeexec\Application] @="wscript" [HKEY_CLASSES_ROOT\PHPScript\shell\Run\ddeexec\Topic] @="System" ***** End of file don't include garfiel_fr at tiscali dot fr 11-May-2005 04:06 There is another way to execute a PHP ActiveScript: 1/ In explorer, open menu "Tools/Folder Options" 2/ Go to tab "File Type" 3/ Click on "New" button and enter a file extension ( PHS for my sample ), you can also select "PHPScript" in "Advanced" button. Then OK, a new file extension is registered. 4/ In tab "File Type" select the new extension and click on button "Advanced". A new dialog box is open. 5/ Click on "New" button and fill edit box with: Action: Run Application to use: C:\WIN2K\system32\wscript.exe //E:PHPScript "%1" "%2" That's all !! Now, your code don't need XML tag at the begining. Hello work in test.phs will be: $WScript->Echo("Bonjour le monde !");

Microsoft IIS
Esta seccin contiene instrucciones especficas de la instalacin de PHP en Microsoft Internet Information Services (IIS). Instalacin manual de PHP en Microsoft IIS 5.1 y IIS 6.0 Instalacin manual de PHP en Microsoft IIS 7.0 y posteriores

Microsoft IIS 5.1 y IIS 6.0


Esta seccin contiene instrucciones para configurar en forma manual Internet Information Services (IIS) 5.1 y IIS 6.0 para trabajar con PHP en Microsoft Windows XP y Windows Server 2003. Para obtener instrucciones sobre la configuracin de IIS 7.0 y versiones posteriores de Windows Vista , Windows Server 2008, Windows 7 y Windows Server 2008 R2 referirse a Microsoft IIS y posteriores.

7.0

Configurar IIS para procesar solicitudes de PHP


Descarga e instala PHP de acuerdo a las instrucciones descritas en

manual de instalacin

detallado

Note: Non-thread-safe build de PHP se recomienda cuando se utiliza IIS. nonthread-safe builds estn disponibles en PHP para Windows: Binarios y

Fuentes.

Configure el CGI- y configure FastCGI-specific en el archivo php.ini como se muestra a continuacin: Example #1 Configuracin CGI y FastCGI en php.ini fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0 Descargue e instale Microsoft FastCGI extensin para IIS 5.1 y 6.0. La extensin est disponible para 32-bit y plataformas de 64-bit - seleccionar el paquete de descarga adecuada para la plataforma. Configure la extensin FastCGI para manejar las solicitudes especficas de PHP ejecutando el comando que se muestra a continuacin. Vuelva a colocar el valor de el parmetro "-path" con la ruta absoluta del fichero en el fichero php-cgi.exe. Example #2 Configuracin de la extensin FastCGI para manejar las solicitudes de PHP cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^ -extension:php -path:"C:\PHP\php-cgi.exe" Este comando crear un script de mapeo IIS para el fichero de extensin *.php , lo que resultar en todas las URLs que terminan con .php siendo manejado por la extensin FastCGI. Asimismo, se configurar la extensin FastCGI a usar en el ejecutable php-cgi.exe para procesar las solicitudes de PHP. Note: En este punto la necesidad de instalacin y configuracin de los pasos se han completado. El resto de instrucciones a continuacin son opcionales, pero altamente recomendable para lograr una funcionalidad ptima y el rendimiento de PHP en IIS.

Suplantacin y acceso a ficheros del sistema


Se recomienda habilitar la suplantacin FastCGI en PHP cuando este utilizando IIS. Esto es controlado por la directiva fastcgi.impersonate en el fichero php.ini. Cuando suplantacin est activado, PHP realizar todas las operaciones de ficheros de sistema en favor de la cuenta de usuario que se ha determinado por la autentificacin de IIS. Esta asegura que, incluso si el mismo proceso PHP se comparte entre diferentes sitios web IIS, los scripts PHP en estos sitios web no podr acceder a los otros fichero ' siempre y cuando use cuentas de usuario diferentes utilizado para la autenticacin IIS en cada sitio web. Por ejemplo IIS 5.1 and IIS 6.0, en su configuracin predeterminada, se ha habilitado la autenticacin annima con una funcin de cuenta de usuario IUSR_<MACHINE_NAME> utilizado como una identidad por defecto. Esto significa que para que IIS puede ejecutar scripts PHP, es necesario concedera la cuenta IIUSR_<MACHINE_NAME> permiso de lectura en estos scripts. Si las aplicaciones PHP necesitan realizar operaciones de escritura sobre determinados ficheros o

escribir ficheros en algunas carpetas a continuacin la cuenta IUSR_<MACHINE_NAME> debe tener permiso para escribir en ellos. Para determinar qu cuenta de usuario es utilizado por IIS autenticacin annima, siga estos pasos: 1. En el men Inicio de Windows seleccione "Run:", type "inetmgr" y haga clic en "Ok"; 2. Expanda la lista de sitios web en el nodo "Web Sites" en la vista de rbol, haga clic derecho en el sitio web que se est utilizando y seleccionar "Properties"; 3. Haga clic en "Directory Security" tab; 4. Tome nota de un "User name:" campo en el "Authentication Methods" dialog

Para modificar la configuracin de permisos en ficheros y carpetas, utilice la interfaz de usuario de el Explorador de Windows o el comando icacls. Example #3 Configuracin del fichero de los permisos de acceso icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Establecerindex.php como un documento predeterminado en IIS


Los documentos por defecto de IIS se utilizan para las solicitudes HTTP que no especifican un nombre de documento. Con las aplicaciones PHP, index.php suele

actuar como un documento predeterminado. Para aadir index.php a la lista de documentos predeterminados IIS, siga estos pasos: 1. En el men Inicio de Windows seleccione "Run:", teclee "inetmgr" y haga clic en "Ok"; 2. Haga clic derecho en el nodo ""Web Sites" de la vista de rbol y seleccione "Properties"; 3. Haga clic en "Documents" tab; 4. Haga clic en el botn "Add..." y enter en "index.php" para el " Contenido de la pgina por defecto :".

FastCGI y Reciclaje de configuracin de PHP


Configurar la extensin IIS FastCGI para el reciclaje de procesos PHP utilizando los comandos de abajo. Los controles de configuracin de FastCGI instanceMaxRequests nmero de solicitudes que sern procesadas por un solo proceso php-cgi.exe antes de el cierre de la extensin FastCGI. La variable PHP de entorno PHP_FCGI_MAX_REQUESTS controla cuntas peticiones de un nico proceso php-cgi.exe se encargar antes de que se recicle as mismo. Asegrese de que el valor especificado por la configuracin FastCGI InstanceMaxRequests es menor o igual al valor especificado para PHP_FCGI_MAX_REQUESTS. Example #4 Configuracin FastCGI y reciclaje PHP cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^

-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuracin de los ajustes de tiempo de espera FastCGI


Aumentar la configuracin de tiempo de espera para la extensin FastCGI si hay aplicaciones que llevan mucho tiempo ejecutar scripts PHP. Los dos valores a ajsutar de los controles de tiempos de espera son ActivityTimeout y RequestTimeout. Vase Configuracin de Extensin FastCGI para IIS 6.0 para ms informacin sobre los ajustes. Example #5 Configuracin de los ajustes de tiempo de espera FastCGI cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -RequestTimeout:90

cambiar la ubicacin del fichero php.ini


PHP busca para el fichero php.ini en varios lugares y es posible cambiar las ubicaciones predeterminadas de el fichero php.ini utilizando la variable de entorno PHPRC. Las instrucciones PHP para cargar el fichero de configuracin desde una ubicacin personalizada, ejecute el comando que se muestra a continuacin. La ruta de acceso absoluta al directorio con el fichero php.ini debe ser especifica con un valor de variable de entorno PHPRC. Example #6 Cambiar la ubicacin del fichero php.ini cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHPRC:"C:\Some\Directory\"

Microsoft IIS 7.0 y posteriores


Esta seccin contiene instrucciones para configurar en forma manual Internet Information Services (IIS) 7.0 y posteriores para trabajar con PHP en Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. Para obtener instrucciones sobre la configuracin de IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refirase a Microsoft IIS 5.1 and IIS 6.0.

Habilitacin de apoyo FastCGI en IIS


Mdulo FastCGI est deshabilitado en la instalacin por defecto de IIS. Los pasos para que pueda variar segn la versin de Windows se est utilizando. Para activar el soporte FastCGI en Windows Vista SP1 y Windows 7: 1. En el menu de inicio de Windows seleccione "Run:", teclee "optionalfeatures.exe" y click "Ok"; 2. En el "Windows Features" cuadro de dilogo "Internet Information Services", "World Wide Web Services", " Caracteristicas Desarrollo de aplicaciones " y luego permitir que el "CGI" checkbox; 3. Haga clic en Aceptar y espere hasta que se complete la instalacin

Para activar el soporte FastCGI en Windows Server 2008 y Windows Server 2008 R2: 1. En el men Inicio de Windows elegir "Run:", teclee "CompMgmtLauncher" y click "Ok"; 2. En el "Web Server (IIS)" El rol no est presente en el marco del "Roles" nodo, a continuacin, aadir haciendo clic en "Adicionar Roles"; 3. Si la "Web Server (IIS)" role esta presente, entonces haga click "Add Role Services" y luego permitir que el "CGI" casilla de verificacin en grupo "Desarrollo de Aplicaciones" ; 4. Click "Next" y luego "Install" ay espere a que la instalacin se complete.

Configurar IIS para procesar las solicitudes de PHP


Descargue e instale PHP de acuerdo a las instrucciones descritas en

installation steps

manual

Note: No construir thread-safe de PHP se recomienda cuando IIS utilizando. El nothread-safe crea estn disponibles en PHP para Windows: binarios y

fuentes.
Configure el CGI y la configuracin especfica de FastCGI php.ini fichero como se muestra a continuacin: Example #1 CGI y FastCGI en la configuracin php.ini fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0 Configurar la asignacin de IIS controlador para PHP utilizando la interfaz de usuario Administrador de IIS o una herramienta de lnea de comandos.

El uso de IIS interfaz de usuario de Manager para crear una asignacin de controlador para PHP Siga estos pasos para crear una asignacin de controlador de IIS para PHP en la interfaz de usuario Administrador de IIS: 1. En el men Inicio de Windows elegir "Run:", escriba "inetmgr" y click "Ok"; 2. En la interfaz de usuario de IIS Manager, seleccione el nodo de servidor en el "Connections" vista de rbol; 3. En el "Caractersticas" Pgina de abrir el "Handler Mappings" feature;

4. En el "Actions" haga click en panel "Add Module Mapping..."; 5. En el "Add Module Mapping" dilogo entre lo siguiente: Solicitud de ruta: *.php Modulo: FastCgiModule Ejecutable: C:\[Path to PHP installation]\php-cgi.exe Nombre: PHP_via_FastCGI 6. Haga Click en "Solicitar Restricciones" botn y luego configurar la asignacin de invocar controlador slo si la solicitud se asigna a un archivo o una carpeta; 7. Haga clic en Aceptar en todos los cuadros de dilogo para guardar la configuracin.

Utilizando la herramienta de lnea de comandos para crear una asignacin de controlador para PHP Utilice el comando mostrado a continuacin para crear un grupo de IIS FastCGI proceso que utilizar php-cgi.exe ejecutable para la tramitacin de solicitudes de PHP. Vuelva a colocar el valor del parmetro fullPath con la ruta absoluta al fichero php-cgi.exe. Example #2 >Creacin del proceso del grupo IIS FastCGI %windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^ /+[fullPath='c:\PHP\php-cgi.exe']

Configurar IIS PHP para manejar las peticiones concretas de la ejecucin del comando que se muestra a continuacin. Vuelva a colocar el valor del parmetro scriptProcessor con la ruta de acceso absoluta al fichero php-cgi.exe. Example #3 Creacin de mapas manejador de peticiones PHP

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^ /+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^ scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

Este comando crea una asignacin de controlador de IIS para la extensin de archivo *.php, lo que resultar en todas las direcciones URL que terminan con. Php siendo manejado por el mdulo FastCGI. Note: En este punto la necesidad de instalacin y configuracin de los pasos se han completado. Las instrucciones a continuacin son opcionales, pero altamente recomendable para lograr una funcionalidad ptima y el rendimiento de PHP en IIS.

Suplantacin de identidad y acceso a archivos del sistema


Se recomienda habilitar la suplantacin en PHP FastCGI cuando IIS utilizando. Esta est controlado por la directiva fastcgi.impersonate en el fichero php.ini. Cuando est habilitada la suplantacin, PHP realizar todas las operaciones del sistema de ficheros en nombre de la cuenta de usuario que ha sido determinado por la autentificacin de IIS. Esto asegura que, aunque el proceso mismo PHP es compartido a travs de diferentes sitios web IIS, los scripts PHP en los sitios web no ser capaz de acceder a los dems ficheros, siempre y cuando las cuentas de usuario se utilizan para la autenticacin de IIS en cada sitio web. Por ejemplo IIS 7, en su configuracin por defecto, se ha habilitado la autenticacin annima con incorporada IUSR cuenta de usuario utilizada como una identidad por defecto. Esto significa que para que IIS ejecutar scripts PHP, es necesario conceder a la cuenta IUSR permiso de lectura en estos scripts. Si las aplicaciones PHP necesidad de realizar operaciones de escritura de ciertos ficheros o escribir ficheros en una carpetas entonces cuenta IUSR debe tener permiso para escribir en ellos. Para determinar qu cuenta de usuario se utiliza como una identidad annima en IIS 7 utilice el siguiente comando. Vuelva a colocar el "Sitio Web predeterminado" con el nombre del sitio Web de IIS que utiliza. En la produccin configuracin XML aspecto de elemento para el atributo userName. Example #4 La determinacin de la cuenta utilizada como IIS identidad annima %windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^ /section:anonymousAuthentication <system.webServer> <security> <authentication> <anonymousAuthentication enabled="true" userName="IUSR" />

</authentication> </security> </system.webServer>

Note: Si el atributo userName no est presente en el elemento anonymousAuthentication, o si se establece una cadena vaca, entonces significa que la identidad del grupo de aplicaciones se utiliza como un identidad annima para ese sitio web. Para modificar la configuracin de permisos de archivos y carpetas, utilice la interfaz de usuario del Explorador de Windows o comando icacls. Example #5 Configuracin de archivo de los permisos de acceso icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Establecer index.php como un documento predeterminado en IIS


Los documentos por defecto de IIS se utilizan para las solicitudes HTTP que no se especifica un nombre de documento. Con las aplicaciones PHP,index.php por lo general acta como un documento predeterminado. Para aadir index.php a la lista de los documentos por defecto de IIS, utilice este comando: Example #6 Establecer index.php como un documento predeterminado en IIS %windir%\system32\inetsrv\appcmd.exe set config ^ -section:system.webServer/defaultDocument /+"files.[value='index.php']" ^ /commit:apphost

FastCGI y configuracin de PHP Reciclaje


Configurar la configuracin de IIS FastCGI PHP para el reciclaje de los procesos mediante los comandos de abajo. La configuracin FastCGI instanceMaxRequests controla cuntas peticiones se procesado por un solo peoceso php-cgi.exe antes de IIS se cierra. La variable de entorno PHP PHP_FCGI_MAX_REQUESTS controla el nmero pide una sola proceso php-cgi.exe se encargar antes de que se recicla s misma. Asegrese de que el valor especificado para la configuracin FastCGI InstanceMaxRequests es menor o igual al valor especificado para PHP_FCGI_MAX_REQUESTS. Example #7 Configuracin de PHP FastCGI y el reciclaje %windir%\system32\inetsrv\appcmd.exe set config section:system.webServer/fastCgi ^

/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000 %windir%\system32\inetsrv\appcmd.exe set config section:system.webServer/fastCgi ^ /+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^ [name='PHP_FCGI_MAX_REQUESTS',value='10000']"

FastCGI ajustes de tiempo de espera


Aumentar el tiempo de espera para la configuracin de FastCGI si se espera tener a largo ejecutar scripts PHP. Los dos valores que los tiempos de espera de control activityTimeout y requestTimeout. Utilice los comandos siguientes para cambiar la configuracin de tiempo de espera. Asegrese de sustituir el valor en el parmetro a fullPath contendr la ruta absoluta a el fichero php-cgi.exe. Example #8 Configuracin de los ajustes de tiempo de espera FastCGI %windir%\system32\inetsrv\appcmd.exe set config section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90" /commit:apphost %windir%\system32\inetsrv\appcmd.exe set config section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90" /commit:apphost

Cambiar la ubicacin del fichero php.ini


PHP busca el fichero php.ini en varios lugares y es posible cambiar las ubicaciones predeterminadas del fichero php.ini utilizando variable de entorno PHPRC. Encomendar a PHP para cargar el archivo de configuracin desde una ubicacin personalizada, ejecute el comando se muestra a continuacin. La ruta de acceso absoluta al directorio con el fichero php.ini debe ser especifica como un valor de variable de entorno PHPRC. Example #9 Cambiar la ubicacin del fichero php.ini appcmd.exe set config -section:system.webServer/fastCgi ^

/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^ [name='PHPRC',value='C:\Some\Directory\']" /commit:apphost

Apache 1.3.x en Microsoft Windows

Esta seccin contiene notas y sugerencias especficas para Apache 1.3.x instaladas con PHP en sistemas Microsoft Windows. Tambin hay instrucciones y notas para Apache 2 en una nueva pgina. Note: Por favor lea primero

el manual de instalacin

Hay dos formas de configurar PHP para trabajar con Apache 1.3.x en Windows. La primera es usar CGI binary (php.exe para PHP 4 y php-cgi.exe para PHP 5), la otra es utilizar el mdulo DLL de Apache. En ambos casos se necesita editar httpd.conf para configurar Apache para trabajar con PHP, y despus reiniciar el servidor. Vale la pena resaltar, que el mdulo SAPI ha sido desarrollado mas estable bajo Windows. Se recomienda su uso ms que el binario CGI, ya que es ms trasparente y seguro. Aunque pueden haber algunas variaciones en la configuracin de PHP bajo Apache, estas son sencillas para ser utilizados por el principiante. Por favor consulte la documentacin de Apache para seguir directivas de configuracin. Despus de modificar el archivo de configuracin, recuerde que debe reiniciar el servidor, por ejemplo NET STOP APACHE seguido de NET START APACHE, si ejecuta Apache como un servicio de Windows, o si usa los atajos Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext should be converted to forward slashes: c:/directory/file.ext. A trailing slash may also be necessary for directories.

Instalacin como mdulo de Apache


Se deben agregar las siguientes lneas a su archivo de configuracin Apache httpd.conf Example #1 PHP como mdulo de Apache 1.3.x Se asume que PHP est instalado en c:\php. Ajuste la ruta de acceso si este no es el caso. Para PHP 4: # Adicionar al final de la seccin LoadModule # No olvidar copiar este ficrero desde el directorio sapi! LoadModule php4_module "C:/php/php4apache.dll"

# Adicionar al final de la seccin AddModule AddModule mod_php4.c Para PHP 5:

# Adicionar al final de la seccin LoadModule LoadModule php5_module "C:/php/php5apache.dll"

# Adicionar al final de la seccin AddModule AddModule mod_php5.c Para ambos : # Adicionar esta lnea dentro de la <IfModule Mod_mime.c> condicional brace AddType application/x-httpd-php .php

# Para la sintaxis highlighted .phps files, tambien adicionar AddType application/x-httpd-php-source .phps

Instalacin como un binario CGI


Si se ha descomprimido el paquete PHP C:\php\ como se describe en la seccin Manual de instalacin paso a paso, es necesario insertar estas lneas a su archivo de configuracin de Apache para configurar el binario CGI: Example #2 PHP y Apache 1.3.x como CGI ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php

# Para PHP 4 Action application/x-httpd-php "/php/php.exe"

# Para PHP 5 Action application/x-httpd-php "/php/php-cgi.exe"

# Especifica el directorio donde php.ini esta SetEnv PHPRC C:/php Tenga en cuenta que la segunda lnea en la lista anterior se puede encontrar en las versiones actuales de httpd.conf, pero se comenta. Recordar tambin sustituir el c:\php\ para su ruta de acceso real a PHP. Warning

Al usar el modo CGI, su servidor esta expuesto a diferentes ataques. Por favor, leer la seccin Seguridad con CGI para aprender como defenderse de estos ataques. Si desea presentar archivos de cdigo fuente PHP sintaxis highlighted, no existe la opcin ms conveniente con la versin de PHP como mdulo. Si ha elegido configurar Apache para usar PHP como un binario CGI, tendr que usar la funcin highlight_file(). Para ello se necesita crear un script PHP y agregarle el cdigo <?php highlight_file('some_php_script.php'); ?>.

Apache 2.x en Microsoft Windows


Esta seccin contiene notas y sugerencias especficas de Apache 2.x instaladas con PHP en sistemas Microsoft Windows. Tambin hay instrucciones y notas para usuarios de Apache 1.3.x en una nueva pgina.. Note: Por favor lea primero

el manual de instalacin

Note: Soporte Apache 2.2 Los usuarios de Apache 2.2 deben tener en cuenta que el archivo DLL para Apache 2.2 es llamado php5apache2_2.dll a cambio de php5apache2.dll y slo est disponible para PHP 5.2.0 y posteriores. Ver tambin http://snaps.php.net/ Se le recomienda consultar la Documentacin de Apache Para obtener un conocimiento bsico del servidor Apache 2.x. Tambien considere leer las notas especificas de Windows para Apache 2.x antes de seguir leyendo aqu. Apache 2.x est diseado para ejecutarse en las versiones de Windows designado como servidor de plataforma, tales como Windows NT 4.0, Windows 2000, Windows XP o Windows 7. Aunque Apache 2.x funciona bastante bien en Windows 9x, el soporte en estas plataformas es incompleta, y algunas cosas no funcionan correctamente. No existe un plan para remediar esta situacin. Descargue la versin ms reciente de de PHP. Siga los pasos del Manual integracin de PHP y Apache.

Apache 2.x y un accesorio de la versin de Instalacin y regrese a continuar con la

Hay tres formas de configurar PHP para trabajar con Apache 2.x en Windows. Puede ejecutar PHP como un controlador, como CGI o bajo FastCGI. Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext should be converted to forward slashes: c:/directory/file.ext. A trailing slash may also be necessary for directories.

Instalacin como un controlador de Apache


Es necesario insertar las siguientes lneas en Apache httpd.conf archivo de configuracin para cargar el mdulo PHP para Apache 2.x: Example #1 PHP and Apache 2.x como controlador

# LoadModule php5_module "c:/php/php5apache2.dll" AddHandler application/x-httpd-php .php

# Configurar la ruta de php.ini PHPIniDir "C:/php" Note: Recuerda sustituir la ruta de acceso actual a PHP para el C:/php/ en los ejemplos anteriores. Tenga cuidado en utilizar ya sea php5apache2.dll o php5apache2_2.dll en la directiva LoadModule y verificar que el fichero de referencia se encuentra localizado en la ruta de fichero que se seala en la presente directiva. La configuracin anterior permite habilitar PHP como controlador de cualquier fichero que tiene una extensin .php, aunque existen otras extensiones de fichero. Por ejemplo, un fichero llamadoexample.php.txt ser ejecutado por el controlador de PHP. Para garantizar que slo los ficheros queterminen en .php son ejecutados, se utiliza la siguiente configuracin en su lugar: <FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch>

Ejecutar PHP como CGI


Se debe consultar la Documentacin de ms completa de ejecutar CGI en Apache

Apache CGI para una comprensin

Para ejecutar PHP como CGI, tendrs que colocar los ficheros php-cgi en un directorio designado como directorio CGI usando la directiva ScriptAlias. A continuacin, se nesesita insertar una #! lnea en los ficheros PHP, apuntando a la ubicacin del binario de PHP: Example #2 PHP y Apache 2.x como CGI #!C:/php/php.exe <?php phpinfo(); ?> Warning Al usar el modo CGI, su servidor esta expuesto a diferentes ataques. Por favor, leer la seccin Seguridad con CGI para aprender como defenderse de estos ataques.

Ejecutar PHP bajo FastCGI


Ejecutar PHP bajo FastCGI tiene una serie de ventajas con respecto a ejecutarlo como un CGI. Si lo establece de esta manera es bastante sencillo: Obtener mod_fcgid de http://httpd.apache.org/mod_fcgid/. Los binarios de Win32 estn disponibles para la descargar en ese sitio. Instalar el mdulo de acuerdo con las instrucciones que vienen con l. Configurar el servidor web como se muestra abajo, teniendo cuidado de ajustar cualquier ruta que refleje como se tiene instalado las cosas en el sistema: Example #3 Configurar Apache para ejecutar PHP como FastCGI LoadModule fcgid_module modules/mod_fcgid.so

# Donde est el fichero php.ini? FcgidInitialEnv PHPRC "c:/php"

AddHandler fcgid-script .php FcgidWrapper "c:/php/php-cgi.exe" .php Los ficheros con extensin .php ahora sern ejecutados por PHP FastCGI

Sun, iPlanet and Netscape servers on Microsoft Windows


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 Windows. From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

CGI setup on Sun, iPlanet and Netscape servers


To install PHP as a CGI handler, do the following: Copy php4ts.dll to your systemroot (the directory where you installed Windows) Make a file association from the command line. Type the following two lines: assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).

In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php). Do it for each web server instance you want PHP to run

More details about setting up PHP as a CGI executable can be found here:

http://benoit.noss.free.fr/php/install-php.html
NSAPI setup on Sun, iPlanet and Netscape servers
To install PHP with NSAPI, do the following:

Copy php4ts.dll to your systemroot (the directory where you installed Windows) Make a file association from the command line. Type the following two lines: assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php). Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init. Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/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 configuration directory.

Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines: Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] (PHP >= 4.3.3) As additional parameters you can add some special php.inivalues, 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"

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 x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

Restart your web service and apply changes Do it for each web server instance you want PHP to run

Note: More details about setting up PHP as an NSAPI filter can be found here:

http://benoit.noss.free.fr/php/install-php4.html

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").

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. The problem is, that this function uses some undocumented features from the NSAPI library. Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled. Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled. If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf: Init fn=php4_init ... server_lib="ns-httpdXX.dll" where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one. You can check the status by using the Note: But be warned: Support for

phpinfo() function.

nsapi_virtual() is EXPERIMENTAL!!!

OmniHTTPd Server
This section contains notes and hints specific to OmniHTTPd on Windows. Note: You should read the manual installation steps first! Warning Al usar el modo CGI, su servidor esta expuesto a diferentes ataques. Por favor, leer la seccin Seguridad con CGI para aprender como defenderse de estos ataques. You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

Note: Important for CGI users Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. 1. Install OmniHTTPd server. 2. Right click on the blue OmniHTTPd icon in the system tray and select Properties 3. Click on Web Server Global Settings 4. On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button. 5. On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button. 6. Click OK Repeat steps 2 - 6 for each extension you want to associate with PHP. Note: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.

Sambar Server en Microsoft Windows


Esta seccin contiene notas y consejos especficos a el Servidor Sambar para Windows. Note: Debe leer primero los pasos del manual de instalacin. Esta lista describe cmo configurar el mdulo ISAPI para trabajar con el servidor Sambar en Windows. Busque el archivo llamado mappings.ini (en el directorio de configuracin) en el directorio de instalacin de Sambar. Abra mappings.ini y adicione la siguiente lnea de abajo [ISAPI]: Example #1 Configuracion de Sambar ISAPI #for PHP 4 *.php = c:\php\php4isapi.dll #for PHP 5 *.php = c:\php\php5isapi.dll

(Esta lnea asume que PHP se instal en c:\php.) Ahora reinicie el servidor Sambar para que los cambios surtan efecto.

Note: Si va a usar PHP para comunicarse con los recursos que se celebran en un equipo diferente en la red, entonces usted tendr que modificar la cuenta utilizada por los servicios de el servidor Sambar. La cuenta por defecto utilizado por el Servicio del servidor Sambar es LocalSystem que no tendrn acceso a recursos remotos. La cuenta puede ser modificada mediante el uso de la opcin de servicios de Windows en el Panel de control de las herramientas de administracin.

Xitami en Microsoft Windows


Esta seccin contiene notas y sugerencias especficas para Xitami en Windows. Note: Debe leer primero los pasos del Manual de instalacin. Esta lista describe cmo configurar el PHP CGI binary para trabajar con Xitami en Windows. Note: Importante para los usuarios de CGI Leer las preguntas frecuentes en cgi.force_redirect para ms detalles importantes. Esta directiva se debe establecer a0. Si desea utilizar $_SERVER['PHP_SELF'] tienes que habilitar la directiva cgi.fix_pathinfo. Warning Al usar el modo CGI, su servidor esta expuesto a diferentes ataques. Por favor, leer la seccin Seguridad con CGI para aprender como defenderse de estos ataques. Asegrese de que el servidor web est funcionando, y apunte el navegador a la consola de administracin xitamis (por lo general http://127.0.0.1/admin), Y haga clic en Configuracin. Navegue a los filtros, y ponga la extensin PHP que debe analizar (es decir, .php) en el campo de las extensiones del fichero(.xxx). En el comando del filtro o script coloque la ruta y el nombre de el ejecutable PHP CGI es decir, C:\php\php.exe para PHP 4, o C:\php\php-cgi.exe para PHP 5. Pulse el icono "Guardar". Reinicie el servidor para reflejar los cambios.

Construccin de la fuente
En este captulo se ensea a compilar PHP a partir de fuentes en Windows, usando Microsoft's tools. Para compilar PHP con cygwin, por favor vaya a Instalacin sobre sistemas Unix.

http://wiki.php.net/internals/windows/stepbystepbuild
Consulte la documentacin del Wiki en:

Instalacin de extensiones en Windows


Despus de instalar PHP y un servidor web en Windows, es probable que desee instalar algunas extensiones para mayor funcionalidad. Puede elegir cuales extensiones desea cargar cuando PHP inicia modificando php.ini. Tambin puede cargar un mdulo dinmicamente en el script con dll(). Los DLL para las extensiones PHP tienen el prefijo php_. Algunas extensiones son construidas dentro de la versin de Windows de PHP. Esto significa que los ficheros DLL adicionales, y la extensin directiva, no se utiliza para cargar estas extensiones. En la tabla de Windows las extensiones PHP son enumeradas las extensiones que se requieren, se utilizan, ficheros PHP DLL adicionales. Aqu hay una lista de extensiones construidas:

En PHP 4 (actualizacin de PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML and Zlib En PHP 5 (actualizacin de PHP 5.0.4), existen los siguientes cambios. Contruidos en: DOM, LibXML, Iconv, SimpleXML, SPL and SQLite. Y a continuacin se enumeran los no construidos en: MySQL y Overload. La ubicacin predeterminada de las bsquedas PHP para las extensiones es C:\php4\extensions en PHP 4 y C:\php5 en PHP 5. Para cambiar estos parmetros reflejando la configuracin de PHP, edite el fichero php.ini: Tendr que cambiar los parmetros de la extension_dir para apuntar al directorio donde est la extensin, o donde tenga localizado el fichero php_*.dll. Por ejemplo: extension_dir = C:\php\extensions Habilite la extensin(s) en php.ini que desea utilizar descomentando las siguientes lneas extension=php_*.dll en php.ini. Esto se hace mediante el borrado de la cabecera, desde la extensin que desea cargar. Example #1 Habilitar la extensin Bzip2 para PHP-Windows // cambiar la siguiente lnea de ... ;extension=php_bz2.dll // ... to extension=php_bz2.dll Algunas de las extensiones de archivos necesita DLL extras para trabajar. Un par de ellos se puede encontrar en el paquete de distribucin, en la carpeta C:\php\dlls\ en PHP 4 o en la carpeta principal en PHP 5, pero algunos, por ejemplo Oracle requieren (php_oci8.dll) ficheros DLL que no se incluyen con el paquete de distribucin. Si va a instalar PHP 4, copie el paquete DLL de la carpeta C:\php\dlls a la carpeta principal C:\php. No se olvide de incluir en el sistema C:\php PATH (Este proceso se explica por separado en Preguntas Frecuentes de entrada). Algunos de estos DLLs no se incluye con la distribucin de PHP. Consulta cada pgina de documentacin de las extensiones para ms detalles. Adems, lea el manual seccin titulada Instalacin de extensiones PECL para ms detalles sobre PECL. Un gran nmero de extensiones de PHP se encuentran en PECL, y estas extensiones requieren una descarga independiente .

Note: Si est ejecutando un servidor de la versin de PHP como mdulo recuerde reiniciar su servidor web para reflejar los cambios a php.ini. En la tabla siguiente se describen algunas de las extensiones disponibles y las dlls adicionales.

Extensin php_bz2.dll

Extensiones de PHP Descripcin Funciones de Nada compresin bzip2

Notas

Extensin php_calendar.dll php_crack.dll php_ctype.dll php_curl.dll

php_dba.dll

php_dbase.dll php_dbx.dll php_domxml.dll php_dotnet.dll php_exif.dll

php_fbsql.dll

php_fdf.dll php_filepro.dll php_ftp.dll

php_gd.dll

php_gd2.dll

Extensiones de PHP Descripcin Notas Funciones de Construido a partir de PHP conversin 4.0.3 Calendario Funciones Crack Nada Funciones Construido a partir de PHP familiares ctype 4.3.0 Funciones de la Requiere: libeay32.dll, libreria cliente ssleay32.dll(incluido) URL CURL DBA: Funciones de Capa de abstraccin de la Nada Base de datos (dbm-style) Funciones dBase Nada Funciones dbx PHP <= 4.2.0 Requiere: Funciones DOM libxml2.dll (incluido) PHP >= XML 4.3.0 Requiere: iconv.dll (incluido) Funciones .NET PHP <= 4.1.1 php_mbstring.dll. y, php_exif.dll se debe cargar FuncionesEXIF despus de php_mbstring.dll en php.ini. Funciones PHP <= 4.2.0 FrontBase FDF: Formato de datos de Requiere: fdftk.dll (incluido) formularios de funciones. Funciones filePro Acceso de slo lectura Funciones FTP Incorporado desde PHP 4.0.3 Eliminada en PHP 4.3.2. Tambin tenga en cuenta que Funciones de las funciones de color libreria de imagen verdadero no estn GD disponibles en GD1, utilice en su lugar php_gd2.dll. Funciones de libreria de imagen GD2 GD

Extensiones de PHP Extensin Descripcin Notas PHP <= 4.2.0 requiere gnu_gettext.dll (incluido), php_gettext.dll Funciones Gettext PHP >= 4.2.3 requiere libintl1.dll, iconv.dll (incluido). Funciones php_hyperwave.dll Nada HyperWave Requiere: iconv-1.3.dll Conversin de php_iconv.dll (incluido), PHP >=4.2.1 caracteres ICONV iconv.dll Funciones php_ifx.dll Requiere: Librerias Informix Informix Funciones de php_iisfunc.dll Nada administracion IIS POP3 y Funciones php_imap.dll Nada NNTP IMAP php_ingres.dll Funciones Ingres Requiere: Librerias Ingres Funciones php_interbase.dll Requiere: gds32.dll (incluido) InterBase PHP <= 4.0.6 requiere: php_java.dll Funciones Java jvm.dll (incluido) PHP <= 4.2.0 requiere libsasl.dll (incluido), PHP >= php_ldap.dll Funciones LDAP 4.3.0 requiere libeay32.dll, ssleay32.dll (incluido) Funciones Multiphp_mbstring.dll Nada Byte String Funciones Mcrypt php_mcrypt.dll Requiere: libmcrypt.dll Encryption PHP >= 4.3.0 requiere: php_mhash.dll Funciones Mhash libmhash.dll (incluido) Funciones Requiere: magic.mime php_mime_magic.dll Mimetype (incluido) Funciones para php_ming.dll Nada Flash Ming php_msql.dll Funciones mSQL Requiere: msql.dll (incluido) Requiere: ntwdblib.dll php_mssql.dll Funciones MSSQL (incluido) PHP >= 5.0.0, requiere php_mysql.dll Funciones MySQL libmysql.dll (incluido) PHP >= 5.0.0, requiere php_mysqli.dll Funciones MySQLi libmysql.dll (libmysqli.dll en

Extensin php_oci8.dll php_openssl.dll php_overload.dll php_pdf.dll php_pgsql.dll php_printer.dll php_shmop.dll php_snmp.dll php_soap.dll php_sockets.dll php_sybase_ct.dll php_tidy.dll php_tokenizer.dll php_w32api.dll php_xmlrpc.dll

php_xslt.dll

php_yaz.dll php_zip.dll php_zlib.dll

Extensiones de PHP Descripcin Notas PHP <= 5.0.2) (incluido) Funciones Oracle Requiere: Librerias cliente 8 Oracle 8.1+ Funciones Requiere: libeay32.dll OpenSSL (incluido) Funciones Object Construido a partir de PHP overloading 4.3.0 Funciones PDF Nada Funciones Nada PostgreSQL Funciones Printer Nada Funciones Shared Nada Memory Funciones SNMP Solo NT ! Funciones SOAP PHP >= 5.0.0 Funciones Socket Nada Requiere: librerias cliente Funciones Sybase Sybase Funciones Tidy PHP >= 5.0.0 Funciones Construido a partir de PHP Tokenizer 4.3.0 Funciones W32api Nada Funciones XMLPHP >= 4.2.1 requiere: RPC iconv.dll (incluido) PHP <= 4.2.0 requiere sablot.dll, expat.dll (incluido). Funciones XSLT PHP >= 4.2.1 requiere sablot.dll, expat.dll, iconv.dll (incluido). Funciones YAZ Requiere: yaz.dll (incluido) Ficheros Zip Acceso de slo lectura incluido Funciones de Construido a partir de PHP compresin ZLib 4.3.0

Linea de Comandos PHP en Microsoft Windows


Esta seccin contiene notas y sugerencias especficas para conseguir ejecutar PHP en la lnea de comandos para Windows.

Note: Usted debe leer primero el manual de instalacin Cmo ejecutar PHP desde la lnea de comandos sin hacer ningn cambio a Windows. C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3 Pero hay algunos pasos sencillos que puede seguir para hacer esto simple. Algunas de estas medidas ya se deberan haber tomado, pero se repiten aqu para ser capaz de proporcionar una completa secuencia paso a paso. Aada la ubicacin del ejecutable de PHP (php.exe, php-win.exe o phpcli.exe dependiendo de su versin de PHP y las preferencias de presentacin) a la variable de entorno PATH. Lea ms acerca de cmo aadir el directorio de PHP PATH en la entrada correspondiente de preguntas frecuentes. Adicione la extensin .PHP de la variable de entorno PATHEXT. Esto se puede hacer al mismo tiempo, con la modificacin de la variable de entorno PATH. Siga los mismos pasos como se describe en las Preguntas frecuentes pero habra que modificar la variable de entorno PATHEXTen lugar de la variable de entornoPATH. Note: La posicin en que se coloca el .PHP determina qu secuencia de comandos o programa se ejecuta cuando hay nombre de archivos coincidentes. Por ejemplo, colocar .PHP antes de .BAT har que el script se ejecute, en lugar de el archivo por lotes, si hay un fichero por lotes con el mismo nombre. Asociar la extensin .PHP con un tipo de fichero. Esta se hace ejecutando el siguiente comando: assoc .php=phpfile Asociar el tipo de fichero phpfile con el adecuado ejecutable PHP. Esto se hace ejecutando el siguiente comando: ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2

Si sigue estos pasos permitir ejecutar scripts PHP desde cualquier directorio sin necesidad de escribir el ejecutable PHP o la extensin .PHP y todos los parmetros, ser enviada a el script para el procesamiento. En el ejemplo a continuacin se detallan algunos de los cambios de registro que se puede hacer manualmente. Example #1 Registro de cambios Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php] @="phpfile" "Content Type"="application/php" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile] @="PHP Script" "EditFlags"=dword:00000000 "BrowserFlags"=dword:00000008 "AlwaysShowExt"="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]

@="C:\\PHP5\\php-win.exe0" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell] @="Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open] @="&Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command] @="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2" Con estos cambios el mismo comando se puede escribir como: "C:\PHP Scripts\script" -arg1 -arg2 -arg3 O, si la ruta de acceso "C:\PHP Scripts" est en el variable de entorno PATH: script -arg1 -arg2 -arg3 Note: Hay un pequeo problema si tiene intencin de utilizar esta tcnica y usar scripts PHP como filtro de lnea de comandos, como el ejemplo a continuacin: dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3 o dir | script -arg1 -arg2 -arg3 Es posible que el script simplemente se cuelga y no salga nada. Para hacer esto operacional, es necesario hacer otro cambio en el registro. Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explor er] "InheritConsoleHandles"=dword:00000001 Informacin adicional sobre este tema se pueden encontrar en el artculo de Microsoft: 321788

Anda mungkin juga menyukai