Learning PHP: Get Started Using PHP

By Elias Zerrouq

Advertisement

This PHP tutorial will guide you through the process of learning and using PHP, preparing you with some fundamental knowledge to get you started in the right path. We will talk about the history of PHP, create a local development environment (so that you won’t need a web server) and create a basic PHP script while discussing common beginner PHP gotchas along the way.

Introduction

In the beginning, there was nothing. Well, there were static web pages that had to be edited manually. That was a pain. And it didn’t do anything other than display text and images on a web page.

With the introduction of PHP/FI (Personal Homepage Tools) in 1995, everything changed. It became possible to create dynamic web applications that generated content on-the-fly and allowed users to interact with the once static web pages.

When Rasmus Lerdorf, the creator of PHP/FI, decided to release the source code of his project, the development went even faster.

Andi Gutmans and Zeev Suraski joined the project in 1997 and started working on PHP 3.0 as the official successor of PHP/FI. The development of PHP/FI was mostly halted. PHP 3.0 (which is a recursive acronym for PHP: Hypertext Preprocessor) was officially released in June 1998.

Shortly after the release, Andi and Zeev were already working on a rewrite of PHP’s core. It was finished in mid-1999 and the new engine, dubbed Zend Engine (comprised of parts of their first names, Zeev and Andi), was a huge success.

PHP 4.0, based on the new Zend engine, was officially released in May 2000.

After four long years, PHP 5.0 was released introducing a new object model and dozens of other new features. In 2010, PHP 5.3.1 is the latest stable release.

What’s PHP?

If you’ve never heard about PHP, even after reading my boring introduction you probably still have no idea what PHP is.

PHP is a scripting language that was originally created for developing dynamic web applications. The difference between PHP and a client-side language like JavaScript is that PHP code is executed on your web server, generating HTML that is then sent to the client. PHP can take an input, such as a date, and then spit out another date (maybe by adding 30 days to it), without showing the process of how that number was derived.

Overview of how PHP works.

The Development Environment

Since PHP is executed on the server, we’ll need one. The best way to develop PHP applications is offline using a server package installed on your computer. Alternatively, you could use a private server.

If you prefer developing on a live web server by FTP’ing your files every time you make changes — although not advisable — I can’t stop you.

But in this PHP tutorial, we’ll do it right and install a server package on our computers: XAMPP.

Installing XAMPP

It’s possible to download Apache (the name of the web server software) and PHP individually and then set it up manually. However, its way easier to use XAMPP, a bundled package containing the software we’ll need.

To install XAMPP, we obviously need to download it first. Go to the XAMPP website, select your operating system and start downloading the basic package. XAMPP is cross-platform, so it’s available for the Mac OS, Windows, and Linux.

When your download is finished, open it.

If you are using Windows like I am, pick this version.

An installation wizard will pop up when you run the executable file. You only have to specify a path (the default value is fine) and you are good to go. Because a lot of files are being copied, this might take a while.

This might take a while…

When it’s done copying files, a command screen will appear. It’ll ask you a few questions but most of them are just personal preferences. If you have no idea which option you should choose, just accept the default settings.

After a few questions, it’s done configuring and you’ll be asked what you want to do next.

Let’s disable HTTPS, Perl, and ASP. We are disabling them because we won’t need them. If you do want to use these later on (HTTPS is especially nice if you are developing a financial app or something that needs a secure transfer protocol), you can enable them at that point in time.

When the installation is complete, open the XAMPP Control Panel.

This is what your XAMPP Control Panel should look like.

On the XAMPP Control Panel, click the first Start button to start the Apache software. If you don’t want to open the control panel every time you want to start Apache, press the first SVC button. Press the Exit button to close the Control Panel.

Congratulations, your web server is ready for use! Point your web browser to http://localhost, take a deep breath and keep your fingers crossed.

If all goes well, you will see this default message.

Picking a Source Code Editor

Writing PHP code in your regular word-processing editor like Microsoft Word is not an option. It’ll add all sorts of junk (e.g. style definitions, proprietary characters, etc.) to your document — and PHP isn’t able to process that junk.

