PHP for Non-Developers

After years of making it clear that I'm not a developer in just about every article I've written here at Linux Journal, I do have a confession to make. I can write the "Hello World" equivalent in almost every programming language out there. In assembly, it might have been "1+1", but my lack of advanced skills should be evident. The thing is, I've always wanted to learn how to program, but I hate the process so much I never get past "Hello World".

Then I met PHP.

I know PHP is no longer cool. I know that compared to Python it's extremely limited. But I also know that with PHP, I actually was able to create useful programs from the beginning. I suspect that's why I love Bash scripting so much. With Bash, I always start with a problem to solve and use scripting to solve it. I never "learned" to write Bash scripts, I just did it. My goal in this article is to throw you right into writing useful PHP code. If you really want to make "Hello World" appear in a browser window, by all means do so. But I'm not going to teach you how!

Preliminaries

Server:

One great thing about PHP is that just about every Web server has it installed and ready to go. If you get advanced and want to start making system calls to the underlying Linux OS, you might have to tweak php.ini a bit, but getting a PHP platform is usually as simple as installing a Web server with a LAMP stack.

One thing that makes programming easier for me is to make sure my user account has write access to the place I'm writing code. My process usually involves making a small change and clicking refresh on the browser to see if it worked. If you have to sudo cp localfile serverfile every time you make a change, it will be no fun. Worry about proper file permissions when you release your code to the Internet, but not while you're developing.

The only other server tweak I recommend is adding a .htaccess that turns on error reporting. I don't always have errors display on the page, but if you get the dreaded "php blank page", it's nice to turn on error reporting quickly so you get a nice message telling you where you forgot a semicolon. I usually create a file called "err" and quickly rename it to ".htaccess" when I want to see errors displayed. You probably will have to modify your Apache server, telling it to "AllowOverride" for the folder you're using, but it's worth the effort. Here's what my .htaccess file looks like:


php_flag  display_errors        on
php_value error_reporting       2039

Editor:

PHP code is just text. You can use any text editor you like. I highly suggest using a text editor that does syntax highlighting though, because it makes it much easier to spot typos. I usually use vim when I do Bash scripting, but with PHP, I find myself scrolling more, so something like gedit works better for me. If you really want to get fancy, programs like Sublime or SlickEdit are amazing, but really gedit is fine. Just make sure whatever editor you use has syntax highlighting, it's awesome. (If you need to edit remote files, I'd check out using SSHFS to mount the remote folder and edit them as if they were local files. It works great in gedit.)

The Goal

For this first foray together into the world of programming, let's create something useful, but still simple. I also want to start with something worth building on to. So let's make a start page for your browser. Remember iGoogle? Well, you're going to start with something far more simple, but because you're making it yourself, you can expand later. (I find coding to be a perfect way to spend nights of insomnia, just saying.)

How PHP Works

It took me a little while to understand this concept, so I'm going to explain it quickly. PHP code can be added to standard HTML, or it can be strictly PHP code that creates HTML as output. These following two snippets of code do the same thing.

test.php:


<html>
<body>
<h1>The current day is: <?php echo date("l"); ?>!</h1>
</body>
</html>

test2.php:


<?php
echo "<html>";
echo "<body>";
echo "<h1>The current day is: " . date("l") . "!</h1>";
echo "</body>";
echo "</html>";
?>

Feel free to copy that into two separate PHP files and browse to the page. You should see something like Figure 1. The reason I spelled this out is because different people code PHP in different ways. Just remember that if it's not inside a <?php ?> container, it is treated like plain-old HTML. Anything inside those <?php ?> containers are executed, and the output is sent to the browser window. Often, PHP code won't have any output, and so nothing is displayed on the screen. But, if you want to use PHP, it must be inside those tags, namely: <?php PHP STUFF HERE ?>.

Figure 1. It's not "Hello World", but I'll admit, it's dangerously close.

Let's Make Something!

I created a simple landing page in PHP. (Figure 2 shows its output.) You can download it at http://snar.co/ljphp. It's also shown in Listing 1. Unzip the file, and put it in your Web server so you can edit it and make it work for you.

Figure 2. This is the portal. Your family probably will be less silly looking!

Listing 1. Example Landing Page

<?php

// This is a comment. The next lines fetch weather info
// and then turn it into a PHP array (You'll need your 
// own API key!)

