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

search for in the

Algo útil> <Una explicación sencilla
Last updated: Fri, 22 Aug 2008

view this page in

Su primera página con PHP

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

Example #1 Nuestro primer script PHP: hola.php

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

Utilice su navegador web para acceder al archivo, con la URL terminando en "/hola.php". Si está programando localmente este URL lucirá algo como http://localhost/hola.php o http://127.0.0.1/hola.php pero esto depende de la configuración de su servidor web. Aunque este tema está fuera del alcance de este tutorial, también puede ver las directivas DocumentRoot y ServerName en la configuración de su servidor (en Apache, esto es httpd.conf). Si todo está configurado correctamente, el archivo será analizado por PHP y el siguiente contenido aparecerá en su navegador:

<html>
 <head>
  <title>Ejemplo de PHP</title>
 </head>
 <body>
 <p>Hola Mundo</p>
 </body>
</html>

Note que esto no es como los scripts de CGI. El archivo no necesita ninguna clase especial de permisos para ser ejecutado. Piense en ellos como si fueran archivos HTML con un conjunto muy especial de etiquetas disponibles, y que hacen muchas cosas interesantes.

Este programa es extremadamente simple, y no necesita usar PHP para crear una página como ésta. Todo lo que hace es mostrar: Hola Mundo usando la sentencia echo().

Si ha intentado usar este ejemplo, y no produjo ningún resultado, preguntando si deseaba descargar el archivo, o mostró todo el archivo como texto, lo más seguro es que PHP no se encuentra habilitado en su servidor. Pídale a su administrador que active esta función por usted, o use el capítulo titulado Instalación en el manual. Si está trabajando localmente, lea también el capítulo dedicado a la instalación, y asegúrese de que todo esté configurado apropiadamente. Si el problema continúa, por favor use una de las muchas opciones para obtener » ayuda con PHP.

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

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

Note: Una nota acerca de los procesadores de palabras
Los procesadores de palabras como "StarOffice", "Microsoft word" y "Abiword" no son buenas opciones para editar archivos de PHP. Si desea usar uno de éstos programas para probar sus scripts, primero debe asegurarse de guardar el documento en formato de "Texto" puro, o PHP no será capaz de ejecutar el script.

Note: Una nota acerca del "Bloc de Notas de Windows"
Si desea escribir sus archivos PHP usando el "Bloc de Notas de Windows" o en algún otro editor de texto para Windows necesita asegurarse de que sus archivos sean guardados con la extensión .php (la mayoría de editores de texto en Windows automáticamente tratarán de añadir la extensión .txt a los archivos a menos que tome los siguientes pasos para prevenirlo). Cuando guarde sus archivos y el programa le pregunte qué nombre le desea dar al archivo, use comillas para indicar el nombre (es decir, "hola.php"). Una alternativa es, en la lista de opciones "Archivos de Texto *.txt", seleccionar la opción "Todos los archivos *.*". Aquí puede escribir el nombre del archivo sin las comillas.

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



Algo útil> <Una explicación sencilla
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
Su primera página con PHP
anpnymous
08-Sep-2008 10:28
I would highly recommend Aptana due to its ability to incorporate with other languages such as xhtml, javascript, and css, along with php.  The included validation tools are a great plus.  The basic version is free.
schneider at georgia dot com
08-Jul-2008 08:30
also I just started using HomeSite which is also a very good and simple to use editor.  It compliments Dreamweaver quite well.
pld at dervey dot co dot uk
23-Jun-2008 06:14
Always been happy with the facilities available in Dreamweaver (cur CS3), although the footprint on your PC can be high so notepad++ comes in second for little use of PC resources.
Anonymous
08-Jan-2008 04:30
The most usefull editor for me is Eclipse PDT and the debugger provided by Zend to the open source community.

Please check: http://www.zend.com/en/community/pdt
                    http://www.eclipse.org/pdt/
It's not only an editor, but an IDE also.

Good luck!

BN
byroniac at aol dot com
01-Jan-2008 10:46
For text editors, my current favorites are Bluefish on Linux, and Notepad++ on Windows. I believe you can't go wrong with these (and I believe Bluefish is available in many Linux distributions in pre-packaged form). I'm not affiliated with either of these; I'm just a satisfied user.

http://bluefish.openoffice.nl/
http://notepad-plus.sourceforge.net/uk/site.htm
Lori
09-Sep-2007 03:51
Re: .txt extensions at the end of Notepad files

I am not a programmer, but I do know that when you ftp files to a server, not only is the real name of the file shown that you want to transfer, but you can change it to whatever you want on the other end.  I know that can make uploading a lot of files a pain, but then, I have never had to upload that many files.  I remember a long time ago having to change .htm to .html, but I have never encountered the problem of having a .txt added that I didn't want.
jt at fuw dot edu dot pl
19-May-2007 04: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).
tinscurv at Hotmail dot com
12-Apr-2007 10:29
I noticed that it mentioned to add a "double quote" i.e "hello.php", when saving a php file when the drop down menu says txt. It is not necessary. You can type the whole name without quotes when the drown down menu is either txt or all. UNLESS, maybe for older windows? But for newer windows, it is not necessary. It works without a double quote. Anyway, if double quote is mentioned in the manual, then window versions needs to be stated.
Geoff
18-Mar-2007 03:56
People with file extension woes on Win32 really just need a better text editor.  Notepad2 is easy, very like notepad and supports syntax highlighting; quite a neat little thing:

http://www.flos-freeware.ch/notepad2.html

...and it won't mangle your file extensions.  Of course there are lots of others, but I use this one at work and it's OK when you have to work on Windows toasters.  Of course EMACS is also available on Win32 for those who like that sort of thing but Notepad2 is a neat, minimal, easy to use app for those who are generally comfortable in the Windows environment and might be intimidated by EMACS.
Stewart
05-Jan-2007 02:55
No need to go through these contortions each time to make sure the file is properly saved with the .php extension.  Just register .php as a file type in Windows, and then saving as hello.php without the quotes will work fine.
HobbyTech
08-Aug-2006 10: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 06:26
document_root variable is  located in your web server configuration file
onebadscrivener at gmail dot com
17-Jan-2005 05: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 02: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 02: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.

Algo útil> <Una explicación sencilla
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites