Official website for Web Designer - defining the internet through beautiful design
FOLLOW US ON:
Author: Steve Jenkins
18th June 2013

A Beginners guide to PHP – part 1

Everything you need to know to get up and running and become fluent in this key scripting language

A Beginners guide to PHP - part 1

Ever considered learning a second language? Well, how about five? That’s what will be required of you, if you intend to become a modern web developer. If you’re not careful, you may find yourself getting a little overwhelmed as you stare at confusing blog articles or technical books.

The key, as with anything, is to take one step at a time. Would you fault yourself for not learning a spoken language in a month? Of course not. Then apply that same level of thinking to your programming journey. These things take a while, but as long as you continue pushing forward, you’ll be there in no time.

Step one is HTML. Understand what purpose a <div>

serves. Learn how to structure content using semantic tags. Build a basic, unstyled web page.

Step two, as you might have guessed, is CSS. Learn how to style elements on the page. Appreciate what ‘separation of concerns’ refers to, and how this applies to your HTML and CSS. Complete your first simple website.

Step three is when developers begin branching off into their own specialities. At this point, you could dive into the world of JavaScript, which is booming like never before. Or, you could instead focus your efforts on the backend.

Frontend or backend?

Confused by the difference between ‘frontend’ and ‘backend’? Think of the frontend as the tip of the iceberg that brought down the Titanic. It’s the part of the application that is visible to the user, and can be interacted with. The backend, on the other hand, handles everything else from persistence, to validations, to routing. For the purposes of this article, let’s assume that you’ve chosen the latter option; the server-side, it is!

Unfortunately, once again, you come upon a handful of paths to take. Should you choose the most popular option – PHP? What about Ruby? The cool kids seem to prefer that these days. Then again, what if you have a beard? Is Python the correct choice. Most importantly, though, how could you possibly make a selection, when you have zero experience? In situations such as this – and in this author’s opinion – there is no wrong choice. And, certainly, there isn’t a thing prohibiting you from switching down the road. In fact, all developers are encouraged to learn multiple languages! For now, however, the key is to pick just one and learn it well.

While it’s true that PHP is not the most beautiful of languages, there’s no denying the fact that it dominates the web. In fact, it’s the world’s most popular scripting language. The benefit to this is that you may rest assured that every PHP question has already been asked, solved, and documented. There’s comfort in knowing this. Though you’re at the most fragile stage of your learning, a massive, friendly community is at your doorstep, ready to help. Even better, PHP is experiencing a modern renaissance like never before, thanks to tools like Composer and Laravel.

What is PHP?

PHP, an acronym for ‘PHP: Hypertext Preprocessor’ (yes, developers love their recursive jokes), is a scripting language that was built specifically for the web. Chances are high, though, that this still means nothing to you. Scripting language? Huh? When would you reach for PHP over simple HTML? Well, perhaps an example is in order. Assuming that you’ve successfully installed PHP, create an `index.php` file within a new folder on your desktop, and add:

001 < ?php
002 echo ‘Hello world’;

Yes, it’s the ubiquitous ‘hello world’ example that you’ll become quite familiar with as your skills progress. Every language/framework/tool has one!
In order to run this code, use PHP’s built-in server. Switch to your favourite command line tool (Terminal, for Mac users), ‘cd’ to the project folder, and boot up the server with ‘php -S localhost:8888’. This command translates to, “Run a server, and make it accessible from my browser at localhost, port 8888.” Go ahead and try it out! Open Google Chrome, browse to ‘localhost:8888’, and you’ll see ‘Hello world’ on the page! Nifty! ‘echo’ is a language construct that does nothing more than output a given value.

Admittedly, this isn’t the most exciting thing in the world. In fact, you’re likely thinking to yourself, “Why couldn’t I write ‘Hello world’ directly into the HTML page, and remove the need for PHP all together?” It’s true; for this example, it serves no purpose. However, a scripting language like PHP becomes particularly useful when the output should be dynamic in nature. What if, rather than ‘world’, you want the greeting to reference a value passed through the URL’s querystring (the text in the address bar that comes after the question mark). Here’s an updated example, which you’ll see accomplishes just that!

001 002 echo ‘Hello, ‘ . $_GET[‘person’];

This introduces a few new techniques. Firstly, the single period that separates the ‘Hello’ string and that confusing ‘$_GET’ allows you to concatenate (or group) values. In this case, we wish to print “Hello” and then the value represented by ‘$_GET[‘person’]’. This is what we refer to as a super-global array. For the sake of simplicity, think of this as a way to ‘GET’ a value from the URL’s querystring.

Test this out by loading ‘localhost:8888/?person=Joe’. If configured properly, the web page should now display “Hello, Joe.” Play around with it by replacing ‘Joe’ with your own name. Notice how the output updates each time the page is refreshed? This simply wouldn’t be possible with static HTML.

One of the keys to mature programming is considering every possible path through your code. For example, what if no ‘person’ key is available? Perhaps the query string was omitted entirely. In that case, an error will certainly be thrown, as the ‘person’ key won’t exist. So what’s the solution? While it’s true that this is nothing more than a simple example, it’s still very important to consider all possible outcomes. Let’s provide a default.

001 002 if (isset($_GET[‘person’])) {
003 $person = $_GET[‘person’];
004 } else {
005 $person = ‘Joe’;
006 }
007 echo ‘Hello, ‘ . $person;

Though there are more streamlined ways to allow for this, the example above is an excellent starting point. It’s also your first introduction to conditional statements. Approach your code in the same way that you would handle scenarios in real life. For example, “If we are out of milk, then go to the store. Otherwise, stay home.” This line of thinking could be translated to PHP, using the following logic:

001 $outOfMilk = true;
002 if ($outOfMilk) {
003 echo ‘Going out to the store.’;
004 } else {
005 echo ‘Breakfast is served.’
006 }

Here only a single line of text will be printed to the screen. The value of the variable (a dynamic value), ‘$outOfMilk’, will determine the control flow.
Returning to the previous example, as long as ‘$_GET[‘person’]’ is set (think of this as a pseudo-name for ‘is available’), then create a new ‘$person’ variable equal to its value. Otherwise, apply a default. If you return to the browser, you’ll see that it should now function correctly, regardless of whether the ‘person’ key exists in the querystring.

Security

Unfortunately, we’re still not home free. A key programming best practice is to place security at the forefront of every action. Even with this incredibly basic example, we’ve opened the door to one of the most widespread security issues on the web: XSS (Cross-Site Scripting). A true understanding of this is absolutely beyond the scope of this introductory lesson (entire books have been written on the subject), however, here’s a basic illustration: what if ‘$_GET[‘person’]’ is equal to, not a string, but a script?

001 http://localhost:8888/?person=< script type=”text/javascript”>// < ![CDATA[
// < ![CDATA[
alert( ‘ATTACK!’)
// ]]>< /script>

Because this value has not been sanitised, upon execution, in some browsers, you will see that an alert box is displayed.
Webkit-based browsers (think Chrome and Safari) now provide protection against these sorts of attacks. However, this wasn’t always the case, and still isn’t in the likes of Firefox and Internet Explorer.

Yikes! We can’t have that. While modern society dictates that a man is innocent until proven guilty, the same is not true for the programming world. All user input is guilty until sanitized! Here’s an updated example which does this very thing:

001 < ?php
002 if (isset($_GET[‘person’])) { 
003 $person = $_GET[‘person’];
004 } else {
005 $person = ‘Joe’;
006 }
007 echo ‘Hello, ‘ . htmlspecialchars($person, ENT_QUOTES);

With this modification, should someone attempt an XSS attack, we’ll be ready! ‘htmlspecialchars’ is a native PHP function that translates various symbols to their entity counter-parts. ‘&’ becomes ‘&amp;’, ‘<’ becomes ‘&lt;’, etc. This makes it the perfect tool to provide that extra bit of security. ‘<script>’ is meaningless if it is converted to ‘&lt;script&gt;’ before being executed. The user will simply see:

001       Hello, <script>alert(‘ATTACK!’)</    script>

Great; no harm done!

Functions

While PHP ships with a plethora of native functions, there will certainly be times when you require your own. Luckily, they’re a cinch to write. Think of a function as a reusable piece of logic that can be abstracted away, so that it may be identified and called, using a readable name. Perhaps you run a nightclub (not likely if you’re reading this!), and need an easy way to accept a person’s birth date, and calculate whether he or she is at least twenty-one years old. A custom function would be an excellent way to accomplish this task.

The first step is to define a new function, called ‘isAdult’. Functions may accept outside input, which can then be operated on. This allows the returned data from the function to be dynamic. In this case, to determine if a person is an adult, we need to know their year of birth. The final step is to return either ‘true’ or ‘false’, dependent upon whether the current year minus the person’s birth date is at least twenty-one.

001 function isAdult($yob) {
002 $currentYear = 2013;
003 return $currentYear – $yob >= 21;
004 }

It’s really quite simple! Now, we only need to pass it off to the bouncer. A function may be triggered, or called, by referencing its name, followed by a set of parenthesis: ‘isAdult()’. However, if the function requires an argument, then you may specify it within these parenthesis, as illustrated below:

001 if (isAdult(1985)) {
002 echo ‘Come on in!’;
003 } else { 
004 echo ‘Please leave now, before I call your mother.’;
005 }

There’s one problem with this ‘isAdult’ function. The current year has been hard-coded. Sure, it will work throughout 2013, but what about next year? It seems that this value, too, needs to be dynamic. PHP provides a ‘date’ function, which can be used to calculate the current year. As such, the function may be updated to:

001 function isAdult($yob) {
002 $currentYear = date(‘Y’);
003 return $currentYear – $yob >= 21;
004 }

LOOK OUT FOR PART 2 – COMING SOON

  • Tell a Friend
  • Follow our Twitter to find out about all the latest web development, news, reviews, previews, interviews, features and a whole more.
    • leicester web design

      Really its a very good information about php.So dear can you tell me how can I find the other part of the beginner’s guide to PHP.