Você está na página 1de 101

Introduction

Welcome to your first PHP course on unclassroom. At unclassroom, we believe that the best way to learn web development is by building mini projects. So, before we even begin this course, let us actually create a very simple application that searches Facebook for public posts containing a search term. All you need to do to create it is hit the blue "Run Code" button.

Note:
When you hit the 'Run Code' button, you will see a popup with the link to the app that was created. You will also be able to share the app you created from that popup. Run Code

Exercise

<?php require '../WEB-INF/php/includes/appengine.php'; $search_term = urlencode(" "); $url = 'http://graph.facebook.com/search?q='. $search_term . '&type=post'; $output = get_url($url); $data = json_decode($output, true); $posts = $data['data']; $count = count($posts); echo "<h1>Searching for $search_term on Facebook</h1>"; for($i = 0; $i < $count; $i++) { $post = $posts[$i]; $user_id = $post['from']['id']; echo "<img src='" . "http://graph.facebook.com/$user_id/picture" . "'><br>"; echo $post['message'] . '<hr>'; } ?>

As you continue to learn, you will be building multiple apps such as this one. In each case, we'll be hosting those apps for you (for free) so please do share the apps you build with your friends or coworkers. Do also let us know at our (un)classroom group when you build something cool and we're really looking forward to seeing what you build.

Tip:
You can easily post to our group by using the 'Ask a Question' box on the right column of every activity page. BTW, we think of every page as an activity, meaning you will learn something useful, or even better, build something with what you just learnt.

What is PHP?
PHP is a very popular programming language that is best suited for web development. It is a server side language which means that PHP scripts (files) are executed (run) on a server. The output of the script is then sent to the client (usually a browser) where it is viewed by a user. We'll see how PHP works in greater detail later on in this course but now let us first understand why PHP is awesome and why you should learn it.

Note:
PHP actually stands for PHP: Hypertext Processor. If you don't understand what that means, don't worry about it :-). Before we continue, let us quickly run the first PHP program.
Run Code

Try It Out

<?php echo "Hey, this is so simple!"; ?>


Do you see how simple PHP is? The above program basically just outputs (displays) the sentence "Hey, this is so simple!". You will learn how this program works later on in this course but you already know that PHP isn't hard! Now, try making the script below output:

12345
Run Code

Exercise

1 2 3 4 5 <?php echo "Hello world!"; ?>

What part of the program will you change? Feel free to experiment and find out. What you just did (try changing something and seeing what happens) is a great way to learn programming. However, once something works, you should also spend sometime understanding why it worked. YES, reading (the right book ;-) can actually be useful!

Why you should learn PHP


PHP is one of the easiest languages to learn and it also happens to be a very popular programming language. How do we know it is popular? Well, some of the largest websites in the world such as Facebook.com & Wordpress.com use PHP. The next time you log into Facebook, you're actually using a website built in PHP.

Note:
In fact, the Facebook 'like' button is nothing but a PHP script embedded in the HTML page using an iframe. Google what an 'iframe' is if you don't know. Here is the actual link to that iframe that is embedded on this page:

https://www.facebook.com/plugins/like.php?api_key=23632332645743 4&channel_url=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd _arbiter.php%3Fversion%3D9%23cb%3Df8e894ed%26origin%3Dhttp%253A% 252F%252F127.0.0.1%253A8080%252Ff2716709fc%26domain%3D127.0.0.1% 26relation%3Dparent.parent&extended_social_context=false&href=ht tps%3A%2F%2Fwww.facebook.com%2Funclassroom&layout=standard&local e=en_US&node_type=link&sdk=joey&send=false&show_faces=true&width =225


Notice the 'like.php' part? Yes, this is a PHP script!! You can also view just the like button on a separate page.

This is what Facebook has to say about PHP:


PHP is an incredibly popular scripting language which makes up the majority of our code-base. Its simple syntax lets us move fast and iterate on products.

Facebook Developers

It is a skill in demand
Indeed.com, a leading job search website has a section where they display the latest trends with respect to skills in demand. Here is a graph that shows the demand for PHP in the job market.

As you can see, there is a lot (and growing) of demand for programmers who know PHP. Graphs can sometimes be misleading so let us also compare the demand for PHP versus the demand for similar languages like Ruby and Python.

The above graph compares the total demand for PHP programmers versus total demand for Python and Ruby programmers in the job market. Clearly, PHP is a great language to know and is in great demand. That said, it is always good to know more than one language and Ruby & Python are increasingly becoming very popular. The graph below shows the percentage increase in PHP, Ruby and Python jobs and it is clear that while there are more PHP jobs in total, Ruby and Python have a greater percentage growth compared to PHP.

Summary

PHP is a great language to learn and you will quickly start building apps while also learning something that has a lot of demand in the industry.

PHP is Popular
There are a large number of websites and open source projects out there that use PHP. You have already seen that PHP ranks very well when it comes to job trends but that is not all. We also mentioned that very popular companies like Facebook.com and Wordpress.com also use PHP. Infact, Wordpress.org (the open source platform that powers Wordpress.com) is an extremely popular open source content management system.

Note:
If you want to learn Wordpress, please request a course at our group:https://www.facebook.com/groups/unclassroom/ We take requests for courses seriously :).

Partial list of PHP open source projects


Content Management Systems

Wordpress Joomla Drupal

E-commerce

Magento

Forum

PunBB phpBB

Social Networking

Buddypress Elgg

Portfolio

Mahara

E-learning

Moodle

... and many many more. Clearly, there is a lot that you can work on after you learn PHP. You can get a great job, build a product or even contribute to open source projects like the ones above.

First PHP Program


Let us start with a simple PHP program.
Run Code

Try It Out

<?php echo "Hello world!"; ?>


Wasn't that easy? Now let us learn a little bit about the program we just wrote. Every program in PHP must start with a PHP start tag which is <?php and must end with a PHP end tag which is?>. When a PHP program is run, the code between these tags is executed by the server.

Quick Quiz:
The PHP start tag is and the PHP end tag is .

Also, you can only view data that is output from the PHP program. In this case, we're outputting the sentence Hello world!. This sentence is also known as a String in PHP. You will learn more about Strings later on but for now you only need to know that a String is just a sequence of characters (letters, numbers or symbols). Strings should always be enclosed within either single or double quotation marks (you have to use the same type of quote at both ends).

In the above program, we used double quotation marks to enclose the String. The following are all valid examples of Strings.

"Hello world" 'PHP is fun' 'My phone # is 999999999' 'I currently feel like &%^&^%^$%%$%'

The following however are invalid Strings.


123 (Not enclosed by quotes.) "Hello' (The same type of quote should be used at both ends) "Hello there (Forgot to add a double quote at the end)

Quick Quiz:
Complete the String to make it valid: "Good morning Strings need to be enclosed by either .

or double quotes at both ends.

You're doing great so far! Let us take another look at the PHP program. Do you notice the wordecho before the String? echo is a language construct in PHP which means that it provides some functionality. The specific functionality it provides is (any guesses?) that it helps output data from the program.

Quick Quiz:
The command is used to output data from a PHP program.

Also, the entire line echo "Hello world!"; is known as a statement in PHP. A statement is nothing but a piece of code that does something. In this case it outputs the text "Hello world!". Since this statement uses the echo command, it is also called an echo statement.

Note:
All statements in PHP must end with a semicolon ;. Notice the semicolon at the end of the echo statement?

Tip:

You can use output more than one string by adding multiple echo statements. You can also make these strings appear on separate lines by outputting a HTML line break tag<br> after each string is output.
Run Code

Try It Out

<?php echo echo echo echo echo echo ?>

"Line 1"; "<br>"; "Line 2"; "<br>"; "Line 3"; "<br>";

OK. Enough learning for now, let us quickly build a simple application. We've already added a simple PHP program for you. Feel free to modify it to output whatever you want it to. Run Code

Exercise

1 2 3 4 5 <?php echo "Let's begin!"; ?>

From Wikipedia:
PHP is a general-purpose server-side scripting language originally designed for Web development to produce dynamic Web pages.

Wikipedia

What does all of this mean?


Let us look at each sentence one by one and understand it.

PHP is a general purpose language


PHP can be used for writing software in a variety of application areas.

PHP is a scripting language


For now it is enough if you understand that some programming languages need to be compiled and executed (such as C, C++, Java) whereas other languages (such as PHP, Python) are interpreted by an interpreter. If you don't understand what this means, never mind. You will understand this better as you continue learning programming.

PHP is a server side language


PHP runs on the server. You also have scripting languages that run on the client (your browser) such as Javascript.

PHP is used for producing dynamic pages


Static pages such as .txt files or plain .html files display the same information no matter which user sees the page or how many times you reload the page. They are static because their output is always the same unless a change is explicitly made to the contents of the file. Dynamic pages on the other hand are able to change the output displayed based on various factors. This could be to display a logged-in user's information or to display the output of a search query.

Note:
A dynamic page can also be made to produce static output (just like your Hello world PHP program), that is, the output never changes. Therefore, the real difference is that static pages always show the same output unless the page itself is modified (code / text) whereas dynamic pages can display different output even without a change in its code / text becauses of changes in say data stored in a database or in reaction to some user input. As an example, the following is a static page:
Run Code

Try It Out

<div> The number is 2. </div>


You can try clicking the run button as many times in the above program and you will always see the same output: "The number is 2". The following program is a dynamic program which outputs a random number.
Run Code

Try It Out

<?php $rand = rand(10, 1000); echo "The number is $rand."; ?>


Now try running the above code a few times and see what happens. You will notice that the number displayed changes with each run. This is an example of a dynamic page.

Quick Quiz:
PHP is a general purpose language that runs on the from the program is then displayed in your browser. . The

Note:
How does the server run PHP? Just like how you need to install software on your computer to perform a certain task, PHP also needs to be installed on the server. Sometimes servers come preinstalled with PHP and at other times, you will have to install PHP manually. Installing and configuring a server that supports PHP is an advanced topic and is out of scope for this course.

Checking if the server supports PHP


Let us say you're given access to a server and you want to find out if it supports PHP. One quick and easy way to test it is by creating a simple PHP file (say index.php) that just has one echo statement (to output some text). Then when you access this file via a web browser, if you see the sentence displayed, it means that the server supports PHP. Otherwise, you will either see an error or the actual text of your program displayed. While the above method will work, you often want to know more information about the server's support for PHP than whether it just supports it. This is where a function called phpinfo() is very useful.

A function is nothing but some code that provides a specific functionality and in this case thephpinfo() function will output a lot of information about the server's support for PHP. You don't have to understand how to read this output or where you will use it but as you continue learning, you will understand where and how to use this information. For now, it is enough if you understand that there is a function called phpinfo() that will give you information about the server's support for PHP and using this function is also a great way to find out if the server even supports PHP.
Run Code

Try It Out

<?php phpinfo(); ?>


When you run the above program, you will see something like:

Notice the word 'quercus'? We will come back to this in a bit. However, when you usually run the same command on a server you own or on a hosting service, the output will look like:

The reason for this difference is that unclassroom's platform is completely built in Java and Quercus (remember the word you noticed?) allows us to run PHP code on our platform. In other words, Quercus is an implementation of PHP in Java while the usual PHP is implemented in C. This is just for your information.

Sample PHP Programs


Let us now run a few PHP programs to get a sense for what you will be able to build very soon. We're here to help you learn PHP and build apps :).

Note:
Try reading the following programs and understand how they work. If you are unable to, don't worry as every concept will be explained in detail in a later chapter. We want you to get comfortable reading code and trying to figure out what it does because that is what you will have to do even after 10 years of experience in the IT industry :).

Hello world!
Let us start with a simple program that will output the string "Hello world!".
Run Code

Try It Out

<?php echo "Hello world!"; ?>

Pyramid of Numbers
You can also write interesting programs in PHP. Here's one that outputs an interesting pattern of numbers.
Run Code

Try It Out

<?php for($i = 0; $i <= 10; $i++) { for($j = 0; $j <= $i; $j++) { echo $j . ' '; } echo "<br>"; } ?>

Parrot out your name


A PHP program to accept your name as input and display it back to you. This is also an example of an HTML form. You will learn all about forms in a future project.
Run Code

Try It Out

<?php if(isset($_GET['name'])) { $name = htmlentities($_GET['name']); } ?> <?php if(isset($name)) { ?> Your name is <?php echo $name; ?>! <?php } else { ?> <form method='GET'> <label for='name'> Please enter your name</label> <input type='text' id='name' name='name'> <input type='submit' value='submit'>

</form> <?php } ?>

Pepsi in Tweets
Here is a really simple program that searches Twitter for tweets that contain the word 'Pepsi' and displays the first 10 results. Isn't that cool? You'll be learning how this works real soon :).
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://search.twitter.com/search.json?q=pepsi&include_entities= false&result_type=recent&rpp=10'; $output = get_url($url); $data = json_decode($output, true); $tweets = $data['results']; $count = count($tweets); echo '<h1>Pepsi in Tweets</h1>'; for($i = 0; $i < $count; $i++) { $tweet = $tweets[$i]; echo "<img src='" . $tweet['profile_image_url'] . "'><br>"; echo $tweet['text'] . '<hr>'; } ?>

Tip:
We will be looking at the above program in greater detail later on in this course. So, please try and understand what is going on and later it will all make sense.

...& lots more


There are literally tons of cool applications and mini apps you can build with PHP and at unclassroom, you will build while you learn. I know you are itching to modify some of these programs and play with them. Below is a code editor where you can do just that! Feel free to copy paste a program into the code editor and modify it. Don't forget to post the link to what you build along with a brief description of what it does using the 'Ask a Question' box on the right column.

Reading Code
In this chapter, we're going to do something interesting which also happens to be something very important. We're going to introduce you to the art of reading code. What does that mean? You see there are many concepts that you need to learn before being able to write complete apps. The irony here is that programming is fun mainly because you can create these cool apps. So at unclassroom, we've come up with what we call fill-in-the-blank exercies where you will fill-in blanks using concepts you're supposed to know even though you may not fully understand how the entire program works. Doing this will help you immediately see how the concepts you're learning are actually used in various situations. You will also have an opportunity to read these programs and try and see if you can understand what the full programs do. When we talk about readability of programs, there are two things you should keep in mind. Before we tell you what they are, take a look at the following two programs.

<?php $a = $b = $c = $d = echo ?>

2; 2; 8; $b + $a * $c; $d;

What does the above program do? Is it even possible to figure it out from looking at the program? Looking at it, you know there are three variables $a, $b and $c which arr then used to compute the value of a fourth variable $d. Beyond that, the code does not give you much more information does it? Now suppose you are working somewhere and your boss comes to you and tell you to that the above code has a bug (meaning it does not work correctly) and asks you to correct it what would you do? You have no idea what it is supposed to do so how can you possibly figure out what is wrong with it? This is where readability of code comes in. Now let us look at a different version of the same program.

<?php /* This program computes the final velocity

* of an object given its initial velocity, * time, and accelaration * using the formula v = u + a * t */ $u = $a = $t = $v = echo ?>
Now is it clear what the original program actually did? Was the second program more readable? Definitely! right? So what was different? Firstly, we added comments (you will learn more about comments in future courses) to the code that explained what the program did and what each variable represented. Secondly, we used variable names that are fairly standard in physics to represent velocity, acceleration and time etc.

2; //initial velocity in m/s 2; //acceleration in m/s^2 8; //time in seconds $u + $a * $t; //final velocity in m/s $v;

Note:
You might also want to consider using more descriptive variable names such as$acceleration, $time etc. In this case since we're dealing with an area (kinematics) in which there are fairly standard ways to represent these quanities as v, u and t etc., we opted to use the short form instead of the full variable name. The assumption here is that someone who would want to read this code knows physics and so will have no problem understanding what the variables actually represent. That said, you should pick variable names wisely given your specific situation.

Comments
A comment in PHP code is a line that is not read as part of the program. Its only purpose is to be read by someone who is editing the code. So why use comments?

To help others understand your code When working in a team, you should add comments to your code describing what it does. This helps others understand your program.

To remind yourself what you did Sometimes, you may revisit a particular part of your program after many months or even years. Leaving comments will help you understand what the code does and also why it was written in a specific way. Without comments, you may have forgotten why the code was written and what functionality it provides and so maintaining the software may become very difficult.

Here is an example of a program with comments:

<?php //This line is a comment. echo 'The line above is a comment'; ?>
Comments in PHP can either be a single line or span multiple lines.