Junk! Open one of your Word documents with Notepad to find out what I am talking about.

Syntax Highlighting is Important

So you open Notepad and you’re ready to start writing a few lines of code. It’s time to test what you’ve written and PHP tells you that you forgot a single quote on line X, and it is therefore unable to run your script. If you are working with "a few lines of code," it won’t be hard to determine where you forgot the single quote.

But what if there are a "few thousand lines of code"?

Meet syntax highlighting. When enabled, instructions, declarations and so forth will have their own color (it’s not added to the document, so no junk!). Even without knowing what the following piece of code does, it will only take a second to find the missing single quote.

Finding the missing single quote is a piece of cake with syntax highlighting enabled.

Most source code editors have many other useful options (and some of them even have too many options). I prefer Notepad++ because it’s lightweight, simple to use and has everything you’ll need. Oh, and it’s open source — that’s always nice.

Is PHP Installed?

If you are unsure of your web host’s capability to run PHP, it’s recommended to follow this part.

Open Notepad++. Copy and paste the following into a new text document and save it as info.php (or any file name that you’ll remember) in your webroot.

<?php
phpinfo();
?>

The webroot is the directory which Apache uses to retrieve files from. For example, the webroot of Six Revisions contains a WordPress installation. As soon as a browser performs an HTTP request for sixrevisions.com, Apache (the server software that runs Six Revisions) will try to find a index.* file and will send it back to the browser (the client). If it’s not found, a list of files will be returned (if the Apache configuration allows directory listing — but at Six Revisions, it doesn’t).

Your webroot can be found in xampp\htdocs (the default value for Windows is C:\xampp\htdocs).

If you are using a web host, your provider should have given you FTP details for accessing the webroot so that you can transfer your files to your web server.

Now point your browser to http://localhost/info.php (if you’re using XAMPP). If the page looks similar to the image below, PHP is installed correctly!

PHP is installed correctly!

You just ran your first PHP script! phpinfo() is a PHP function which outputs information about PHP’s configuration on your web server. You’ll find that when you’re working on a new server environment, phpinfo() will be a function you’ll use at least once to see what the PHP and server configurations are. This function is also used in debugging migration issues; if you transferred a website to another web server and it suddenly breaks, you can check the PHP information on the new server to see differences between the old and new server.

If nothing happened, PHP isn’t installed correctly and thus the PHP code will not be parsed. Your browser will not recognize the <?php ?> tags and it’ll just ignore them.

The PHP Block

PHP is a beautiful language. As long as the web server knows that a specific file has to be checked by the PHP parser, you are free to put PHP blocks anywhere you want. A PHP block you say?

A PHP block is nothing more than a piece of PHP code. By having a PHP block in a specific file, PHP can easily find and process a block of PHP code.

Imagine the time it would take to process all the contents of a file to determine whether it contains PHP code or not! That’s why a PHP block is needed.

It takes only five characters to open a PHP block (<?php) and two to close it (?>). They look like HTML tags, but they give you the ability to do a lot more than HTML is capable of. Let’s try it out, shall we?

Note: Some servers have the option to use the short opening tag (<?) enabled. It’s been recommended for several years that you should not use the short tag and instead use the full <?php and ?> tag combination. With the widespread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context!

Go to your webroot (there are probably already some files in there, feel free to delete them if you want, we don’t need them) and create a new file called index.php and fill up the file as if it was a new HTML file. Or if you are lazy, just copy and paste it from below.

By pointing your browser to http://localhost, the index.php file will be served to your browser by default. You shouldn’t need to type http://localhost/index.php.

It’s just a blank file, nothing interesting. However, if we look at the source of the web page (right-click to view source in your web browser), we see the regular HTML tags but without a trace of the PHP block.

If the PHP block would have contained executable lines of code, the PHP parser would have processed them, but would still remove the complete PHP block afterwards so that your code isn’t shown to the public.

Hello World!

Our previous PHP script didn’t do anything; it’s time to change that.

Open the index.php file again and create a new line in the PHP block.

Put the line below inside the PHP block, save the file and then refresh your web browser.

echo 'Hello World!';

Your code should resemble the following:

<body>
<?php
echo 'Hello World!';
?>
</body>

Congratulations, you just ran your first working PHP script! Your browser should be showing "Hello World!"

You really did not need to use PHP to create a page like this; it’s just a tradition in the programming world to start learning a new language by trying to output these characters on the screen.

Yet again, the PHP block magically disappeared.

So what exactly is that line of PHP code? As you’ve seen, the characters between the single quotes have appeared on the screen. echo is a PHP function which takes care of that. echo would be analogous to the .write() method in JavaScript (as in document.write('Hello World!')).

Normally, a PHP function is called by writing down its name, followed by an opening and closing parenthesis. Because echo is a language construct of PHP, which means that it’s hard-baked into the language and not actually a function, the parentheses are not required. The last character of the line is always appended after a PHP statement.

With the echo function, it’s also possible to send HTML to the browser. In these examples, you could just as well use HTML instead of doing it via PHP; it’s just for illustrative purposes.

Escape Characters

echo '<p>Hello <strong>world</strong>!</p>';

Everybody likes to have his or her HTML full of indentation for readability. Because PHP deletes a linefeed (tabs, returns, spaces and such) immediately after the closing PHP tag, your HTML markup will not be properly formatted with indentation, which can make it hard to read.

What PHP does with beautiful indentation.

Sometimes you might want to specify indentation in an echo statement. This is done by including the linefeeds in your echo statement by escaping characters.

Note that manually including the linefeeds in an echo statement with only a single quote will not work. This is because PHP doesn’t scan echo statements with only one quote for escaped characters and treats it as a literal string except when a single apostrophe is escaped with a backslash (\).

Single quotes versus double quotes make a difference when working with strings.

This code, for example, will produce an error:

echo 'I'm PHP';

It produces an error because the string is being terminated incorrectly.

To fix this, you can do one of the following:

// Escape the apostrophe with a backslash
echo 'I\'m PHP';

// Use double quotes
echo "I'm PHP";

And with that, let’s call it a day.

Conclusion

Everything you’ve learned here might seem useless. Believe me: it is not. Without the knowledge of these fundamentals, it’s easy to go down the wrong path. I wish you luck in your exploration of this beautiful language, and I encourage you to ask questions and share your thoughts in the comments.

Related Content

About the Author

Elias Zerrouq is a young web developer located in the Netherlands. He specializes in back-end development (PHP and MySQL) and classifies himself as a non-designing web developer (front-end development is okay though!). Contact information can be found on his personal website.

Tip : if you are using Skype and Xampp together Apache wont start on ur computer coz both apache and skype use port 80 to connect. You can solve this by changing your default connection port in Skype – Tools => Options => Advanced => Connection => Uncheck “Use port 80 and 443…” and enter any no except 80 in the upper box .. :D . (Many people have this problem so you should add this in the post)

I find that there are two types of people that offer web development:
1. People good with design
2. People good with programming.
On occasion, I find someone that is good with both, and people like that are worth their weight in gold.

Very well done article. I have been trying to get a WAMP server to work on my computer. It doesn’t seem to work. I tried different WAMP servers too. None of them work. The default Apache port (80) is being used by IIS. Even if I change it to something like 8080 it doesn’t work. I am unable to figure out which port to use. Could you please suggest a fix?

Great job explaining the setup, but that’s already a very simple process with XAMPP these days. I also think it might be a little too basic, since it doesn’t really highlight any of PHP’s features. Showcasing advantages of server-side scripts might’ve been more helpful. Since XAMPP installation is well-outlined on their site, you probably could’ve spent more of the article’s efforts on the actual scripting rather than the setup.

Thank you Elias for this article, it’s good to know some basic stuff about PHP, especially the trick about the ‘ and “. I hope you’ll continue with mere articles about PHP as I’m just a beginner in this programming language.
Btw, you made just a small error in your article :
“a single apostrophe is escaped with a backslash (/)”
would be rather : “[…] blackslash (\)”

@Sid: Yes, there will be follow-ups to this one, exploring more topics related to PHP.

@Nagarjun Palavalli: Strange. I’ve heard weird conflicts like Skype being turned on or another app conflicting with WAMP. Might want to see if turning off internet-enabled apps will help (IM, Skype, etc.)

Great article Jacob, thank you! As someone totally noob to all this, my sticking point is between installing and configuring it at my end, and getting it published on the web. I have registered a domain name, so I now assume its a matter of purchasing a web hosting plan from the company then they will walk me through the steps of getting my stuff published? I know I sound like a douchebag. It’s just a general question I guess. At the moment I just use google sites and use DNS forwarding. I would like to be able to host my own PHP site, as it’s obviously more configurable than the trash templates googlesites gives you.

Regarding the Skype issue that’s because Apache use port 80 and Skype versions after 3.0.0 use the same port as alternative for incoming connections… You can simply disable this option from Skype settings.

@Piers: I didn’t write this post, but I’m glad you liked it. You’re not sounding like a “douchebag” — this guide, after all, is aimed at beginners (although this site is for web designers and web developers — so our assumption is that most of our readers are already familiar with the basics, such as FTP). As for your question, you need a hosting plan, yes. Once you have a web host, you FTP your PHP files to the server. Once you get a hosting plan, they will have specific instructions on how to set your DNS records to link with your domain name. Check out this domain name basics FAQ on Site5, a web host. They also have a guide for FTP which will allow you to put your files up online.

EasyPHP is a good alternative to XAMPP and the deprecated versions makes it easy to match up to your host environment. This article is well written, and particularly by such a young writer. I’ve been teaching PHP for years and it’s always the basics that catch new coders so it’s always nice to see attention to detail.

@Nagarjun Palavalli: This is particularly problematic with Win7, but with that said, IIS7 will run PHP as well, so there is no reason for XAMPP or other option in the first place. In any case, you have to modify both the hosts file that dictates the IIS options, as well as the apache config.

I don’t know about you guys, but I think its time jake wrote up a nice php tutorial that shows how to do a simple e-commerce site in wordpress as a step in the right direction following this tutorial. what do you think?

I’ve got multiple projects on the go so I’ve started storing them all in the xampp folder. I name my project folders htdocs-project1, htdocs-project2, etc. That way I can quickly rename the folder to htdocs for testing/debugging.

About midway through your article, under the heading “The PHP Block” you have made a note about making use of both the php opening and closing tags: and provided solid reasons for why you should practice this.

In a recent php tutorial, it was suggested that this isn’t in fact that case and that the end php tag should not be used.

Does this scenario boil down more to personal taste and habit, perhaps? If it does, which is the more trustworthy way for a beginner to follow?

Great article, obviously geared toward total newbies. I would suggest ignoring those that believe your posts are too simplistic and only geared to newbies. Often there are advanced users that skip things they “assume” you will know that just leaves people unnecessarily in the dust.

That scenario is much, much worse than being accused of keeping it too simple.

You can always include a link to a more basic post from a more advanced post. That way everyone is happy, the advanced PHP user can ignore the basic link, the newbie can go to the link to get more information.

Since you are advertising yourself as a back end developer, perhaps looking at both apache and non-apache http(s) back end servers in addition to Microsoft leaning layers. You can do this very inexpensively…I have a Pentium II with only 256MB of RAM running LAMP (Linux, Apache, MySQL, PHP) and while I would not recommend it for a web server today, functions just fine as a home server. Great for testing extensions of the PHP language meant for Linux and not other operating systems. My guess is you could pick a better server than that up for FREE today. I bought three of them (extra parts) for less than $100 over 6 years ago.

Another added plus to having a server with minimum memory is it forces you to write efficient code that will only serve more users on a current server with faster processors, more memory and better hardware. This technique was used in creating many of the current MMO game servers on the web today. Linux, SSH, SSL, PHP, MySQL, etc…all work the exact same way, you just cannot load up everything into memory.