OS X users editing in TextEdit will need to make sure their TextEdit preferences are set to allow plain text files. Under the TextEdit pull-down menu, choose PREFERENCES, then under NEW DOCUMENT ATTRIBUTES in the window that pops up, click PLAIN TEXT.
Then, in the section of that same window called "saving," DESELECT "append .txt extension to plain text files." This will allow you to save your files with a .php extension.
Then close the PREFERENCES window. You're good to go.
Su primera página con PHP
Comienze por crear un archivo llamado hola.php y póngalo en el "directorio raíz" (DOCUMENT_ROOT) con el siguiente contenido:
Ejemplo #1 Nuestro primer script PHP: hola.php
<html>
<head>
<title>Ejemplo PHP</title>
</head>
<body>
<?php echo '<p>Hola Mundo</p>'; ?>
</body>
</html>
Utilice su navegador web para acceder al archivo en su servidor, con la URL terminando en /hola.php. Si está programando localmente este URL será algo como http://localhost/hola.php o http://127.0.0.1/hola.php pero esto depende de la configuración de su servidor web. Si todo está configurado correctamente, el fichero será analizado por PHP y el siguiente contenido aparecerá en su navegador:
<html> <head> <title>Ejemplo PHP</title> </head> <body> <p>Hola mundo</p> </body> </html>
Este script es extremadamente simple y no es necesario usar PHP para crear una página como esta. Lo único que muestra es: Hola mundo usando la sentencia de PHP echo. El fichero no debe ser ejecutable o especial de ninguna forma. El servidor reconoce que este fichero debe ser interpretado por PHP porque estamos usando la extensión ".php", el cuál está configurado para enviarlo a PHP. Piensa como si fuera un fichero HTML normal el cual tiene una serie de etiquetas especiales disponibles con las que puedes hacer muchas cosas interesantes.
Si ha intentado usar este ejemplo y no produjo ningún resultado, preguntando si deseaba descargar el archivo, o mostró todo el archivo como texto, lo más seguro es que PHP no se encuentra habilitado en su servidor. Pídale a su administrador que active esta función usando el capítulo titulado Instalación en el manual. Si está trabajando localmente, lea también el capítulo dedicado a la instalación para asegurarse de que todo esté configurado apropiadamente. Asegúrese que está accediendo al fichero vía http a través del servidor para mostrar el resultado. Si está abriendo el archivo desde el sistema de archivos, entonces probablemente no estará siendo analizado por PHP. Si el problema persiste no dude en usar alguna de las múltiples opciones de » Soporte de PHP.
El objetivo de este ejemplo es demostrar cómo puede usar el formato especial de las etiquetas PHP. En este ejemplo usamos <?php para indicar el inicio de la etiqueta PHP. Después indicamos la sentencia y abandonamos el modo PHP usando ?>. Puede salir de PHP y regresar cuantas veces lo desee usando este método. Para más información, puede leer la sección en el manual titulada Sintaxis básica de PHP.
Nota: sobre los avances de línea
Los avances de línia tienen poco sentido en HTML, igualmente sigue siendo buena idea hacer que el código HTML se vea limpio y bien, poniendo avances de línea. PHP automáticamente eliminará los avances de línea puestos inmediatamente después de cerrar ?>. Esto puede ser muy útil si pone muchos bloques de PHP o incluye ficheros que contienen PHP que no se supone que deban mostarar nada. Al mismo tiempo, puede resultar un poco confuso. Se puede poner un espacio después de cerrar ?> para forzar el mostrar un espacio y un avance de línea , o se puede poner un avance de línea explícitamente en el último echo o print dentro de tu bloque en PHP.
Nota: acerca de editores de texto
Hay muchos editores de texto y Entornos Integrados de Desarrollo (IDE por sus siglas en Inglés) que puede usar para crear, editar, y organizar archivos PHP. Puede encontrar una lista parcial de éstos en » Lista de editores de PHP. Si desea recomendar un editor, por favor visite la página mencionada anteriormente, y comunique su recomendación a las personas encargadas del mantenimiento para que lo incluyan en la lista. Contar con un editor que resalte la sintaxis de PHP puede ser de mucha ayuda.
Nota: 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.
Nota: acerca del "Bloc de Notas de Windows"
Si escribe sus archivos PHP usando el "Bloc de Notas de Windows", debe asegurarse de que sus archivos sean guardados con la extensión .php (El Bloc de Notas automáticamente añade la extensión .txt a los archivos a menos que tome los siguientes pasos para prevenirlo). Cuando guarde sus archivos y el programa le pregunte qué nombre le desea dar al archivo, use comillas para indicar el nombre (es decir, "hola.php"). Una alternativa es, en la lista de opciones "Archivos de Texto *.txt", seleccionar la opción "Todos los archivos *.*". Aquí puede escribir el nombre del archivo sin las comillas.
Ahora que ha creado un pequeño script de PHP que funciona correctamente, es hora de trabajar con el script de PHP más famoso; vamos a hacer una llamada a la función phpinfo() para obtener información acerca de su sistema y configuración como las variables predefinidas disponibles, los módulos utilizados por PHP, y las diferentes opciones de configuración. Tomemos algo de tiempo para revisar esta información.
Ejemplo #2 Obtener la información del sistema desde PHP
<?php phpinfo(); ?>
Note on permissions of php files: You don't have to use 'chmod 0755' under UNIX or Linux; the permissions need not be set to executable. Again, this is more like a html file than a cgi script. The only mandatory requirement is that the web server process has read access to the php file(s). With many Linux systems, it is popular for Apache to run under the 'apache' account. Given that HTML and other web files, like php, are often owned by user 'root' and group 'web' (or another similar group name), acceptable permissions might be those achieved with 'chmod 664' or 'chmod 644'. The web server process, running under the 'apache' account, will inherit read only permissions. The 'apache' account is not root and is not a member of the 'web' group, so the "other" portion of the permissions (the last "4") applies.
Well, but PHP file ownership is important when server has safe_mode enabled - HTTP server checks it, uses it to set UID of process which executes it, or may even refuse to execute such a file - e.g. if one user is owner of main PHP file, and the main file includes another, owned by other user, this is considered to be security violation (quite reasonably).
document_root variable is located in your web server configuration file
If you save your code as UTF-8, make sure that the BOM (EF BB BF) is not present as the first 3 bytes of the file otherwise it may interfere with the code if the PHP need to be run before any output (e.g. header()).
On Windows, if file extensions can be hidden, you may not SEE that you have accidently saved a file as 'Text Documents' (and that the browser has added '.txt' to the end of your 'page.html', resulting in 'page.html.txt'.) You still see only 'page.html' even though it's really 'page.html.txt'. Also, if you try to rename it, it won't work because it's not overwriting the '.txt' part and not changing the filetype.
By the way, the hiding of file extensions is ALSO a way malicious crackers get you to click on an executable virus, fooling you into thinking it's an innocent document. You should always be able to view the extensions of all files on your system.
To view all extensions, open Windows Explorer. Click the 'Tools' menu, then 'Folder Options'. In the dialog box that appears, click the 'View' tab. In the 'Advanced Settings Box', scroll down to 'Hide extensions for known file types' and click the checkbox next to it to REMOVE THE CHECKMARK. Click the 'Apply to All Folders' button near the top of the dialog. This may or may not take a few minutes. Then click the 'OK' button to close the dialog.
Now, if something accidentally gets saved as the wrong filetype, resulting in another file extension automatically appended to the one you typed, you will see it and be able to rename it.
Of course, a badly-named file can be renamed simply by using 'Save As' and saving it as the proper filetype, but if you can't see the file extension, you may not know that is the problem. Also, renaming is easier than opening, resaving as a new filetype, and then deleting the old version!
