PHP - - By Tom Butler

The following is a short extract from our new book, PHP & MySQL: Novice to Ninja, 6th Edition, written by Tom Butler and Kevin Yank. It’s the ultimate beginner’s guide to PHP. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.

Now that you have your virtual server up and running, it’s time to write your first PHP script. PHP is a server-side language. This concept may be a little difficult to grasp, especially if you’ve only ever designed websites using client-side languages like HTML, CSS, and JavaScript.

A server-side language is similar to JavaScript in that it allows you to embed little programs (scripts) into the HTML code of a web page. When executed, these programs give you greater control over what appears in the browser window than HTML alone can provide. The key difference between JavaScript and PHP is the stage of loading the web page at which these embedded programs are executed.

Client-side languages like JavaScript are read and executed by the web browser after downloading the web page (embedded programs and all) from the web server. In contrast, server-side languages like PHP are run by the web server, before sending the web page to the browser. Whereas client-side languages give you control over how a page behaves once it’s displayed by the browser, server-side languages let you generate customized pages on the fly before they’re even sent to the browser.

Once the web server has executed the PHP code embedded in a web page, the result takes the place of the PHP code in the page. All the browser sees is standard HTML code when it receives the page, hence the name “server-side language.” Let’s look at simple example of some PHP that generates a random number between 1 and 10 and then displays it on the screen:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            <?php

            echo rand(1, 10);

            ?>
        </p>
    </body>
</html>
                  

Most of this is plain HTML. Only the line between <?php and ?> is PHP code. <?php marks the start of an embedded PHP script and ?> marks its end. The web server is asked to interpret everything between these two delimiters and convert it to regular HTML code before it sends the web page to the requesting browser. If you right-click inside your browser and choose View Source (the text may be different depending on the browser you’re using) you can see that the browser is presented with the following:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            5
        </p>
    </body>
</html>
            

Notice that all signs of the PHP code have disappeared. In its place the output of the script has appeared, and it looks just like standard HTML. This example demonstrates several advantages of server-side scripting …

  • No browser compatibility issues. PHP scripts are interpreted by the web server alone, so there’s no need to worry about whether the language features you’re using are supported by the visitor’s browser.
  • Access to server-side resources. In the example above, we placed a random number generated by the web server into the web page. If we had inserted the number using JavaScript, the number would be generated in the browser and someone could potentially amend the code to insert a specific number. Granted, there are more impressive examples of the exploitation of server-side resources, such as inserting content pulled out of a MySQL database.
  • Reduced load on the client. JavaScript can delay the display of a web page significantly (especially on mobile devices!) as the browser must run the script before it can display the web page. With server-side code, this burden is passed to the web server, which you can make as beefy as your application requires (and your wallet can afford).
  • Choice. When writing code that’s run in the browser, the browser has to understand how to run the code given to it. All modern browsers understand HTML, CSS and JavaScript. To write some code that’s run in the browser, you must use one of these languages. By running code on the server that generates HTML, you have a choice of many languages—one of which is PHP.

Basic Syntax and Statements

PHP syntax will be very familiar to anyone with an understanding of JavaScript, C, C++, C#, Objective-C, Java, Perl, or any other C-derived language. But if these languages are unfamiliar to you, or if you’re new to programming in general, there’s no need to worry about it.

A PHP script consists of a series of commands, or statements. Each statement is an instruction that must be followed by the web server before it can proceed to the next instruction. PHP statements, like those in the aforementioned languages, are always terminated by a semicolon (;).

This is a typical PHP statement:

echo 'This is a <strong>test</strong>!';
            

This is an echo statement, which is used to generate content (usually HTML code) to send to the browser. An echo statement simply takes the text it’s given and inserts it into the page’s HTML code at the position of the PHP script where it was contained.

In this case, we’ve supplied a string of text to be output: This is a <strong>test</strong>!. Notice that the string of text contains HTML tags (<strong> and </strong>), which is perfectly acceptable.

So, if we take this statement and put it into a complete web page, here’s the resulting code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test page</title>
    </head>
    <body>
        <p><?php echo 'This is a <strong>test</strong>!'; ?></p>
    </body>
</html>
                    

If you place this file on your web server and then request it using a web browser, your browser will receive this HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test page</title>
    </head>
    <body>
        <p>This is a <strong>test</strong>!</p>
    </body>
</html>
            

The random.php example we looked at earlier contained a slightly more complex echo statement:


echo rand(1, 10);
            

You’ll notice that, in the first example, PHP is given some text to print directly, and in the second, PHP is given an instruction to follow. PHP tries to read anything that exists outside quotes as an instruction it must follow. Anything inside quotes is treated as a string, which means PHP doesn’t process it at all but just passes it to the command you called. So the following code will pass the string This is a <strong>test</strong>! directly to the echo command:


echo 'This is a <strong>test</strong>!';
            

A string is signified using a start quote and an end quote. PHP will see the first ' as the start of the string and find the next ' and use that as the end of the string.

In contrast, the following code will first run the built-in function rand to generate a random number and then pass the result to the echo command:


echo rand(1, 10);
            

You can think of built-in functions as tasks that PHP knows how to do without you needing to spell out the details. PHP has many built-in functions that let you do everything, from sending email to working with information stored in various types of databases.

PHP won’t try to run anything that’s inside a string. The following code won’t have the result you may be expecting:


echo 'rand(1, 10)';
           

Instead of running the inbuilt function rand, PHP will see it as a string, and rather than printing out a random number, it will actually send the text rand(1, 10) to the browser, which probably isn’t what you wanted to do. It’s important to understand the difference between a string and code. PHP will see any text outside quotes as a series of commands it should follow. Anything inside quotes is a string and is data that PHP will work with.

PHP doesn’t try to understand strings. They can contain any characters in any order. But code—which is essentially a series of instructions—must follow a rigid structure for a computer to understand it.

When you invoke a function in PHP—that is, ask it to do its job—you’re said to be calling that function. Most functions return a value when they’re called; PHP then behaves as if you’d actually just typed that returned value in your code instead. In the echo 'rand(1, 10)'; example, our echo statement contains a call to the rand function, which returns a random number as a string of text. The echo statement then outputs the value returned by the function call.

Every function in PHP can have one or more arguments that allow you to make the function behave in a slightly different way. The rand function takes two arguments: the minimum random number and the maximum. By changing the values that are passed to the function, you’re able to change the way it works. For example, if you wanted a random number between 1 and 50, you could use the code:


echo rand(1, 50);
           

You may wonder why we need to surround the arguments with parentheses ((1, 50)). The parentheses serve two purposes. First, they indicate that rand is a function that you want to call. Second, they mark the beginning and end of a list of arguments—PHP statements that you wish to provide—in order to tell the function what you want it to do. In the case of the rand function, you need to provide a minimum and a maximum value. Those values are separated by a comma.

Later on, we’ll look at functions that take different kinds of arguments. We’ll also consider functions that take no arguments at all. These functions will still need the parentheses, even though there will be nothing to type between them.

Sponsors