downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Algo útil> <¿Qué necesito?
Last updated: Fri, 20 May 2011

view this page in

Su primera página con PHP

Comienze por crear un archivo llamado hola.php y póngalo en el "directorio raíz" (DOCUMENT_ROOT) con el siguiente contenido:

Example #1 Nuestro primer script PHP: hola.php

<html>
 <head>
  <title>Ejemplo PHP</title>
 </head>
 <body>
 <?php echo '<p>Hola Mundo</p>'?> 
 </body>
</html>

Utilice su navegador web para acceder al archivo en su servidor, con la URL terminando en /hola.php. Si está programando localmente este URL será algo como http://localhost/hola.php o http://127.0.0.1/hola.php pero esto depende de la configuración de su servidor web. Si todo está configurado correctamente, el fichero será analizado por PHP y el siguiente contenido aparecerá en su navegador:

<html>
 <head>
  <title>Ejemplo PHP</title>
 </head>
 <body>
 <p>Hola mundo</p>
 </body>
</html>

Este script es extremadamente simple y no es necesario usar PHP para crear una página como esta. Lo único que muestra es: Hola mundo usando la función de PHP echo(). El fichero no debe ser ejecutable o especial de ninguna forma. El servidor reconoce que este fichero debe ser interpretado por PHP porque estamos usando la extensión ".php", el cuál está configurado para enviarlo a PHP. Piensa como si fuera un fichero HTML normal el cual tiene una serie de etiquetas especiales disponibles con las que puedes hacer muchas cosas interesantes.

Si ha intentado usar este ejemplo y no produjo ningún resultado, preguntando si deseaba descargar el archivo, o mostró todo el archivo como texto, lo más seguro es que PHP no se encuentra habilitado en su servidor. Pídale a su administrador que active esta función usando el capítulo titulado Instalación en el manual. Si está trabajando localmente, lea también el capítulo dedicado a la instalación para asegurarse de que todo esté configurado apropiadamente. Asegúrese que está accediendo al fichero vía http a través del servidor para mostrar el resultado. Si está abriendo el archivo desde el sistema de archivos, entonces probablemente no estará siendo analizado por PHP. Si el problema persiste no dude en usar alguna de las múltiples opciones de » Soporte de PHP.

El objetivo de este ejemplo es demostrar cómo puede usar el formato especial de las etiquetas PHP. En este ejemplo usamos <?php para indicar el inicio de la etiqueta PHP. Después indicamos la sentencia y abandonamos el modo PHP usando ?>. Puede salir de PHP y regresar cuantas veces lo desee usando este método. Para más información, puede leer la sección en el manual titulada Sintaxis básica de PHP.

Note: 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.

Note: acerca de editores de texto

Hay muchos editores de texto y Entornos Integrados de Desarrollo (IDE por sus siglas en Inglés) que puede usar para crear, editar, y organizar archivos PHP. Puede encontrar una lista parcial de éstos en » Lista de editores de PHP. Si desea recomendar un editor, por favor visite la página mencionada anteriormente, y comunique su recomendación a las personas encargadas del mantenimiento para que lo incluyan en la lista. Contar con un editor que resalte la sintaxis de PHP puede ser de mucha ayuda.

Note: 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 extensión .php (El Bloc de Notas automáticamente añade la extensión .txt a los archivos a menos que tome los siguientes pasos para prevenirlo). Cuando guarde sus archivos y el programa le pregunte qué nombre le desea dar al archivo, use comillas para indicar el nombre (es decir, "hola.php"). Una alternativa es, en la lista de opciones "Archivos de Texto *.txt", seleccionar la opción "Todos los archivos *.*". Aquí puede escribir el nombre del archivo sin las comillas.

Ahora que ha creado un pequeño script de PHP que funciona correctamente, es hora de trabajar con el script de PHP más famoso; vamos a hacer una llamada a la función phpinfo() para obtener información acerca de su sistema y configuración como las variables predefinidas disponibles, los módulos utilizados por PHP, y las diferentes opciones de configuración. Tomemos algo de tiempo para revisar esta información.

Example #2 Obtener la información del sistema desde PHP

<?php phpinfo(); ?>



Algo útil> <¿Qué necesito?
Last updated: Fri, 20 May 2011
 
add a note add a note User Contributed Notes Su primera página con PHP
Studio at archipelago dot co dot uk 29-Jan-2011 08:40
If, when you test the file in a browser, you see the HTML code rather than your greeting, it may be because you launched the page by dragging it to your browser. The URL should start with 'http://' NOT 'file://'
xiaomao5 at live dot com 03-Sep-2010 09:29
save your php script without the BOM when using UTF-8 or you will see "锘" in front of any output. A solution is save it without BOM(available in editplus and notepad++)
miklcct at gmail dot com 03-Jan-2010 01:56
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()).
jt at fuw dot edu dot pl 19-May-2007 11:48
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).
HobbyTech 09-Aug-2006 05:12
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!
c300501 at yahoo dot com 07-Jun-2006 01:26
document_root variable is  located in your web server configuration file
onebadscrivener at gmail dot com 18-Jan-2005 01:25
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.
Curtis 10-Aug-2004 09:47
Expansion on saving w/ notepad/wordpad: (tested on XP; but should work on 2000,NT, and 98)

You can associate the .php file extension w/ Windows w/o going into the registry.

Open up My Computer or MSIE in file mode. Go to folder options > File types tab. Now click new. Add the extension as PHP or php. If you can't find the PHP application in the dropdown list under advanced, just go OK, for now. At least the extension is in place.

Now, try and create a php file by using the directions from this page of the PHP tutorial (should save it with the rest of your HTML files, i.e. your DocumentRoot). If you go to view your php file listed in the directory, and you see that it's still a .txt file, right-click the icon to see if you can locate "open with." If so, you should be able to browse for the appropriate file, which should be at (may vary, depending on where you installed PHP):

C:\PHP\php.exe

Click that as the default program, and the PHP logo should appear on all your scripts, and no problems saving should occur w/ any program.

Good luck.
ryan420 at earthling dot net 03-Feb-2003 10:18
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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites