Learning PHP: Get Started Using PHP

Sep 12 2010 by Elias Zerrouq | 49 Comments

Learning PHP: Get Started Using PHP

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.

What's PHP?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.

What's PHP?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.

What's PHP?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.

You’ll need a text editor like Notepad — or better yet Notepad++. Text editors produce plaintext and that’s the only thing PHP understands.

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.

There are a lot of source code editors which offer syntax highlighting. (Check out this list of text editors for developers.)

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?

We’ve got a web server up and running and installed (XAMPP), a source code editor (Notepad++ or your preferred source code editor) — but we haven’t checked whether PHP is installed correctly or not.

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.

<!DOCTYPE html>
<html>
<head>
  <title>My first PHP script</title>
</head>
<body>

</body>
</html>

Now it’s a piece of cake to put a PHP block between the opening and closing body tag.

<!DOCTYPE html >
<html>  
<head>  
  <title>My first PHP script</title> 
</head>
<body>
<?php

?>
</body>
</html>

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.

It has been removed by the PHP parser.

Because our PHP block didn’t contain any executable lines of code, nothing else happened.

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 (\).

echo "\nHello World, I'm using \tindentation.\n";

echo '\nHello World, I'm using \tindentation.\n';

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.

49 Comments

Eric Hoffman

September 12th, 2010

Great! Well written and easy to understand. I’m ‘fluent’ in PHP, but I’m sure beginners will learn a lot from this.

Eric

Johnny

September 12th, 2010

Maybe too basic in my opinion

abutt

September 12th, 2010

PHP INVENTED CGI AND SSI ALL BY ITSELF

Sid

September 12th, 2010

Explained very well Mate .. will there be any follow ups. Eager to Read them too .. :)
Cheers
Sid

Sid

September 12th, 2010

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)

David

September 12th, 2010

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.

Nagarjun Palavalli

September 12th, 2010

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?

Nagarjun Palavalli

September 12th, 2010

How do I bind it in such a way that if I type ‘localhost’ in the address bar it opens Apache instead of IIS?

Flick

September 12th, 2010

Thank you for a great introduction to PHP. I hope you’ll be writing more for a series so I can follow it step-by-step.

Bjoern

September 12th, 2010

Great Article!
PHP is one of the most important languages out there and compared to others rather easy to pick up.
I really like your “Overview of how PHP works.” graphic, it nails it.

B

Young

September 12th, 2010

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.

bwd

September 12th, 2010

Great article… this will help designers who know how to design but thought PHP is beyond their limits.

AlFrag

September 12th, 2010

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 (\)”

karl escritt

September 12th, 2010

Nice article, well written and good intro to the topic.

mssbee

September 12th, 2010

Thanks for the great tutorial. Looking forward to more.

Jacob Gube

September 12th, 2010

@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.)

@AlFrag: Thanks for the catch AlFrag, it’s been corrected.

Piers

September 13th, 2010

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.

sidd

September 13th, 2010

very useful for beginners

Aafrin

September 13th, 2010

Informative crash course about PHP for the beginners. I prefer apatana than the notepad to edit the PHP files. thanks…

Ahmad Alfy

September 13th, 2010

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.

http://alfystudio.com/blog/52-apache-and-skype-conflict.html

Jacob Gube

September 13th, 2010

@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.

aki

September 13th, 2010

Well said. Very good for beginners. I hope you do the follow up for this boy! Looking forward to it

John G

September 13th, 2010

I know just enough php to be dangerous, but I keep meaning to dive in more. It would certainly make my life easier if I would just buckle down and learn it already.

I prefer using MAMP (http://www.mamp.info/en/index.html) on my Mac, it’s a bit easier than this to setup. Thanks for the article!

logolitic

September 13th, 2010

I am really looking to learn php and I know it’s hard but never impossible. It’s a plus to be a designer and a coder as well. I added to my Bookmarks to take a look when I have more free time.

ddeja

September 13th, 2010

I think this article should be all about setting up environment. This way, we would have one good tutorial about something.

And right now sadly, this article is about nothing:
1) basic xampp installation – not configuration
2) basic of basic of php syntax

That’s it.

David

September 13th, 2010

Thanks, a really great introduction to PHP, i look forward to the follow up, hopefully on little more advanced PHP topics.

john

September 13th, 2010

Excellent article, very clear and understood right away.
Could use lots more plain straightforward how-tos like this.
Many thanks Elias.

Mat Rosa

September 13th, 2010

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.

robert

September 14th, 2010

Nice Tutorial, Very Good start and looking forward to the follow up…
@sid thanks for the tip

Ben

September 14th, 2010

Great introduction for PHP, I found it really usful, cheers bud.

Craig

September 15th, 2010

Thanks, great introduction to PHP, and covers the fundamentals very well.

Freeon

September 15th, 2010

what about on picking up a framework? CodeIgniter, or Yii?

Elias

September 15th, 2010

It’s awesome to read all the positive and supporting comments! Thanks guys!

Jeff

September 15th, 2010

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?

KT Dorjee

September 16th, 2010

Basic and usefull…, hoping for next step.

SL

September 16th, 2010

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.

Hope that helps someone,

Natalie

September 17th, 2010

very useful entry. nice introduction. thx.

Matthew Lowery

September 20th, 2010

I know PHP like I know English. But I read it anyway. It is a nice article, well done!

Christina

September 20th, 2010

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?

Craig Pennings

September 30th, 2010

I’m going to bookmark this post…. need to dig into php for my next freelance project.

Juegos

October 5th, 2010

Good post Elias, didn’t used XAMPP to make tests on my localhost, I used Vertrigo, maybe it’s a little outdated but I found it more user friendly. Thanks for this post.

cbemerine

November 15th, 2010

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.

omvaishnav

November 17th, 2010

very useful article for beginners.

Thanks

silver_light

February 5th, 2011

informative but too short found of next

Helle

March 7th, 2011

I use ASP and when testing locally I see “http://localhost” on my local pages. If I choose to try out PHP on my PC, will I run into trouble? Can both ASP and PHP run on the same PC?

Florin

September 24th, 2011

Hello,
I installed XAMMP on Win7 where II7 already exists. When I go to “http://localhost” I get the II7 image and cannot continue the PHP lesson. Anybody knows what’s the solution? Thanks

Dafren

November 29th, 2011

Where is the “Next” Button? too short. great Job.

Joel machado

August 30th, 2012

Very good article, will be useful for beginners.
Thank you!

Provex Sports

October 7th, 2012

Elias,

What a fantastic tutorial/article you have shared. I am in the process of learning PHP from the start, and your tutorial has answered a lot of questions I had. Thank you so much for this tutorial.

Leave a Comment

Subscribe to the comments on this article.