How do I create my first PHP file?

Understanding the basics of file structure is a key part of learning the language

Writing your first PHP file shouldn’t seem like a daunting task. Getting the first few lines of PHP up and running involves a few basic principles which can then be applied to more complex situations to expand your knowledge.

How does PHP work?

PHP, in its basic form, is like any other programming language - a tool for processing code to return an output. For example, when we run PHP via the command line, the code

// the "php -r" command executes whatever code is between the quotes
> php -r "echo 2 + 2;"

will output the following result to the command line

4

An extremely simple example, but you get the idea. PHP takes input in the form of text instructions & code, and produces an output.

In this example, we’re passing in the instruction echo 2 + 2; which, in English, says “Add 2 and 2 together and print the result to screen”

On its own, PHP doesn’t have the capability to power websites, but after installation and setup of a webserver such as Apache, it gains the ability to communicate with a web browser on your computer from either another computer elsewhere in the world, or from software running on your own machine.

When combined with a properly configured webserver, the computer on which the server is running knows to look for PHP files in a specific location, and when directed to process a specific file, executes the code stored within and returns the result back to the webserver, which is then sent onwards to the user’s web browser.

Naming a PHP file

PHP code is stored within files ending in the .php extension, which lets the computer on which they are running know that these files are to be interpreted with the PHP interpreter and the output sent to the user’s web browser.

Take the example above. Instead of typing the code into the command line, you can save it in a file, and then run the PHP interpreter against that file. This makes it far easier to process a lot of PHP code in one go, and means you don’t have to type a long, unwieldy instruction into the command line.

Let’s say our code above is saved into a file called myexample.php within the current directory. We’d run the following command line instruction

//the file myexample.php contains the text "<?php echo 2 + 2; ?>"
//the meaning of <?php will be given shortly
php -f myexample.php

Which will give us

4

This small change in how we pass our code into the PHP interpreter is a big step towards a system that can process multiple files containing large quantities of PHP code to generate a fully functional website.

Creating and saving a PHP file

PHP code can be written and saved with the use of a simple text editor, like Notepad++, or the more powerful Sublime Text or PHPStorm (Notepad++ is a free option).

(Important: Don’t use a program such as Microsoft Word, Frontpage or other more complex word processors to create your PHP file. Although the page might look free of formatting when you save the file, there will be other hidden formatting elements within the file itself that will prevent any PHP code from running.)

For example, here’s the contents of an example file:

<?php
  $x = 1;
  $y = "b";
  echo "Hello world";
?>

The first thing to note here is the opening and closing php tags, <?php and ?>. These are fundamental to allow the interpreter to understand your file.

In essence, you’re telling the system, “Everything between <?php and ?> is to be thought of as PHP code”. This is required when specifying PHP within a file rather than via the command line.

The lines between these two tags contain PHP code. This example doesn’t do anything useful. It allocates the value “1” to a variable $x, allocates the value “b” to the variable $y and prints “Hello world” to the screen. More details about these operations will be provided in later tutorials.

You could upload this code to a PHP-based web host and have it show up to the world right away, although it wouldn’t look like what you’d expect from a standard web page.

We’ll take a look shortly at how you can create your very own simple PHP file to run as a basic web-page. First though, we need to know where to locate our PHP files.

The location of the PHP file on disk

(Note: This tutorial assumes that you already have a suitable location set up for hosting PHP files. This can either be through a remote web-host or within a local server environment installed with something like XAMPP)

An important thing for us at this point is to know where to save this .php file for it to be recognised as a valid web-page file. Any PHP documents must be placed within the document root of a website server. In simple terms, this means that on your computer, or on the remote computer that you’ve got set up as a website host, are a number of folders and directories. One of these directories will be set up as the document root, and is usually named c:\local if you’re using your own Windows machine to run the code, something like /opt/lampp/htdocs on Linux, or something like /htdocs or /html_root if you’re running on a remote server.

The document root is the base directory from which all the website data is served from. Any sub-directories within this main root directory will show up as sub-folders when you type in the URL.

e.g. if you have a folder “mysite” within the c:\local\ folder, you’ll be able to access the URL http://localhost/mysite to see the contents of this folder. Any PHP files within this folder can be accessed by adding the PHP filename to the end. e.g. http://localhost/mysite/myphpfile.php

Similarly with a remote host, a folder like htdocs/mysite will be accessible from http://www.example.com/mysite and any relevant PHP files in the mysite folder will be at http://www.example.com/mysite/myphpfile.php and so on

Once uploaded to a location on the web, you can visit that file using your web browser to view the result. As an example, take the following code example, within a file named index.php

// this text is stored within a file named index.php
// and uploaded to http://www.example.com
echo 2 + 2;

So, if we now visit http://www.example.com/index.php, we’ll see in our browser

4

Again, not much to write home about! But we’re now seeing the result of the PHP script within a web browser rather than the command line. It’s a step in the right direction

Also, note that by default, most web servers are configured to automatically serve up the “index.php” file when visiting the web address without specifying a file. So, visiting http://www.example.com without specifying index.php will also get us

4

We can also use the echo command to output text, for example

echo "Hello world";

Will show us, at http://www.example.com in our browser

Hello world

You might realise that you can save more PHP code into another file, let’s call it “page2.php” and upload that to your website. So, if we have the following code

echo "This is page 2!";

saved as page2.php and uploaded to www.example.com, now when we visit http://www.example.com/page2.php we see

This is page 2!

Using this approach, we can now have a website with multiple pages. On its own, this doesn’t provide us with a fully working website, as there’s no way to link between these pages. But that’s where introducing HTML into the mix comes in useful, and we’ll cover that in the next tutorial so that we can really start to understand and harness PHP’s potential in providing dynamic and interesting web content.

Getting started with a slightly more complex example

To get started, first of all save a blank file with a .php extension into the document root of your web-server, either on your local computer, or accessed remotely via FTP. This is the file you’ll edit to create your first PHP application.

After saving a blank PHP file in your chosen location, point your browser to the URL where your file is located, according to the directory structure and the location you saved the file in. E.g. using the address http://localhost/myphp/myphp.php if you saved the file in c:\local\myphp\myphp.php or http://www.example.com/mysite/file.php if you saved the file file.php on a remote server in the folder mysite).

After entering this URL, you should see a blank screen appear. This is because we’ve not added anything to the file yet!

Return to your text editor, and add the following lines to the file

<?php
echo "Hello world";
?>

Type it out exactly as it’s written above. Return to the web browser now, and reload the page. You should see the following output

Hello world

If you see the above text, then everything is going well! You should now have your first working PHP application. If you don’t see the text above appear on the screen, go back and check the file again. You must enter the code exactly as it appears above.

Now, go back to your text editor and adjust the text again to read as follows

<?php
$name = "Bob";
echo "Hello {$name}, how are you?";

Return to your browser, and refresh the page

Hello Bob, how are you?

Here, we’re introducing a concept known as variables, something covered in a later tutorial, as well as some other syntax (notice the curly brackets around $name in the third line?). For now though, I’m sure you can make a fair assumption about what’s going on. We’re using PHP to dynamically construct a sentence.

The attentive amongst you may also notice this second example has discarded the closing ?> tag. There’s a good reason for this.

The closing ?> tag in a PHP file isn’t needed. Once the PHP interpreter reaches the end of a file, it’ll automatically finish processing PHP. We don’t need to manually tell it to do so.

A second reason for ommiting the tag is more subtle, but more important. I won’t include all the details here, as they’re a little technical, but if you include the closing ?> tag, and the include other non-PHP content after the closing tag, then in certain cases this has the potential to break some web functionality in a way that isn’t immediately obvious, and may cause subtle but noticeable errors.

So - best practice, always leave out the final closing PHP ?> tag in PHP files

As a last step, let’s go back to our text editor

<?php
$name = "Bob";
$age = 21;
echo "Hello {$name}. ";
echo "You are ".$age." years old";

In our final example, I’ve introduced a second method for inserting data into a sentence. The dot . operator performs a concatenation operation on the text in line 5, joining together the text “You are “, the value $age and the text ” years old”

Looking back at our browser, we get

Hello Bob. You are 21 years old

I’ll cover the technical details of the methods used here in later articles. I’ve included these examples here as a taster of what’s possible with PHP.

The semi-colon

The semi-colon which appears at the end of each line in PHP is very important. It tells the PHP interpreter that it should stop processing the last instruction and move onto the next.

In the following code, the lack of a semi-colon on the first line will cause an error

echo "Hello world"
echo 2 + 2;

This code will not run, as the interpreter will notice the missing semi-colon and halt at that point, showing no result

This code, however, will work - despite both instructions being on the same line, they are seperated by a semi-colon

echo "Hello world"; echo 2+2; 

This will print

Hello world4

Likewise, the following code will also work

<?php echo "Hello world" ?>
<?php echo 2 + 2 ?>

But - no semi-colons? There’s an exception to the semi-colon rule. When we include PHP instructions within PHP tags <?php and ?>, the closing ?> implies a semi-colon, so we don’t need to include one. It’s good practice to always add one in though.

And one last little point: Those attentive ones out there may wonder now, “Hey, that closing ?> tag, you can leave that out, right?” - Yep, absolutely right, but…

<?php echo "Hello world" ?>
<?php echo 2 + 2

will cause an error! Specifically syntax error, unexpected end of file, expecting ',' or ';' - this is PHP telling you that you do need to include a semi-colon if you choose to omit the closing ?> tag. This following code snippet on the other hand, this will work.

<?php echo "Hello world" ?>
<?php echo 2 + 2;

Going into the full scope of PHP file structure and syntax is waaaay beyond the scope of this, and later tutorials. This is the sort of thing you only really learn through trial and error and experimentation.

So go ahead, fire up your text editor and try a few experiments. And I’ll leave it as a little practical exercise to figure out why the error message above was expecting either a semi-colon or a comma…

Using Comments in PHP

Comments are an excellent way to document your code. They allow for a way to place handy notes and thoughts for yourself alongside your code so that you can pick up where you left off when you return to either add new features or debug the script. Comments also provide an effective way for other developers to understand your thoughts and motivations when working on your code.

Comments can be written in one of three ways as the following examples demonstrate

<?php
/* this is a comment
   it can cover multiple lines */
echo "Yes, it is";
//this is also a comment, but only for a single line
#this is also a comment, but not used as much
echo "I never use it anyway";
echo "You can also.."; //..add comments after statements
echo "As well as.."; /*multiline
  comments */ echo "..and another statement after";
?>

Comments may seem a bit counterintuitive at first. If you’re not used to programming, you might wonder what the point is of adding all that extra work if it does nothing useful. In time though, and with experience of larger projects, you’ll find that all those little thoughts and statements become invaluable when you return to debug code days, weeks, months or years later.

Conclusion

I hope you enjoyed this initial introduction into the structure of a PHP file. It’s a fascinating language to learn, while admittedly being somewhat non-intuitive at times. Its massive following and extensively documented features make it, I believe, a very good time investment, especially if you’re looking to delve deeper into the world of web programming.

« Previous Next »

Robin Metcalfe is a freelance developer based in Edinburgh, Scotland with loads of experience in old and new web technologies. Want to know more?

He is currently available for hire . You can also get in touch via Twitter