Single-line Comments
Single line comments are used when you want to comment out just a single line. To comment a line, prefix it with two forward slashes (//).

<?php //This is a comment echo 'The above line is a comment'; ?>

Multi-line comments
Multi-line comments are used when you want to comment out multiple lines. To comment multiple lines, enclose them within a /* and */.

<?php /*This is a first comment line This is the second comment line*/ echo 'Multi-line comment'; ?>

Practice
Please fill-in the correct type of comment.

Quick Quiz:
<?php

This function computes the sum of two numbers

function add_two_numbers($n1, $n2) { return $n1 + $n2; } First let us initialize the variables $a = 2; $b = 3; Then we output the sum of $a and $b echo add_two_numbers($a, $b); ?>

HTML and PHP


In the previous activity we saw how we can include multiple PHP sections within the same program. We also said code that is inside these tags will be executed while text outside these tags will be treated as just output. So, what text would you usually want to have outside the PHP tags? Well, since in most cases the output of a PHP file is being sent to a web browser (of the person accessing the PHP page), it makes a lot of sense to use HTML in these non-PHP sections. Let us see a example first of how this works:
Run Code

Try It Out

<?php echo "Hello "; ?>

<b><u>World!</u></b>
In the above program, the code within the PHP tags outputs

Hello
. Then the HTML is output as is so the final HTML that is sent back to the browser is: <b><u>World!</u></b>

Hello <b><u>World!</u></b>
The way this works is the following. If PHP is installed and configured on your server, whenever a file with an extension .php is loaded (by say a user visiting the URL in their browser), the server asks what is called the PHP interpreter to process the file. The interpreter then looks for the PHP sections in the file (between start and end tags) and executes the code in between these sections. The interpreter will skip sections that are outside the PHP tags and these are included in the output as is. What is seen by the user is then the final output which includes output from the PHP sections as well as whatever was in the other non-PHP sections.

Example
Run Code

Try It Out

<?php //PHP section echo '<h1>In PHP</h1>'; ?> <h2>Hey am in HTML now!!!</h2> <?php //PHP section echo '<h3>Back in PHP</h3>'; ?> <h4>In HTML again</h4>

Practice Time
So you can experiment and practice. It is important to understand how you can mix HTML and PHP in the same script.

Run Code

Exercise

<?php echo '<h1>In PHP</h1>'; ?> <h2>Hey am in HTML now!!!</h2> <?php echo '<h3>Back in PHP</h3>'; ?> <h4>In HTML again</h4>

Multiple Files
PHP lets you include other PHP scripts within a script. This is useful for a number of reasons.

Firstly, you can include libraries that you or someone else writes. This will allow you to use the functionality that the library provides from within your script.

You can organize your code in a better fashion. Instead of having a 1000 line PHP program, you can split it into meaningful parts (say 3 separate PHP files) and then include the files in a single script in the correct order.

You can reuse common code across multiple PHP scripts. For example, you can create a PHP file called footer.php that contains the code that will output the footer of your website (common across all web pages on your site). You can then include this file in the bottom of all the web pages. If you want to make a change to the footer, you only have to make the change in one place (footer.php) instead of in all 300 web pages. Can be very useful!!

There are multiple ways to include other PHP scripts in a particular script.

require require_once include include_once

Please visit each of the above URLs and understand the differences between each option.

Example 1
In the code below, we use require to use a library that defines and implements theget_url() function.

<?php require 'WEB-INF/php/includes/appengine.php'; $search_term = urlencode("coldplay"); $url = 'http://search.twitter.com/search.json?q='. $search_term . '&include_entities=false&result_type=recent&rpp=10'; $output = get_url($url); $data = json_decode($output, true); $tweets = $data['results']; $count = count($tweets); echo "<h1>Searching for $search_term on Twitter</h1>"; for($i = 0; $i < $count; $i++) { $tweet = $tweets[$i]; echo "<img src='" . $tweet['profile_image_url'] . "'><br>"; echo $tweet['text'] . '<hr>'; } ?>

Example 2
In the code below, we are including sections that are common to all web pages on our site. Again, we use the require statement.

<html> <head> <?php require '../../head.php'; ?>

</head> <body> <?php require '../../header.php'; ?> <div class='content'> ................. ................. ................. </div> <?php require '../../footer.php'; ?> </body> </html>

Practice 1
In this activity we're going to use what is called a for loop. We're going to write a program that will output the first 20 numbers (0 to 19). A loop is essentially a way to perform a specific task a certain number of times. In this case we use what is called a for loop to output the first 20 natural numbers. The first number we want to output is 0 and the last one is 19. So, we write a loop that outputs a single number every time it is run and we run the loop 20 times such that the value being output is incremented each time the loop runs. First, complete the echo statement in the program below and try running it.

<?php /* This program outputs numbers * from 0 to 20 (not including 20) * with line breaks between * consecutive numbers. */ for($i = 0; $i < 20; $i = $i + 1) { $i; echo '<br/>'; } ?>
Now read the program a few times and try and understand what is happening before you answer the following questions.

Note:

Please keep in mind that you will be learning about loops in detail in a future course. The goal here is to try and understand what the program is doing by reading it. It is absolutely fine if you're unable to figure it out but the fact that you tried will really help you as you continue learning. Suppose you wanted to make the program output numbers from 0 to 30 (not including 30) instead? What change would you make to the for loop?

for($i = ; $i < ; $i = $i + 1) { //rest of code is unchanged }


Now let us say you want to output only even numbers between 10 and 40 (not including 40) what changes will you make to the program?

for($i = ; $i < ; $i = $i + //rest of code is unchanged }

) {

Practice 2
We promised that you will be learning to write mini applications and this is the first one. We're going to write a simple app called Music Book. What the app does is, it retrieves public data available on Facebook about popular music artists / bands and displays the results. The program below makes use of a small library to retrieve data from Facbook. Once it gets the data, it uses another type of loop called the foreach loop to display information about the artists. Again, take your time to read the program and the comments and try and understand what it does and how it works. Then try the following exercise. First, complete the blanks in the program below and try running it. You will have to complete the following tasks:

The program is missing the PHP start and tags. One statement is missing the echo command. A semicolon is missing at the end of a statement.

Run Code

Exercise

// This program displays public data from Facebook // Require a library that will help us get data // from a given URL using the get_url() function require '../WEB-INF/php/includes/appengine.php'; //The URL from which we are going to retrieve data $url = 'http://graph.facebook.com/?ids=' . '15253175252,10376464573,19691681472' . '&fields=likes,name'; // Get public data about the artists // from Facebook $data = get_url($url); // The data is in the JSON format so // we need to decode it so it can be used $data = json_decode($data, true); //Output the app's title echo "<h1>Music Book</h1>"; // Output information about the artists foreach($data as $artist) { //Output the artist's name within a <h3> tag $artist_name = $artist['name']; echo "<h3>"; $artist_name; echo "</h3>"; //Output the artist's profile pic $artist_id = $artist['id']; $pic = "http://graph.facebook.com/$artist_id/picture"; echo "<img src='$pic'><br>"

//Output the number of likes the artist has //followed by a line (<hr>) $likes = $artist['likes']; echo "$artist_name has $likes likes on Facebook." . "<hr>"; }

Did you notice how easy it is to retrieve and mashup data from other sources such as Facebook? This is one of the cool things about web programming which is you can build interesting apps by using data from sites like Facebook, Twitter & Crunchbase etc.

Practice 3
A great way to learn programming is by taking programs that already work and then modifying them using your own ideas. In this activity, you're going to modify the app you created in the previous activity by making a number of changes. You may wonder how you're supposed to make changes when you've hardly learned anything but we'll see how easy it is to make informed guesses about how the program works. Keep in mind that not matter how good a programmer you are, there will always be something new to learn and you will most certainly come across some code that you don't understand fully. So, let's get started.

Tip:
Notice that we have already entered the code for you in the editor so you can difrectly start making changes. The program currently outputs data for just three artists: Coldplay, Lady Gaga and Michael Jackson. Try modifying it to also output information about your favorite artist. First thing we need to figure out is which part of the program needs to be modified. If you read the program carefully, you will notice that nowhere in the program do we explicitly use any of these artist's names. However, you will notice some code that contains weird looking numbers separated by commas.

//The URL from which we are going to retrieve data $url = 'http://graph.facebook.com/?ids=15253175252,10376464573,19691681 472&fields=likes,name';

If you try running the program and see the app, you will notice that the app displays the names and number of likes of three artists. Look at the code fragment above and you will notice that it mentions fields such as likes and name (&fields=likes,name). Notice carefully and you will see that there are actually three long comma separated numbers in the code fragment above and you can guess that these numbers are probably Facebook ids for the artists or bands. Look again and you will see that the text before these numbers actually says ?ids=. Finally, notice that the URL in the above fragment starts with "http://graph.facebook.com" but you don't know what that is so try Googling it. Notice that we wrap the URl within quotes when we google it because we want to know what that URL is about but we don't want Google to think that we want to navigate to that URL. When you Google, you'll see the top few results that all point to something called "The Graph API". The Graph API is basically a way to access information from Facebook and in this case we're using it to access information about music bands and artists. Now that we've understood what is happening, let us complete the exercise. There are two things you need to do to accomplish this.

Find out the Facebook id for your favorite artist. Figure out where in the program to add the id.

To figure out the Facebook id for your favorite artist or band, you should search Facebook using the graph API. This is quite simple to do. For example: if you want to find out the id for Michael Jackson, navigate to the following URL. http://graph.facebook.com/search?q=michael jackson&type=page When you open the above URL, you will see a list of Facebook pages that have the words "Michael Jackson" in the title. Just pick the id of the first page that shows in the result. Now, replace "Michael Jackson" with the name of your favorite artist and repeat the process to get their id. Once you get your favorite artist's id, you already know where you should add it so go ahead and modify the program. When you're done. click run once again to launch the modified app. Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

<?php // This program displays public data from Facebook // Require a library that will help us get data // from a given URL using the get_url() function require '../WEB-INF/php/includes/appengine.php'; //The URL from which we are going to retrieve data $url = 'http://graph.facebook.com/?ids=' . '15253175252,10376464573,19691681472' . '&fields=likes,name'; // Get public data about the artists // from Facebook $data = get_url($url); // The data is in the JSON format so // we need to decode it so it can be used $data = json_decode($data, true); //Output the app's title echo "<h1>Music Book</h1>"; // Output information about the artists foreach($data as $artist) { //Output the artist's name within a <h3> tag $artist_name = $artist['name']; echo "<h3>"; echo $artist_name; echo "</h3>"; //Output the artist's profile pic $artist_id = $artist['id']; $pic = "http://graph.facebook.com/$artist_id/picture"; echo "<img src='$pic'><br>"; //Output the number of likes the artist has //followed by a line (<hr>) $likes = $artist['likes']; echo "$artist_name has $likes likes on Facebook." . "<hr>"; } ?>

So far, you've literally learned just two or three concepts: echo command, statements and PHP start / end tags but you're already able to make trivial changes to programs even though you may not fully understand what is going on. Even if this is hard in the beginning, the more code you read and play with, the faster you will learn.

Practice 4

This is the last activity in this course and in this activity, you're going to draw a chess board :). The code for drawing the chess board has already been entered for you in the code editor. You should first read and understand what the program does and then modify it based on instructions in the quick questions setion. Modify the program to interchange the positions of black and white squares. That is, you should have black squares in places where there are currently white ones and vice-versa. Suppose you decide that the chess board should have 10 rows and 6 columns (instead of 8 rows and 8 columns), make changes to the program that will output a board with 10 rows and 6 columns. What if you decide that 'black' and 'white' are dull colors and you want to now use 'blue' and 'yellow' instead? How will you convert the black and white board to a blue and yellow one? Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <?php // This program draws a chess board //This function draws a single square //using HTML styles function draw_square($color) { $css = "float: left;" . "background-color: $color;" . "width: 30px;" . "height: 30px;"; echo "<div style='$css'>&nbsp;</div>"; } //This function starts a new row of the //chess board using HTML styles function start_new_row() { echo "<div style='clear: both;'></div>"; } //To draw the actual board we use two counters $row and $col to //represent rows and columns of the board. Now, since there are //8 rows and eight columns, these counters start at 0 and end //at 7 (total of 8). //Loop through each row one by one for($row = 0; $row < 8; $row = $row + 1) { //Within that row, loop through each column one by one for($col = 0; $col < 8; $col++) { //If the sum of the row number and column number is even //we draw a black square. Otherwise, we draw a white square. if(($row + $col) % 2 === 0) {

draw_square('black'); } else { draw_square('white'); } } //After we draw all the squares in a row, //we start a new row. start_new_row(); } ?>

Further Reading
Read the getting started section of the PHP manual completely. The manual is the authoritative source for information on PHP. http://us3.php.net/manual/en/getting-started.php

Tip:
Did you know that PHP is actually written in the C programming language? Now you know! Learn about server side scripting and client side scripting.

Server Side Scripting Client Side Scripting

Watch a simple video about how PHP works: http://www.youtube.com/watch?v=PemsuAfc7Jw

Note:
This is advanced. Understand the anatomy of a PHP request.http://www.slideshare.net/josephscott/anatomy-of-a-php-request

The Goal
In this section, you are going to build a profile page for a given Facebook user. Some of the concepts that you will be learning are:

Request - Response cycle Variables

Functions Arrays Operators

Again, just like the previous activites, you will learn these concepts by building mini applications.

Request Response
Before you continue learning PHP, it is important for you to understand how the internet works.

Note:
There is a lot of information in this article and please don't spend too much time reading everything in-depth. This course will be over before you finish :). That said, you should do a quick reading and understand what everything means or does and then you can always bookmark some of these links and spend more time reading it in greater detail. The W3C (world wide web consortium) has an excellent article on this subject that you must read. Here is a link to that article: http://www.w3.org/community/webed/wiki/How_does_the_Internet_work Now, that you understand what the request response cycle is, let us now understand how this works in the context of PHP.

What happens in a request response?


The following steps describe the request-response sequence when you load a PHP file from your web server: (abridged from) http://serverfault.com/questions/69696/how-does-server-side-technology-actually-work

A user requests a PHP file on your server http://www.yoursite.com/index.php (usually via a web browser).

Your Apache web server software receives that request and prepares to serve the appropriate information over the connection to that specific user

Apache's integration with PHP starts the PHP interpreter on your server and executes the PHP code in index.php.

That PHP code may in turn contain requests to get and/or set data from your MySQL database to use in the web page or for user or session management.

Your web server sends the remote user an HTML document that is put together through the above combination of PHP code, database information, and pre-written static HTML and CSS from your web site.

The request to the server happens via the HTTP protocol and HTTP defines several request methods. The method used tells the server what the request aims to do. The two request types we will be using in this course are GET and POST. Learn more about these and other request types at: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods

Example
As an example, let us see what happens when we load a Wikipedia page. I have captured the screenshots using Chrome's developer tools. I highly recommend that you learn how to use the developer tool (for chrome) or Firebug (for Firefox) if you are interested in web development.

What happens when you load a Wikipedia article?


In the screenshot below, you will see a number of requests that my web browser makes to wikipedia's servers (or other servers) to load the contents of the article. These requests may be for loading content, css, javascript, embedded iframes (like Facebook like button), AJAX calls to load data asynchronously or even analytics tracking calls (like Google Analytics). You will also see a Timeline that shows you the order in which these calls are made. This order is important to consider for performance reasons but that is out of scope for this course.

Let us look more closely at the first request which actually is a request to a PHP file (you don't see a .php at the end of the URL because it is possible to map a certain URL to a specific PHP file using what is called URL routing).

In the above screenshot, you will notice the type of request (GET) and the request headers that are sent to the server when your browser makes a request. You will also notice the response headers from the server. The status code 304 means that nothing has changed since the last request. You

can view a list of HTTP status codes and their meanings at: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes Finally, the response itself consists of the actual HTML source of the webpage that is then displayed by the browser.

Public Data from Facebook


In this activity, you are going to learn how to access public data from the Facebook API.

What is an API?
An API or Application Programming Interface is an interface that an application implements to allow other applications to communicate with it. For example, the Facebook API will allow us to communicate with Facebook's server and retrieve data / publish updates etc.

Helper library
In order to make requests to the Facebook API, we are going to make use of a helper libraryappengine.php that we have written. This library contains a function get_url() that will allow us to make a GET HTTP request to any URL and it will return the result (output) from that request as a String.

Note:
A function is a predefined piece of code that does something (provides a functionality). You pass inputs to it and the function performs some action using the inputs you supply and returns an output that you can then use in your program. Don't worry we will cover this in greater detail later in this course.

The best thing about a function is that (if written well) you don't need to know how it works. You just need to know what inputs to supply and what output to expect. This is just like how you use a phone. You know how to dial a number and what output to expect but you don't have to know how this works internally. The phone therefore provides a functionality (function) called 'call' that you have learnt to use. Before you use the function, you have to require the library. You have already seen how to do this.

<?php require '../WEB-INF/php/includes/appengine.php'; //we will enter code below

Access the data - get_url()


As mentioned earlier, let us now use the get_url() function to access public data about a facebook user. Let us say we want to access information about Michael Jackson facebook profile. You can do this by just visiting his facebook page but we want to do this from within our program. Therefore, we need his information in a form that can easily be processed by our program. This is where an API becomes useful. There are many forms (formats) in which APIs return data (the API documentation will usually tell you which formats they support) but popular formats are XML (extensible markup language) and JSON (javascript object notation). In this course, we will primarily be interacting with the facebook API and we will request the API to return the output in the JSON format. PHP makes it very simple to work with data in the JSON format and you will see how a little bit later. We said we are going to request data from an API, but, how do we do that? Well, it turns out that facebook specifies how to do this as part of their API documentation. You can access information about a particular facebook user from the following URL (replacewith the actual facebook username):

http://graph.facebook.com/<user-id>
So, to access information about Michael Jackson's page, we will use:

http://graph.facebook.com/michaeljackson
Now let us write the code to access his details.

<?php require '../WEB-INF/php/includes/appengine.php';

$url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); ?>

Output the data


Finally, we output the result we got from the API call.

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); echo $output; ?>