$json=file_get_contents("http://api.wunderground.com/
↪api/YOUR_API_GOES_HERE/conditions/pws:1/q/49749.json");
$weather = json_decode($json, TRUE);
?>

<html>
<head><h3>Landing Page</h3></head>
<body>
<table style="text-align: left; width: 100%;" border="0" 
 ↪cellpadding="2" cellspacing="2">
    <tr>
        <td>
            <img style="width: 250px;" alt="The Fam!"
              ↪src="fam.jpg"><br>
            <?php
                echo "Current Temp: " .
                 ↪$weather['current_observation']['temp_f'] 
                  ↪. "F<br>";
                echo "Conditions: " .
                 ↪$weather['current_observation']['weather'] 
                  ↪. "<br>";
                echo "<small>" . $weather['current_observation']
                ↪['observation_time'] . "</small><br>";
            ?>
        </td>
    <td style="vertical-align: top;">
                Shawn's Very Simple Page<br>
        <big><strong><a href="http://www.brainofshawn.com">Are You
         ↪Looking for My Blog?</a></strong></big>
                <br><br>
                <?php
                        echo "Google is: ";
                        is_up("www.google.com");
                        echo "<br>";
                        echo "Linux Journal is: ";
                        is_up("www.linuxjournal.com");
                        echo "<br>";
                        echo "Blarxnot is: ";
                        is_up("wwww.blarxn0t.com");
                ?>
        </td>
    </tr>
    <tr>
        <td colspan="2">
        <?php echo "<br><center>Server Uptime: " .
         ↪shell_exec("/usr/bin/uptime") . "</center>"; ?>
        </td>
    </tr>
</table>
</body>
</html>

<?php
    function is_up($host,$port=80,$timeout=1)
    {
    $fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
    if ( ! $fsock )
            {
            echo "DOWN";
    }
    else
    {
        echo "UP";
    }
    }
?>

Notice the first line has <?php in it—that means it starts with a section of PHP code rather than HTML. The first thing you do is load a weather API into a PHP array. You'll need to register on Wunderground to get your own API key (they're free), and then modify the URL to fit your location. Basically, it's a two-step process: you load the JSON string into a variable called $json and then use the json_decode function to break that apart into an array. Check out the Working with Arrays sidebar for some tips on looking at the array itself so you can see what it contains.

After that little bit of variable work, the PHP section closes with a ?> on line 8. From that point on, it's mostly HTML coding that should look fairly clear. Basically, I created a simple table. In the first cell, there is a picture of my family (you can add your own fam.jpg to the same folder where the php file lives), and then I open another section of PHP code. Here I print some of the information from the Weather API. You can figure most of it out, but of particular note are the periods in the echo statements. If you want to print more than one thing on the screen, put a dot in between them outside the quotation marks.

After some more HTML code, there is a section that checks Web servers to see if they're up. It's important to know that "is_up" is not a built-in PHP function, rather it's something I wrote to make the code cleaner. If you look at the bottom of the file, you'll see where I defined the function, and you can see what it does. The only thing it checks is whether it can connect to port 80 on the specified address. I made up blarxn0t.com so one would fail. Hopefully no one buys blarxn0t.com just to spite me! (Note: don't try to visit it, with my luck, somebody bought it and made it porn!)

The last section of the PHP document does a really cool PHP trick and executes a local shell command, dumping the output to the browser screen. So the results of the uptime command are printed at the bottom of the landing page. If you have a Windows server, it probably will just error out, but I'm assuming we're all using Linux here.

To Infinity and Beyond!

This first simple PHP page is just that, very simple. I touched on a few advanced subjects though, and I hope you explore more from here. Arrays are really cool and make working with APIs from Web sites a breeze. If you liked this little taste of PHP, I recommend you look into the following:

  • IF/THEN/ELSE conditionals.

  • For loops.

  • While loops.

  • Reading and writing files on the system.

  • GET and POST variables.

  • Functions.

  • Including other PHP files.

But, I urge you—don't just look them up and memorize how they work. Come up with a problem and then solve it! Everything I've learned in PHP started with a Google search like, "How do I display large numbers with commas in PHP", or "How do I round numbers in PHP", or even "How do I multithread queries in PHP for parallel processing?" (That last one is by far the most complex thing I've done so far!)

PHP coding is incredibly fun. I can't believe I'm saying that, but it's true. If you love Bash and can't imagine living without it, I suspect you'll love PHP, because it's a lot like Bash, but a Web browser gets to be the input/output mechanism! If you'd like me to do more project-based learning with programming languages, please let me know. I'd love a reason to come up with fun projects, but it only makes sense if everyone wants to play along!

Working with Arrays

Arrays can be really confusing. In this article, I showed loading a JSON API feed into a PHP array, and then referenced a couple fields from inside that array. But how on earth do you know how to build those variable names like $weather['current_observation']['temp_f']? Thankfully, there's a great tool for displaying arrays on the screen. Here's a snippet of code that takes a copy of the JSON code from this article's example and displays the entire array so you can see the names of the array indexes. You should be able to see how I created that variable name above:


array_view.php
<?php
$json = file_get_contents("http://snar.co/jsonapi");
$weather = json_decode($json, TRUE);
echo "<pre>";
print_r($weather);
echo "</pre>";
?>

When you load this page, it should display the entire array in an easy-to-read format in your browser. The <pre> tags are important; otherwise, it just jumbles the output all into a single line. Whenever I'm trying to figure out the contents of an array, I make a quick PHP file like this so I can look at it. Hopefully, you'll be able to find the variable indexes, and it will make sense.

Shawn is Associate Editor here at Linux Journal, and has been around Linux since the beginning. He has a passion for open source, and he loves to teach. He also drinks too much coffee, which often shows in his writing.

Load Disqus comments