Your first PHP-enabled page
Create a file named hello.php and put it in your web server’s root directory ( DOCUMENT_ROOT ) with the following content:
Example #1 Our first PHP script: hello.php
Use your browser to access the file with your web server’s URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server’s configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the «.php» extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used . You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
Note: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren’t supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
Note: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
Note: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Example #2 Get system information from PHP
How To Write Your First PHP Program
The “Hello, World!” program is a classic and time-honored tradition in computer programming. Serving as a complete first program for beginners and a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages.
This tutorial will walk you through writing a “Hello, World!” program in PHP. You’ll also learn about opening and closing PHP code blocks within your code and using different types of comments in your code.
Prerequisites
You will need PHP installed as well as a local programming environment set up on your computer.
Writing the “Hello, World!” Program
To write the “Hello, World!” program, start by opening a command-line text editor, such as nano , and create a new file:
Once the text file opens up in the terminal window, type out the program:
Let’s break down the different components of the code.
All PHP code falls within a PHP Code Block, starting with .
echo is a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas and not delimited by parentheses. echo tells PHP to display or output whatever is included between echo and the ending semicolon ; .
Between the echo and the ; is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside quotation marks are called a string.
After writing the program, hold down the CTRL key and press the X key to exit nano . When prompted to save the file, press Y .
Once you exit nano, you’ll return to your shell.
With that, you have written your “Hello, World!” program.
Running the “Hello, World!” Program
With your “Hello, World!” program written, you’re ready to run the program. Use the php command along with the name of the program file as follows:
Running the hello.php program that you just created will cause your terminal to produce the following output:
Let’s go over what the program did in more detail.
PHP executed the line echo «Hello, World!»; by calling the language construct echo . The string value of Hello, World! was passed to the construct.
In this example, the string Hello, World! is also called an argument since it is a value that is passed to another part of the code, such as a construct or a function.
The quotes that are on either side of Hello, World! were not output to the screen because they are used to tell PHP that this section of code contains a string. The quotation marks delineate where the string begins and ends.
Since the program ran successfully, you can now confirm that PHP is properly installed and that the program is syntactically correct. Before going any further in the code itself, let’s take a closer look at the PHP Code Block.
Working Outside the PHP Code Block
Within a .php file, anything outside of the PHP tags is treated as HTML or plain text. The PHP language was originally written as a way to extend the functionality of HTML. With this in mind, you may include multiple PHP code blocks throughout a file. Anything outside the code block will render as HTML or plain text.
Update your hello.php file:
Hi Sammy echo "Hello, World!"; ?> How are you doing? echo "Swimmingly!";
Save the file and rerun it:
OutputHi Sammy Hello, World! How are you doing? Swimmingly!
Diving into the code, you’ll notice that Hi Sammy and How are you doing? are both outside the PHP code blocks and therefore render as plain text when running the program.
This file contains two PHP code blocks. The first code block includes both the starting and ending tags, while the second code block, being at the end of the file, leaves off the final closing tag.
Including the closing block tag ?> is not required. When ending a file with a PHP code block, it is recommended to leave off the closing tag. Any character, even a blank space, which is rendered after the closing tag will be output to the screen as HTML or plain text. This can cause unexpected consequences with the function of your application because certain functionality, such as a redirect, will not process if anything has been output to the browser. When writing a file that contains only PHP code, never include the closing PHP tag.
As code gets more complicated, like when splitting concepts over multiple code blocks, it can be beneficial to leave notes for ourselves and others. You can do this through the use of comments.
Adding Comments in PHP
A comment in code is a line that will not execute as a part of the program. Its only purpose is to be read by a human who is looking at the code. One thing that comes as a shock to many developers is how much time is spent reading code versus writing code. This means it’s essential to have code that is as easy to read as possible. You can accomplish this in a few ways:
- Use coding standards. These are a collection of guidelines and best practices for organizing and formatting code clearly and consistently. In PHP, the most common coding standards are those developed by the PHP-FIG (Framework Interop Group).
- Choose ease of reading over ease of writing. Use descriptive variables over short variables. It’s not about how many lines of code your write, but how long it will take someone to read those lines and understand what’s going on.
- Comment for clarity. While it isn’t a hard and fast rule, if you’ve followed the previous two bullet points, your code should explain what is happening, while the comments explain why something is happening the way it is.
When writing comments in PHP, there are two types of comments: single-line comments and multiline comments. Single line comments can start at any point on a line and end at either the end of the line or the end of the code block, whichever comes first.
The most common way to start a single-line comment is with the double forward slash ( // ), although PHP also recognizes a hash sign ( # ) as a valid start to a single-line comment:
Hi Sammy echo "Hello"; //, World!"; ?> How are you doing? echo "Swimmingly!"; // other options: Floating along
Save the file and run it again:
OutputHi Sammy Hello How are you doing? Swimmingly!
The first comment starts in the middle of a line. A closing quote and semicolon were added after «Hello» and the rest of the line was commented out. Commenting out one or more lines of code is often used in debugging to test how the code responds if certain elements are removed.
You use a second comment to give a secondary option for an answer. The next step in your project may be to respond with one of several different options each time you execute the application. The comment is used as a reminder for other options that could be added.
Multiline comments start with /* and end with */ . The PHP interpreter will ignore any text or code within those characters. To provide more options, let’s change the last line to a multi-line comment:
Hi Sammy echo "Hello"; //, World!"; ?> How are you doing? echo "Swimmingly!"; /* When responding with one of a number of answers, here are some other options: * Floating along * Fin-tastic * Going with the flow * Treading water * Swamped */
Using a multi-line comment gives more room to add detail or formatting to once again make the code, and the intention of the code, easier to understand. This multi-line comment includes line breaks and added * as a delineator for a list. The */ combination signifies the end of our comment block.
Using DocBlocks for Documentation
There is a special type of multi-line comment called a DocBlock. This is a unique way of documenting the functionality of a particular file, class, method, or other structural elements. Although a DocBlock starts and ends like any other multi-line comment /* */ , they are designed to give specific detail for working with an element. Not only do these details provide an overview of the code for developers, but they may also be used by a code editor (or IDE) to provide suggestions and validation.
A DocBlock consists of several parts. The first is a brief summary to introduce the element and a longer description if more context is needed.
The final section that makes a DocBlock unique is for tags and annotations. These provide a way to succinctly and uniformly provide meta-information about the associated element. Tags can, for example, describe the type of information that is accepted or returned by a method or function. It may also provide details about the author or copyright of a file:
/** * DocBlock example * * @author Sammy */ .
While you should strive to write code that is clear and easy to follow, adding clarifying comments can add additional context that will increase the understanding of the code and the choices behind the code.
Conclusion
In this tutorial, you have written the “Hello, World!” program in PHP. You learned about opening and closing PHP code blocks within your code and using different comments to clarify and add context as your code gets more complicated. From here, you can continue learning by following the How To Work with Strings in PHP tutorial.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in PHP
PHP is a popular server scripting language known for creating dynamic and interactive web pages.