Try it out
Try accessing data from other facebook profiles or your own if you have a facebook account. Run Code

Exercise

1 2 3 4 5 <?php ?>

The output should look like the following:

This data is the JSON format. You can format JSON to view the structure more clearly using the website http://jsonformat.com/. Here is how that looks:

Suppose you want to access the public profile data of Lady Gaga whose Facebook id is 'ladygaga'. How will you do it? Run Code

Exercise

<?php '../WEB-INF/php/includes/appengine.php'; $url = 'http:// $output = echo $output; ?> / ($url); ';

What are Variables?


A variable is just like a container that can store a value (more specifically, it's just some space in the computer's memory where a value can be stored). Variables are referred to by their name which will usually tell you what value they contain. For example, the variable $school_name might contain the name of the user's school or the variable $current_temperature might contain the current temperature. All variable names are prefixed with a dollar sign ($). Let us take another look at the previous program we wrote:

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); echo $output; ?>

Quick Quiz:
The two variables in the program are $output and .

A value contained in a variable can change. In contrast, the value of a constant cannot change (you will learn about constants later). You can therefore assign a new value to $output.

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); //Assign new value $output = 'New output'; echo $output; ?>
Now when you run the code, you will see that the output is just the string 'New output'. Run Code

Exercise

1 2 3

Assigning Values
Notice that we assign a value to a variable using =. This equal to sign is called an assignment operator and it is used to assign a value to a variable.

Quick Quiz:
Assign the value 25 to the variable age.

Outputting Values
We use the echo statement to output the value contained in a variable. Yes, we can also useprint.

Quick Quiz:
Now, output the value stored in the variable age.

$age;

Variable Names
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. So, $name is different from $NAME.
Run Code

Try It Out

<?php $number = 10; $NUMBER = 20; echo "number is $number and NUMBER is $NUMBER"; ?>
Did you notice how $number and $NUMBER are two different variables? Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Examples of valid names are: $name, $_testValue, $tax_2012 Examples of invalid names are: $10gen (can't start with a number), $%marks (% is not allowed),marks ($ is missing). Learn more about variables from the PHP language guide at:http://www.php.net/manual/en/language.variables.basics.php

Quick Quiz:
Are the following valid variable names or no? Answer yes/no.

$_test $1password

Ensure Readability
You have already seen how choosing descriptive variable names is always better than choosing short (lazy) variable names. So, don't use names like $a and $b in your programs. Instead, use $age, $name etc. Also, different companies follow different coding conventions where they will specify how to name variables, functions etc. It is important for you to find out the convention where you currently work and then adhere to it.

prev next

Functions
We have already used a few functions in previous activities. For example, we used theget_url() function to retrieve data from the Facebook API. A function is a piece of code that you, or someone else has written that does performs an action and can be called (or invoked) from other parts of your program. A function is called (invoked) using its name followed by parenthesis (round brackets). You can also pass parameters to a function. Here is an example of a function without parameters:
Run Code

Try It Out

<?php echo rand(); ?>

The above function generates a random number. Now we are going to use the same function with parameters. The parameters specify that the generated random number must be within the first and second parameter.
Run Code

Try It Out

<?php echo rand(10,20); ?>


Therefore parameters are optional when it comes to the rand() function. You can also have functions that need a mandatory parameter to work correctly. A function may or may not return a value. Usually, a function is used to perform an operation and the result of that operation is then stored ina variable or passed to another function. That is, the value returned by the function is used again within your program. Example:
Run Code

Try It Out

<?php function add_two_numbers($n1, $n2) { return $n1 + $n2; } echo add_two_numbers(5, 10); ?>
In the above program the result from the function add_two_numbers() is used by the echo statement to output the sum. You can also have functions that do not return any value. Example:
Run Code

Try It Out

<?php function output_grid($rows, $cols, $color) {

for($i=0; $i < $rows; $i++) { echo "<div>"; for($j=0; $j < $cols; $j++) { echo "<span style='background-color: $color; margin: 3px;'> </span>"; } echo "</div>"; } } output_grid(4, 5, 'green'); ?>
In the above function output_grid(), there is no need to return a value as the sole objective of that function is to output a grid like structure as the output. The functions in the above two examples are what are called user defined functions. This is because we defined the function and it was not natively provided by PHP. You also have third-party functions that are provided by other libraries (such as get_url()).

Why do we need functions?


Functions are great for a number of reasons.

They enable you to write modular code. That means that you essentially break-up your program into small pieces and this helps improve the readability and maintainability of the program. This is because it is far easier to understand what a function does even from its name rather than trying to read 20 lines to understand what functionality those lines provide.

It is also easier to test / debug your program as it has been clearly divided into pieces that can be tested individually without testing the entire program. So, if we testadd_two_numbers() and it works fine, we know that the bug has to be somewhere else.

You can re-use code. Suppose you write a 1000 line program and you don't write it in a modular fashion, it will be hard for you to reuse parts of this program elsewhere. When you write modular code, you can nicely create a function library and reuse it anywhere that functionality is desired.

Functions increase maintainability. Suppose you re-visit your code after a year. How will you understand what it does if it is 2000 lines long? Or, suppose you hire a new person and that

person needs to work on code you wrote. It will be very difficult for them to understand what your badly written program does. Functions therefore help with maintaining your program.

Try it out
Write a function that will accept one parameter as input and return true if the number is prime and false if the number is not prime. This is a very interesting program because it touches upon a very interesting problem in theoretical computer science called primality testing. You can use Google to learn why this is such an important problem.

Note:
A team of two Indian students (just like you) and their professor won multiple international awards for their work in this area. You can learn more at:http://en.wikipedia.org/wiki/AKS_primality_test . Don't worry too much about the math and text at that link. This program is very easy to write for small prime numbers. It becomes harder and harder as the prime number becomes larger. Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <?php

//function should return yes or no function is_prime($number) { //complete this function } echo is_prime(1) . '<br>'; echo is_prime(2) . '<br>'; echo is_prime(4) . '<br>'; echo is_prime(100) . '<br>'; echo is_prime(87) . '<br>'; echo is_prime(237) . '<br>'; ?>

Further reading
Parameters can be passed to a function either by value or by reference. If you know C, you will understand what this means, else don't worry about this for now :). http://www.php.net/manual/en/functions.arguments.php PHP also has a very large number of predefined or in-built functions. You can view the entire list at: http://www.php.net/manual/en/funcref.php

Note:
Some of these functions are not turned on by default. You might have to change the PHP configuration file on your computer or server or sometimes even install a new package before you can use them. If your program throws an error saying the function does not exist and you are trying to use a function from the above page, please contact us and we will tell you what to do.

Processing Output
We are going to continue working on the program you were writing to create a Facebook profile. Here is the code that you wrote.

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); echo $output; ?>

Now, we mentioned earlier that PHP makes it very easy to work with JSON data. Let's see how. PHP provides two functions json_decode() and json_encode. The json_decode function helps convert the JSON data into a PHP datastructure that we can then use. The json_encode()function does the exact opposite where it takes a PHP datastructure and returns a JSON string as output. We want to convert JSON data into a PHP datastructure because we want to access the infromation contained in the JSON string. Now, try running this program (notice we use the json_decode() function before we output the contents of $output).
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); $output = json_decode($output); echo $output; ?>

Note:
Notice the line:

$output = json_decode($output);
Here what is happening the contents of the variable $output is being passed to the function json_decode() and the returned value is stored back in $output. What do you see when you run the above program? Did you see something like:

stdClass[]
This is because the json_decode function will convert JSON data into a PHP object (for those of you who know object oriented programming, others don't worry). There is also a way to make

json_decode convert JSON into a PHP array and you do this by passing a second boolean variable as parameter with its value set to true. Now try running the program below, what does it output?
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); $output = json_decode($output, true); echo $output; ?>
Do you see the output as:

Array
The next thing we are going to learn is arrays and how to use them but before that, we're still not done with this program. You see, before you even learn about arrays, perhaps it would be good to see what data this array contains. We have been talking about converting a JSON string into a PHP array and all that but let's see what it actually looks like. For this, PHP has two functions var_dump() and print_r(). Please understand what these functions do by reading the PHP reference.

print_r() var_dump()

Now, let us actually use the print_r() function to view the contents of $output instead of using the echo statement.
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); $output = json_decode($output, true); echo '<pre>'; print_r($output); echo '</pre>'; ?>
What do you see when you run the above code? Do you see something like this?

Now, it is much easier to see what that JSON string actually contained right? In the next few activities, you will learn about arrays and also how to create a profile using this data.

Try it now
What will happen if you use a var_dump() function instead of print_r function? What are the differences between the two? Try it and find out also do read about these two functions using the links we mentioned earlier. Run Code

Exercise

1 2 3 4 5 <?php ?>

Why Arrays?
We'll see in a bit what arrays are but first, let us understand why we need them. Suppose, you're given 5 variables: $color1, $color2, $color3, $color4 and $color5. Now, suppose you need to write a program that will output the names of all five colors one after another. The program might look like:

<?php echo $color1; echo $color2; echo $color3;

echo $color4; echo $color5; ?>


Now, suppose you need to output the names of 256 colors? Are you going to use 256 variables? Also, suppose you output $color234 after $color231 (missing two colors in between, how will you find the error? Will you manually count the number of colors displayed on your screen? These are some of the reasons why arrays are useful. You will learn more in the next activity.

Try it out
We don't have a specific exercise here but feel free to experiment. Don't worry a huge exercises only section is coming up after the next few exercises. Run Code

Exercise

1 2 3 4 5 <?php //Feel free to try out a program ?>

What are Arrays?


In order to output the names of 5 colors, we needed 5 different variables. Imagine a program where you have to output the names of 250,000 colors (including minor gradients)! Is there a better way to do this? Yes there is and its called an array. An array is nothing but a list and like any other list, it can contain a number of items.

Think of an array as a set of boxes placed next to each other in a line with each box containing a value (just like a variable). Each box has a number (called an array index) that specifies its location in the line and you can access the value stored in the box using this number.

Note:
There are actually two types of arrays in PHP. One is a regular array (similar to arrays in other languages such as C) and the other is called an associative array which is more like a map / hashmap (if you know Java). These topics are covered in greater detail later on but for now, you should understand that PHP has two types of arrays but we are only talking about regular arrays in this activity. A few activities later, we will learn about associative arrays. Going back to our example, instead of 500 different variables, you can create one array $colorsthat contains the names of all colors friends. Notice that the array just looks like an ordinary variable on the surface. The way we know whether it is an array or not is by using theis_array() function. Example:
Run Code

Try It Out

<?php $array1 = array(); echo '$array1 is ' . (is_array($array1) ? 'an ' : 'not an ') . 'array.'; echo '<br>'; $array2 = 'this is a string'; echo '$array2 is ' . (is_array($array2) ? 'an ' : 'not an ') . 'array.'; ?>
Notice the following line:

echo '$array2 is ' . (is_array($array2) ? 'an ' : 'not an ') . 'array.';

Here what we are doing is we are joining three strings. First string is '$array2 is '. The second string is either 'an ' or 'not an' depending on the output of is_array($array2) and the third string is 'array'. We are using the string concatenation operator (remember this) . (dot) to join the three strings. Now focus on this specific part:

(is_array($array2) ? 'an ' : 'not an ')


The code within the brackets is called an expression. An expression always evaluates to a value. In this case, this expression evaluates to true or false (ie. 1 or 0 in PHP). The ? and the : form what is called a ternary operator.

Ternary Operator
There are three parts in that expression right?

<expression1> ? <expression2> : <expression3>


So, all three parts are also expressions. In this case, the expression1 has to evaluate to a boolean value (true or false). Now, if the values of this expression1 is true, the second expression is executed else the third expression is evaluated.

Note:
You have to be careful when dealing with boolean values because PHP treats non-zero values (apart fom false and a few specific exceptions) as also true. So 'false' will be treated as true since it is a string and it is non-zero. The following values are considered FALSE:

the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables)

Every other value is TRUE! So, "Krishna" is TRUE, 5 is TRUE, "1234" is TRUE and even "FALSE" is TRUE.

Quick Quiz:
You can find out if a given variable is an array using the In PHP, 'FALSE' evaluates to the boolean value . () function.

Try it out
We don't have a specific exercise here but feel free to experiment. Don't worry a huge exercises only section is coming up after the next few exercises. Run Code

Exercise

1 2 3 4 5 <?php //Feel free to try out a program ?>

Accessing Elements
Suppose you're given an array, how do you access the individual items contained in it? Well, we said earlier that an array is just like a list. So, for example, consider a list of your friends. Now, if I ask you for the first friend on the list, you might say it's 'Matt'. The 3rd one might be 'John' and the 10th, 'Kate'. Similarly an array has what are known as indices (numbers) that are like the serial numbers on a list. Each index refers to a particular slot in which data is stored.

So, in the above example, the friend at the first array index is 'Matt', the third is 'John' etc. Now, one difference with a regular list that you write on paper is that these indices start at 0 and end at n - 1 where n is the number of items in the array. If there are 30 items stored in an array, its index starts at 0 and ends at 29 (30 -1). Now, how do you access data stored in an array? It's actually really simple:

$arrayname[<index number>]
Examples:

$friends[0]; //first item $friends[1]; //second item $friends[19]; //twentieth item


Here $friends is the array and the square brackets are used to access items contained in the array.

Try it out
Output all the colors stored in the array $colors one per line.

Note:
You must complete the program in the code editor below before you run it. Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11

<?php //Initialize an array $colors $colors = array('red', 'blue', 'green', 'violet', 'orange'); //Output all the colors one per line

?>

Suppose you only have 5 items in an array and you try and output the 6th item. What will happen? Try it and find out.

Counting Elements
In the previous activity, you knew that the array $colors contained the names of 5 colors. Suppose you didn't, how would you find out how many elements an array contains? The count() function is what you need to count the number of items in an array. Example:
Run Code

Try It Out

<?php //Initialize an array $colors $colors = array('red', 'blue', 'green', 'violet', 'orange'); echo count($colors); ?>

Try it out
We don't have a specific exercise here but feel free to experiment. Don't worry a huge exercises only section is coming up after the next few exercises. Run Code

Exercise

1 2 3 4 5 6 <?php

?>

Note:
Just like the count() function, there are a large number of useful array functions that help you work with arrays. You can find the entire list at: http://php.net/manual/en/ref.array.php

Creating an Array
Creating array yourself is pretty easy. Here's how you do it: Example that creates an array $labels that contains three adjectives.

$labels = array( 'funny', 'angry', 'sleepy' );


You can also create arrays that contain numbers.

$scores = array( 88, 99, 67, 38, 100 );


The above code creates an array $scores containing scores in 5 subjects. Once you create an array, you can access it's contents in the same way as before:

echo $scores[3]; //outputs the 4th item

Try it out
Create an array $alphabets that contains the 5 letters 'a', 'b', 'c', 'd' and 'e'.

Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 <?php //Write code to create the array $alphabets = echo $alphabet[0] . '<br>'; echo $alphabet[1] . '<br>'; echo $alphabet[2] . '<br>'; echo $alphabet[3] . '<br>'; echo $alphabet[4] . '<br>'; ?>

Associative Arrays
Suppose you have an array $artists that contains information about music artists. Now, we can imagine the array containing all the artist's names or their e-mail addresses etc. However, wouldn't it be cool if we had more information than just their names or their addresses? We could certainly use their facebook profile pictures or the names of their songs etc. when we create apps.

But, how would we store multiple attributes of each artist (say: first name, last name, id etc.) inone array? Enter associative arrays! Here's how an associative array works. Each item in the array consists of key - value pairs containing information about that particular item. You can access the values using the keys. Imagine you have an associative array $artist that contains his/her information. Here's a simple program that displays their first name and last name.

$fname = $artist['first_name']; $lname = $artist['last_name']; echo $fname; echo " "; echo $lname;
In the expression $artist['first_name'], the string 'first_name' is the key corresponding to the value which is the friend's first name and this value is then stored in the variable $fname. Similarly, the friend's last name is stored in the variable $lname.

Quick Quiz:
Now, suppose you have an associative array $artist that contains information about a famous music artist. Let us say that one of the keys in the array is 'name' which contains the artist's name. Write a program that will output their name.

<?php .... .... echo $artist[' ?> '];

Note:
The array $output that you got in the program where you accessed data from Facebook is actually an associative arrays. You are finally close to knowing enough about arrays to continue building your program.

Array of Arrays
In the previous activity, we had information about one artist stored in the array $artist.

What if you're given an array that stores information about multiple artists (ie. each of their entire profile information). How would such an array even look? Basically, each artist's information is stored in an associative array and then these arrays are then stored within another array called $artists. Think of this as multiple little arrays that are then stored within a bigger array $artists. Now, you get the first artist's information by accessing the first element of the array:

$first_artist = $artists[0];
You access information about the second artist by accessing the second element:

$second_artist = $artists[1];
... and so on. Now, $first_artist and $second_artist are associative arrays that each contain information about that particular artist. So to output the name of the first artist, you would write the following program:

echo $first_artist['name'];

Quick Quiz:
Suppose you're given an array $artists that contains information about three artists. Write a program that will output the third artist's name.

<?php .... .... $third_artist = $artists[ echo ?> [' ']; ];

Data Types
Note:
We are including this information because you need to know this and we don't want to come back to talking about variables and arrays later on. This isn't that relevant to the app you are building though. We've seen how a variable is a space in the computer's memory that can hold a value.

These values can be of different types. For example, they could be an integer such as 1, 53, 987 etc., or a float (decimal) such as 1.34 or 4.23 or even a String like "My name is Krishna". In other words, every variable has what is known as a data type which determines the type of data stored in it. In some programming languages you have to explicitly tell the computer what the data type of the variable is but PHP figures it out automatically. The following program outputs the value stored in a variable $unknown_type. Try running the program to see the value and try and determine what its datatype could be?

echo $unknown_type;
You can learn a lot more about PHP datatypes from the following pages: http://www.php.net/manual/en/language.types.php

Type Conversion
We've seen how every variable has a datatype. Sometimes, PHP will convert variables from one type to another. For example, if you try adding a String to an integer, PHP will convert the String to an integer and compute the resulting sum. That is, the following program will output 7.

echo "4" + 3;
Try it out.
Run Code

Try It Out

<?php echo "7" + 10; ?>


Did you see how the string "7" was automatically converted into an integer in the above program? This is type conversion in action.

Further Reading

There are a number of helper functions that allow you to find out the datatype associated with a particular variable. Please take a quick look at some of these functions and how they work.

is_ array is_ bool is_ double is_ float is_ int is_ integer is_ long is_ null is_ object is_ string

You can view the entire list in the left column of the following page: http://php.net/manual/en/function.is-numeric.php

User Profile
Now, finally after a lot of learning, you are ready to build the user's profile page. Just to refresh your memory, this is where we stopped working on that program.
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url);

$output = json_decode($output, true); var_dump($output); ?>


We already mentioned while learning about associative arrays that $output is also an associative array. You can easily verify this using a var_dump() function. How will you recognize an associative array as being different from a numeric array where array indices are used? Let us see with an example: First, let us see what var_dump() outputs when the array is associative.
Run Code

Try It Out

<?php $colors = array('color1' => 'red', 'color2' => 'blue', 'color3' => 'green'); var_dump($colors); ?>

Note:
The above code is also an example of how to create a associative array. Notice the =>separating the key and value? Also a comma (,) separates the key - value pairs from one another. To make it easier to view the contents of the array, programmers typically indent the code like this:

$colors = array( 'color1' => 'red', 'color2' => 'blue', 'color3' => 'green' );
Now, it is very clear what the key - value pairs are and how many pairs are in the array$array. Now, let us see how the output of var_dump() looks for a numeric array.

Run Code

Try It Out

<?php $colors = array('red', 'blue', 'green'); var_dump($colors); ?>


Now, do you see that the output of var_dump() looks different for associative and numeric arrays? Coming back to our program, hopefully you are convinced that $output is an associative array. So, now if we want to output the name of the user, we just do:

echo $output['name'];
Run Code

Try It Out

<?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); $output = json_decode($output, true); echo $output['name']; ?>

Try it out
You have learnt everything you need to create the user's profile. Let us see what an awesome profile page you build for Michael Jackson or any other Facebook page / user. Just replace michaeljackson with your username or a Facebook page's username in the URL. For example to access CocaCola's information, change:

http://graph.facebook.com/michaeljackson
to

http://graph.facebook.com/coca-cola
Also, please be creative with the design and colors. We love to see students creating great apps. Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?php require '../WEB-INF/php/includes/appengine.php'; $url = 'http://graph.facebook.com/michaeljackson'; $output = get_url($url); $output = json_decode($output, true); var_dump($output); ?>

Practice 1

In this chapter you are going to practice some of the concepts you have learnt in the previous chapters. Also, we will be introducing you to new APIs that you will find very useful in the future as you continue to build apps. In this chapter, you will also be doing a lot of extra reading as we will be pointing you to relevant documentation / external sites. Learning how to read a documentation and then follow instructions provided is a crucial skill you need to learn as that is what you will do when you start working.

Let's get started!


Suppose you are given a sentence like this:

The quick brown fox jumps over the lazy dog.


Write a program that will output the number of words in the sentence.

Tip:
Please use the explode() function to do this. Find out how the function works and how to use it at: http://php.net/manual/en/function.explode.php Run Code

Exercise

1 2 3 4 5 6 7 8 9 <?php

$sentence = "The quick brown fox jumps over the lazy dog."; //Write code below to output the number of words in the above sentence. ?>

Note:
Read about the implode() function and how it is used. What practical reasons can you think of for using the function? http://php.net/manual/en/function.implode.php

Practice 2
Read the programs below, understand what the program is trying to do and complete them.

Program 1
Run Code

Exercise

<?php function compute_distance($speed, $time) { return } echo "I ran " . compute_distance(10, 1) . " kms today!"; ?> $time;

Program 2
Run Code

Exercise

<?php function compound_amount($principal, $rate, $time) {

$amount = $time); return $amount; }

pow((1 +

),

echo "If I start with Rs. 1 lakh and compund it at 20% for the next 10 years, I will end up with:"; echo compound_amount(1, ?> ?> , 10) . " lakhs.";

Note:
Note that we use the pow() function. If you know C programming, you know what an exponent operator is. PHP does NOT have an exponent operator.

Program 3
Run Code

Exercise

<?php function even_odd($number) { return $number } echo "20 is ? " . even_odd(20); echo "<br>"; echo "17 is ? " . even_odd(17); ?> 2 === 0 ? "even" " ";

Note:
Notice the ===. Learn more about how === is different from == in PHP. This is very important to know. You should leaqrn this on your own and we will test whether you did at a later date.

Program 4

Run Code

Exercise

<?php function is_teenager($age) { return $age >= 13 && $age } echo "Ram is a teenager? " . is_teenager(20); echo "<br>"; echo "Shyam is a teenager? " . is_teenager(19); ?> 19 ? "yes" " ";

Note:
What operator is &&? We had asked you to learn all about operators from the PHP manual. If not, please do so immediately as this is a very important concept that you should be very comfortable with. http://php.net/manual/en/language.operators.php You should be conformtable with the following sub-sections:

Arithmetic Operators Assignment Operators Bitwise Operators Comparison Operators Incrementing/Decrementing Operators Logical Operators String Operators Operator Precedence

Also, please learn how operator precedence works.

http://www.php.net/manual/en/language.operators.precedence.php Also, learn how the pre-increment operator ++$i is different from the post-increment operator $i++. Similarly, also understand the same difference between the pre and post decrement operators.

Practice 3
In previous activities, you have learnt how to request data from a single Facebook profile / page. Now, you can also request data from multiple profiles in a single GET request. This is an example of how to do that. http://graph.facebook.com/?ids=michaeljackson,coldplay,ladygaga Now, view the output and find out what the structure of the response is and then write a program that will display the profile information of all three artists on the same page. You can decide what information about these artists you want to display. Run Code

Exercise

1 2 3 4 5 6 7 <?php require '../WEB-INF/php/includes/appengine.php';

?>

Practice 4
Nowadays, you have a lot of rich content on the internet and a very popular way by which people share this content is by embedding it in their own blogs / sites / Facebook news feed etc. This makes

it easier for others to consume the content immediately instead of having to navigate to the site where the content was first uploaded. The whole practice of embedding was made popular by Youtube which allowed videos uploaded to the site to be embedded elsewhere. Now, what if you wanted to create a site where users can post links and you automatically embed the content? As an example, suppose a user decided that he/she wants to embed a Youtube video. He or she will then enter the URL of the video (say http://www.youtube.com/watch?v=YYRbzSmVfKA). Then, your program has to figure out how to embed the actual video on the same page like this.

Now, how will you do this for sites that have embeddable content? Few examples are Youtube (videos), Slideshare (PPTs), Soundcloud (audio) etc? This is where something called the oembed(open embed) API comes in. The idea here is that each site will expose an API that conforms to something called the Open Embed specification that will easily allow you to figure out how to embed content found on its pages. The way it works is that you provide the URL to a page on which an item is embedded (eg: a youtube video page) as input and the API will return information about the video as well as the actual HTML code needed to embed the video. Here is the oembed API blog post for Youtube:

http://apiblog.youtube.com/2009/10/oembed-support.html Read the documentation, understand the format of the JSON response from the API and then write a program that will embed the video whose video page url is saved in the variable$video_url. Run Code

Exercise

1 2 3 4 5 6 7 8 <?php require '../WEB-INF/php/includes/appengine.php'; $video_url = 'http://www.youtube.com/watch?v=YYRbzSmVfKA'; ?>

Practice 5
Now, find out the page that documents the oembed API for Slideshare (a service for uploading and sharing PPTs) using Google and then write a program that will embed the PPT for the URL stored in $slide_url. Run Code

Exercise

1 2 3 4 5 6 7 8 <?php require '../WEB-INF/php/includes/appengine.php'; $slide_url = 'http://www.slideshare.net/sebastian_bergmann/php-compiler-internals'; ?>

The Goal
In this chapter, you will learn more about strings and how to use them in your program. If you have noticed, we used strings in pretty much every program. This is because, very often, input that is sent to a server side script (via a GET / POST / other request types) is a string. Of course, this 'string' can then be parsed into various data structures depending on the type of content being sent but the original content that the server receives is usually a string representation of the data structure. We've talked about input to a script but what about output? In the context of web apps, HTML content that is generated as output by the server in response to a request is also just text (containing HTML content). In addition to both input and output, a lot of the data that your application uses will also be strings (example: name, address, username, password etc.). OK. Strings are important. What next? Well, in this chapter we're going to look closely at a few concepts regarding PHP code blocks, mixing HTML and PHP, a brief look at some useful PHP string functions and a few words on security aspects concerning output from your PHP code.

Quick Recap: What are Strings?

A string is nothing but a sequence of characters. In PHP, strings are enclosed within quotes. You can use single quotes (') or double quotes (") to enclose strings but we'll later see when to use one instead of the other later in this chapter. The size of a string is only limited by the amount of memory that is available to PHP. A few examples of strings are:

"Hi, my name is Krishna!" 'ABCDE' "12345"


Note that you have to use the same type of quote (single/double) at both ends of the string.

PHP Blocks
In previous activities, we have seen how we can mix HTML and PHP in the same program. Here is an example once again so you remember.
Run Code

Try It Out

<?php //In PHP now and this is a PHP comment echo 'Hi there!<br>'; ?> <!-- in HTML now and this is a HTML comment --> <p> HTML is awesome. </p>

Variable Scope
Now, you have to understand the scope of variables in the script. Unless the variable / array etc. is defined inside a code block (IF statement / Loop / Function etc. - you will learn what loops and IF statements are in the next 2/3 chapters), the variable is available to the entire part of the script that follows.

Note:

You should also know that variables in one script are also available in another script that includes the former. Suppose you have a variable $a initialized to the value 5 in a script file1.php. Now, conside another script (file2.php):

<?php //code for file2.php .... .... .... //including the script file1.php require 'file1.php'; echo $a; ?>
When you require the PHP script file1.php, its contents get added inline in the place where you include it. So when you try and output the value contained in $a after you require file1.php, the output will be 5 even though you never defined or initialized a variable $a in file2.php. This is also why you are able to use functions such as get_url() in your code by requiring the appengine.php library where it is defined. Coming back to the discussion of PHP blocks, consider the following example:
Run Code

Try It Out

<?php $number = 27; ?> <p> My lucky number is: <?php echo $number; ?> </p>

What do you see as output when you run the program? Did you notice how the variable$number that was initialized to the value 27 in one block could then be used in the next block.

Quick Quiz:
Consider the following code:

<?php $a = 10; ?> echo $a; <br> <?php echo $a; $b = $a + 20; ?> <br> echo $b; <br> <?php echo $a; ?>
The output of the above program will be: <br> <br> <br> 10

Escape Characters
Imagine for a moment that you are building a profile page for Michael Jackson. You decide to begin by writing a simple program that will output the title of the page (remember the we use the echo command to output data):
Run Code

Try It Out

<?php echo 'Michael Jackson's Profile'; ?>

What do you see when you run the program? PHP throws an error saying it expects a semicolon(;) near the word profile. What went wrong? Well, the apostrophe in the word Jackson's also happens to be a single quote and so we end up with three single quotes in the statement. Since there is an unmatched quote, PHP throws an error. In such cases we must prefix the apostrophe with a backslash (\). The backslash is known as an escape character and it changes the meaning of the character that follows it. In this case, the backslash changes the meaning of the apostrophe from that of a single quote to just being a simple english character. The correct program is therefore:
Run Code

Try It Out

<?php echo 'Michael Jackson\'s Profile'; ?>


Notice the backslash before the single quote in Jackson's? Try running the program now to understand what the escape character does. There are also other escape sequences that are used to output certain special characters. For example \n changes the meaning of n from a letter to a linefeed (new line). One gotcha while using these escape sequences is that when you include them within single quotes, they will be treated as a literal ie. the characters will be output as is and the special meaning will not be taken. To use a \n at the end of a string, for example, you must enclose the string within double quotes. Here is an example that will help you understand this better:
Run Code

Try It Out

<?php $sentence1 = 'Hello there.\nWhat is your name?';

$sentence2 = "Hello there.\nWhat is your name?"; ?> <h1>Single quotes</h1> <pre> <?php echo $sentence1; ?> </pre> <h1>Double quotes</h1> <pre> <?php echo $sentence2; ?> </pre>
What do you see when you run the program? Did you notice that the \n was treated as just a literal (plain characters) when you used single quotes and as a newline when double quotes were used? You can get a full list of escaped characters from this link. Scroll down on the following URL to a table names "Escaped Characters". http://php.net/manual/en/language.types.string.php

Try it out
Run Code

Exercise

1 2 3 4 5 6 <?php //experiment! ?>

Variable Interpolation

So far we have seen a few differences when you use single quotes to enclose a string versus double quotes. Now, we are going to learn one more difference and it is called variable interpolation. Variable interpolation is actually pretty simple. When you include a variable name within a string that is enclosed by double quotes, the name of the variable will be replaced by its value when the string is output. On the contrary, in single quoted strings, the output will only contain the name of the variable as is and its value will not have been substituted in its place. Again, let us understand this with an example.
Run Code

Try It Out

<?php $age = 27. ?> <h1>Single quoted string</h1> <?php echo 'I am $age years old.'; ?> <h1>Double quoted string</h1> <?php echo "I am $age years old."; ?>
What do you see as output when you run the program? Did you notice how the value 27 was output instead of the variable name $age in the case of the double quoted string? This happened because of what is called variable interpolation where variables are replaced with their values. This also makes outputting values contained in variables very easy because all you have to do is include the variable names within a sentence just as you would normally (in english) and remember to use double quotes.

$sentence = "My name is $name and I am $age years old. I have $num_children children and their names are $child_1_name and $child_2_name."; echo $sentence;

Array Value Interpolation


What if you want to use a value contained in an array as part of output? Will interpolation work the same way? Let us find out.

Run Code

Try It Out

<?php $colors = array('red', 'blue'); echo "My favorite color is $colors[0]."; ?>
In this case, it worked but now let's try the same thing with an associative array.
Run Code

Try It Out

<?php $colors = array('color1' => 'red', 'color2' => 'blue'); echo "My favorite color is $colors['color1']."; ?>
Do you see an error when you run the above program? It tunes out that if you are trying to access a value corresponding to a key in an associative array from within a string (via inyterpolation), you should not add quotes around the key (as you normally do). Therefore, $colors['color1'] should actually be used as $colors[color1] (notice there are no quotes around the key color1. Try it out:
Run Code

Try It Out

<?php $colors = array('color1' => 'red', 'color2' => 'blue'); echo "My favorite color is $colors[color1]."; ?>
To avoid forgetting this and to ensure that you don't make this mistake, you can also enclose the array access within curly brackets like this {$colors['color1']} and in this case you can also have quotes around the key color1. I would highly recommend that you this technique while using

array values within strings as there is no scope for a error because of forgetting to remove quotes around the key name.
Run Code

Try It Out

<?php $colors = array('color1' => 'red', 'color2' => 'blue'); echo "My favorite color is {$colors['color1']}."; ?>
Notice that the above program works fine even thougn you have quotes surrounding 'color1'. This is because the array access is enclosed by curly brackets { and }.

Try it out!
Run Code

Exercise

1 2 3 4 5 6 <?php //experiment! ?>

String Functions

Like any other programming language, PHP has a number of standard functions that you can use while writing your programs. However, unlike other languages, in PHP there is no need to import or include a library to use one of these functions. There are a number of helpful string functions but it is virtually impossible to talk about all of them without re-typing the entire PHP manual once again :). Therefore, we would recommend that you quickly skim through the list of string functions that PHP provides so you know what exists and then you learn how each one works as and when you have a need to use that particular function. http://www.php.net/manual/en/ref.strings.php In this course, we will explain how a particular function works as and when we encounter a program that uses that function. That is a better approach as just learning how 50 different functions work can be boring to do in one stretch. Often, the best way to find out how a function works is by Googling the use case. For example, suppose you want to capitalize the first character of every word in a sentence. Example:

today is a monday.
should be converted to:

Today Is A Monday.
There is a string function ucwords() in PHP that will do this for you but how can you find out? Simple, just google what you are looking for: https://www.google.co.in/search?q=php+caps+first+letter+of+each+wordach+word The great one (Google), will then answer your question almost magically :).

Escaping Output
Suppose you build an application where you allow a user to add a comment. Since a comment is just text, a user can also type a seemingly harmless piece of text that also happens to be a valid piece of Javascript code.

Note:

Javascript is a scripting language that (usually) runs in your browser and is used to make web pages dynamic on the client side. Now, you may not think this is harmful but this can lead to a huge security problem called Cross-site Scripting. To understand what can happen, try running the following code. Run Code

Exercise

<?php echo "<script type='text/javascript'> alert('Hello, this alert should not be here!!!'); </script>"; ?>
Did you see a alert message appearing? What if that alert message had appeared on your site because of some code that a user entered into your comment box? The message can also contain profanity or other undersirable links. Now, how would code entered into a comment box be able to create a alert message? Here is what is happening:

The comment entered by the user gets saved in your database. When someone else visits the page, the PHP script retrieves comments for that page from the database and then displays them on the screen (remember one of the comments is a valid Javascript code).

Now, when that malicious comment gets added to the page, since it is valid Javascript code, the browser will immediately run (evaluate) it (this is how browsers work).

The alert / popup is then displayed to the user containing possibly undesirable spam messages.

There are also worse things that can be done once someone can get their javascript into your page such as accessing user information, making requests on behalf of the user etc. Here is another example of a Javascript code the does a redirect away from your application. Run Code

Exercise

<?php echo "<script type='text/javascript'> window.top.location= 'http://google.com/'; </script>"; ?>


When you run the above code, did you see the app or did you find yourself staring at a Google.com page? This is because the javascript that we added redirected you to Google (but could have been a dangerous / fraudulent site as well). So the lesson here is that you should always be careful whenever you accept user input (be it their name, college information or any other value that they enter). Since you can never know whether the user entered malicious code or not, the best thing to do is always escape outputbefore displaying it on the page. Escaping output in PHP can easily be done using the htmlentities() function which replaces characters like < and > with their corresponding HTML entities &lt; and &gt; etc. This will prevent the browser from running the text as a Javascript script and the code will be displayed on the page as a piece of text (will not be executed). See what happens when we use the htmlentities() function before we echo the string. Run Code

Exercise

<?php echo htmlentities("<script type='text/javascript'> alert('Hello, this alert should not be here!!!'); </script>"); ?>
What do you see when you run the above program? Do you see the code displayed as text? You don't see a alert message do you? Therefore, please be very careful whenever accepting any kind of input from a user and always escape output before displaying it. There are other important security considerations as well to completely prevent Cross-site scripting (also known as XSS) but those are beyond the schope of this course. For now, understand that untrusted output is dangerous and that XSS is a very common security loop-hole in many PHP applications and you need to take precautions to avoid it in yours.

Practice 6
Suppose you are creating a blogging system and you need to display the titles of posts at the top of every page. Now, users may enter the title in small caps but that will not look professional. So, write a program that will output the title after converting the first letter of each word into CAPS. What string function will you use for this? Also, who enters the title? Is it secure to blindly display it on the page? What other function should you use to ensure that the output is secure? Run Code

Exercise

<?php $title = "this is a title in small caps."; $title = ucwords($title);

?>

Practice 7
In another application suppose you want to only allow users from the company Google to register. Also, assume that all google email addresses have google.com after the '@' symbol. Now write a program to check if the email address stored in $email is acceptable. What string function(s) will you use for this? How will you ensure that the email is acceptable? Run Code

Exercise

<?php $email = "genius@google.com"; //Write code below determine whether or not the email belongs to google.com.

?>

Note:
There is a separate problem of validating that the string stored in $email is infact a valid e-mail address. PHP provides a in-built function to help validate that a given string is an acceptable e-mail address. While this course does not cover it, just for your information, the way to do this is using the filter_var() function. http://php.net/manual/en/function.filter-var.php

Practice 8

Let's go back to the blogging system and imagine you are building one. Every blog post consists of a title, post and categories / tags. Focus on the title for a moment. Suppose the title of a post is 'The first blog post'. You will notice that many blogging tools will generate a URL for that post based on the title. For example the URL may be something like:

http://blah.example.com/blog/the-first-blog-post-1234
Notice how the part of the URL after '/blog/' is derived from the title of the post. This is done for many reasons but the most important reason for this is something known as SEO (search engine optimization).

This derived string is called a URl slug.

Note:
SEO is another area where there is a lot of demand these days and it is an entire subject area that you should study when you get a chance. Let us know if you would like us to create a course on this subject. You can learn more at: http://en.wikipedia.org/wiki/Search_engine_optimization Write a program that will convert the title stored in $title into a URL slug. What string function(s) will you use for this? Your program must do the following:

Lowercase all characters. There should not be any spaces in the beginning or end of the slug. Remove any character that is not a alphabet or a number or a space. All spaces between words must be replaced by a single hyphen (-). The slug must end in a number (can be randomly generated for now but in reality it will come from a database).

Please write the code to convert the string stored in $title into a URL slug. Run Code

Exercise

<?php $title = "Introduction to PHP arrays"; //Write code to convert title into a URL slug.

Practice 10
A palindrome is a word that has the same spelling even if the characters are reversed. For example, the word madam is a palindrome as even if you reverse the letters, you get back the same word. What string function(s) will you use for this? Write code to determine if the string stored in $word is a palindrome. This exercise requires the use of an IF statement. Although we have not covered this concept yet, you have seen examples of how to use an IF statement before so we are confident you will be able to figure out how to use one in this case. Run Code

Exercise

<?php $word = "madam"; //Write code below determine whether or not $word is a palindrome.

?>

Note:
This is also a great time to understand the difference between the == and the ===operators (if you have not already done so). This is not specific to this exercise but we want to remind you that knowing this difference is extremely important.

Superglobal Variables

A superglobal variable is one that is automatically available globally in any PHP script (ie. it can be used in any variable scope - within functions / code blocks / if statements etc. without the need for a global keyword). You will be learning about variable scopes in the last chapter of this course and we will explain what superglobal means in detail at that time. So, don't worry too much if you don't understand what scoping means. For now, you only need to understand that you have superglobal variables in PHP and these variables always start with a $_ (dollar sign followed by an underscore) prefix. Here are a few examples of superglobal variables (these variables are all associative arrays):

$_GET - an associative array of variables passed to the current script via the URL parameters. $_POST - contains data passed to the PHP script via a POST request. $_SERVER - contains information such as headers, paths, and script locations. The entries in this array are created by the web server.

$_COOKIE - contains an associative array of variables passed to the current script via HTTP Cookies.

$_REQUEST -An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

You can view the contents of these arrays just like how you would view the contents of a normal associative array (remember var_dump() and print_r)?

The GET request


As you learnt in the previous activity, the $_GET superglobal variable is an associative array of variables passed to the current script via the URL parameters.

URL parameters
Consider the following URL:

http://example.com/?id=123
In the above URL, you have one parameter called id with a value of 123. Notice how we use the? to indicate that you are passing parameters to the script. Also, each parameter consists of a key

(parameter name) and a value (the value of the parameter). The key of the first parameter always follows the ? symbol. The key and value of a parameter are separated by a = (equal to) sign. You can also pass multiple parameters to the same script by separating the key value pairs with a & character.

http://example.com/?id=123&name=krishna
In the above URL, we pass two parameters id and name along with their values. Notice the &separating the two parameter key-value pairs.

Accessing URL parameters in PHP


You can access URL parameters using the $_GET array. The key you should use is the parameter name and the value will be the value corresponding to that parameter. So for the URL in the example above:

echo $_GET['id']; //will output 123 echo $_GET['name']; //will output krishna

The isset() function


Sometimes a few parameters may be optional and they may not be passed. Therefore, if you try and access a particular key in $_GET and that key is not present, your script can error out. Therefore, it is always recommended that you use the isset() function to check if a parameter has been passed (the corresponding key is set) before trying to access its value.

if(isset($_GET['id'])) { $id = $_GET['id']; } else { $id = NULL; }


You will be learning about IF statements in the next chapter but you should be able to understand what the above code does. We check to see if the URL parameter 'id' has been sent (present as a key in the $_GET array) and then we assign its value to the variable $id. If it has not been sent, we assign null to $id.

Note:
Learn more about NULL at:

http://php.net/manual/en/language.types.null.php

Try it out
When you first run the code below, it will display just one parameter (namespace). But, where is this parameter coming from? If you see the URL, you will not see any parameters being passed. What is happening here is that the URL is of the form: http://unclassroomapps.appspot.com/app/24234/ Through a process called URL routing, the above GET request is actually mapped to a specific file (in our case a file called outer.php) and the number at the end of the original URL (your app id: 24234) is sent to this PHP script as a URL parameter with name (key) as 'namespace'. So although you see the above URL in the browser. The actual URL request (under the covers is): http://unclassroomapps.appspot.com/outer.php?namespace=24234 Since the original URL was mapped to particular script based on a specific URL pattern it is known as URL routing. You will understand more about why this is useful in an advanced PHP course on frameworks. After you create your app by submitting the above code, try passing additional parameters to it (remember how to do this from the first few paragraphs on this page) and see it appearing in the $_GET array. Do you now understand how URL parameters and GET requests work?

Note:
URL parameters are another common way to introduce XSS (remember cross-site scripting) security holes into your application. What will happen if you blindly echo values passed to your script via a parameter? What value will a potential attacker pass? How will you prevent this from happening?

The POST request


As you learnt earlier the $_POST array contains data passed to the PHP script via a POST request. Before continuing to learn how to access this data from within your script, let us take a minute to understand what the differences between the GET and POST request are.

Difference between GET and POST


The GET request is used to pass information to a script via URL parameters. Because of this, the maximum amount of information that can be passed is restricted to the maximum length of URLs (in most cases ~2000 characters). The POST request on the other hand does not have such limits

although the default maximum is 8 MB of data that can be passed (this can be increased by modifying settings in PHP's configuration file). The second important difference is that the URL parameters in a GET request are plainly visible (in the browser address bar) whereas data that is POST will not be visible. Now, given this, what method do you think you should use while sending username / password data in a login form? Although both GET and POST request can be used to pass information to a script, there is a convention regarding when and how you should use one over another. Use GET if you are retrieving data from your script and use POST if you are making changes to the data stored in a database etc. This is only a convention that is usually followed. The response from a GET request is usually cached by your browser (or by what is known as a proxy server) but POST requests are not cached unless your server or a proxy server is explictly configured to do so. Caching means that the response is saved somewhere (on your computer or on the server) so on subsequent requests the page loads much faster - no processing needs to happen; the saved response is fetched and loaded very quickly.

Note:
If you can't understand what caching means, don't worry too much about it now but just remember that something called caching exists. This will be important to learn in an advanced course. Also, in GET requests, you can only send ASCII data to the server whereas in POST requests you can also specify the encoding of the files thereby allowing you to upload binary data (such as files) or send text containing non ASCII characters (other languages).

Note:
Google and learn what ASCII characters are. Suppose you want to build a website for chinese users where they can enter text in chinese (not english), can ASCII be used? Can you think of a few other examples where ASCII will not work?

Note:
You will learn how to upload files in the intermediate PHP course where you will create a photo blog.

Accessing POST data


Consider the following program where we accept a username and password from the user. Run Code

Exercise

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?php if(isset($_POST['username'])) { $username = $_POST['username']; } else { $username = NULL; } if($username) { echo "<p>The username entered is: " . htmlentities($username) . "</p>"; } ?> <form method='POST'> Name:<br> <input type='text' name='username'/> <br> Password <br>

<input type='password' name='password'/> <br> <input type='submit' value='Submit'/> </form>

Note:
When you submit a HTML form, by default, the data is sent to the server as a GET request. So, you should specify the method as 'POST' to ensure that the data is sent via a POST request. try changing the method to GET in the above program and see what happens when you submit the form. You should be able to see the password you enter in plaintext (in the browser address bar) and this is really insecure (what is a friend is watching you login over your shoulder - they now know your password!) Just like in the previous activity where we used $_GET to access data that is sent via a GET request, here we use $_POST. Again, you need to check and see if the particular key is set before trying to access the value for that key.

Note:
The key for a specific form field in $_POST is the same as the value of the name attribute in the form element for that field. For example, you access the value entered in the textbox:

<input type='text' name='username'/>


Using the key 'username' (see the name attribute in the <input> tag above.

if(isset($_POST['username'])) { $username = $_POST['username']; } else { $username = NULL: }


If you don't know forms or haven't worked with them before, please go through this excellent tutorial on HTML forms at: http://learn.shayhowe.com/html-css/building-forms

IF Statement
Sometimes, you will have to take a decision based on some criteria. For example, let's say you want to label someone as an extrovert if they have greater than 50 friends. The way you do that is by using an IF statement.

if ( criteria ) { //code executed if criteria is met }


Suppose you have a variable $num_friends that contains the number of friends a person has and you want to label them an "Extrovert" if they have more than 50 friends. The criteria for checking whether the person is an extrovert is:

$num_friends > 50
This is called an expression since it results in a single value: either TRUE or FALSE. The expression is TRUE if they have greater than 50 friends and or FALSE otherwise. Therefore, the IF statement we need is:

if ( $num_friends > 50 ) { //code executed if criteria is met }


Now, when your friend has greater than 50 friends, we want to output that he/she is an extrovert. So, the full program is:

if ($num_friends > 50) { echo "extrovert"; }


The echo statement will only be executed if the criteria $num_friends > 50 is met. So, if you don't see any output, it means the person only has 50 friends or less. Now, write a program that will output "yes" if the person has lesser than 10 friends. Do this by completing the function is_introvert() . Run Code

Exercise

<?php function is_introvert($num_friends) { //Write code below to complete this function //output yes if user has lesser than 10 friends } is_introvert($num_friends); ?>

IF ELSE Statement
In the previous activity, you labeled a person as an introvert IF they had lesser than 10 friends. Now, what if we want to label the others as extroverts (instead of not displaying any output). The way you do this is by using the IF - ELSE statement. Here's an example:

if ( criteria ) { //executed if criteria is met } else { //executed if criteria <b>not</b> met }


If the criteria is met, the code within the first pair of curly braces is executed. Else, the code inbetween the second pair of braces is executed. So, the modified version of the program that we wrote earlier is:

if ( $num_friends < 10 ) { echo "introvert"; } else { echo "extrovert"; }


Now, let's say we have two variables, $coke_likes and $pepsi_likes that contain the number of likes that the two drinks pepsi & coke have on Facebook. Write a program that will output'coke' if coca cola has more likes or 'pepsi' otherwise. Run Code

If Else Ladder

You can also use multiple if else statements (cascading IFs) to make decisons in more complicated situations where more than 2 outcomes are possible. Suppose you are writing a program to assign grades. The program might look like the following:

if($marks >= 90) { $grade = 'A'; } else if ($marks >= 80) { $grade = 'B'; } else if($marks >=70) { $grade = 'C'; } else if($marks >=40) { $grade = 'D'; } else { $grade = 'F'; }
As you can see above, we use multiple IF Else statements to assign the correct grade. At the end we also have a catch-all else block that will assign the 'F' grade if the mark obtained is < 40.

Note:
You can also have fully contained IF statements. Here is an example:

if($gender === 'male') { if($income >= 100000) { $tax_rate = 0.3; } else { $tax_rate = 0.0; } } else { if($income >= 100000) { $tax_rate = 0.2; } else { $tax_rate = 0.0; } }
In the above code, we assign the tax rate based on the gender of the person as well as their income. In the previous activity, you wrote a program that will output 'coke' or 'pepsi' depending on the number of likes ($coke_likes and $pepsi_likes). Now, you can also have both brands having the same number of likes. Therefore, modify your program to also output 'equal' if both have the same number of likes.

Practice 15
In this activity, you will build a very simple facebook likes leaderboard for your application. This means that you will rank a few pages (about famous people, actors, beverages etc.) based on the number of likes they have on Facebook. Please create a HTML form that will contain a text box. The user will enter exactly three facebook page ids separated by commas. You should then get information on the number of likes each page has received on Facebook and then display a leaderboard based on a decreasing order of likes. The leaderboard should contain the name of the page, its likes, and its display pic.

Note:
You can use HTML tables to display the leaderboard but bonus points if you create the leaderboard using <div> and styling via CSS. Google for how to use the CSS floatproperty to create a table like structure without actually using a HTML table. Run Code

Exercise

<?php require '../WEB-INF/php/includes/appengine.php';

Practice 15
When you create an account on any website (including unclassroom), you will be asked to verify your e-mail address. Now, the way this usually works is when a user creates a new account, the site will send an e-mail with a URL that looks like this: http://example.com/comfirm?code=ahdjj213nhasdjjnadklk&email=a@b.com If the parameter 'code' is correct (meaning the user actually clicked the link in the e-mail as he or she could not have guessed it) for the supplied e-mail parameter, then the user's account is activated (email is confirmed).

You are going to implement a few parts of this system now. You will also make the same page deal with both $_GET and $_POST request. First create a HTML form that will ask the user to enter their e-mail, password and password check (re-enter password). Then, you should check to see if the passwords match and whether the password is more than 6 characters. If not, please output an error message with details of the error.

Note:
Ideally, you should also check that the e-mail is valid using the filter_var function but that function will not work on the platform we use (it will work on a normal PHP installation though). That is why you can't perform that validation at this time. OK, now if the passwords match, your code should create a random string of letters and numbers sufficiently random so the user cannot guess it. Also, it has to be random because if it is the same for every user then the point of confirming the e-mail address is totally lost. Once you generate this random code, output it (this is ofcourse only if the validation checks pass, right). The above form should submit data via the POST method.

Note:
Usually, instead of outputting a message, the script will send an e-mail to the id supplied with the cofirmation code and then a message saying 'Please check your e-mail will be output. Also, this generated code will have been stored in the database along with the e-mail id and password details. Now, the same script should also accept a GET URL parameter called 'code' and a parameter called 'email'. If both the parameters are passed to the script, just display a message like 'Activation code received, checking validity.' but the form should not be displayed in this case. Also, if only one parameter is set but not the other then an error message should be displayed. Also, if even one parameter is set (even if the other one is not) the registration form should not be displayed. Basically, if the code and email parameters are passed to the script, no form should appear. However, if both parameters are not set as URL parameters, then the registration form should appear. If only one parameter is set and the other one is not then only an error should be displayed and the form should not be displayed. Makes sense?

Note:
In the above script, we only display a message saying 'Activation code received ...' etc. In a real scenario, the script would check the supplied email and code in the database (remember these details were stored when the user registered?) and then if the code is found to match for the given email id, the corresponding user account will then be activated. Run Code

Exercise

<?php require '../WEB-INF/php/includes/appengine.php';

Você também pode gostar