Basics of PHP

In this tutorial, you will learn the basics of PHP. This tutorial contains examples that you can try on your local webserver. This tutorial is not meant to be comprehensive. For more information please refer to the slide presentation available on eLearn@USM, reference book or the internet.

Simple Program

PHP code is capable of executing code inside an HTML document. So for example, you may start with a simple HTML page which looks like this:

<html> 
  <body> 
  Hello! 
  </body> 
</html>
	

And later on add a PHP section which executes PHP code, and writes the output as HTML. Notice that the PHP line disappeared when executing, since the PHP code is replaced by the output. Let's try adding the name of the user's name. Notice the PHP tag (starting with <?php and ending with ?>). PHP code is inserted between the delimiters. Save the file as 'test.php'. Navigate your browser to http://localhost/test.php or 127.0.0.1/edsa-htdocs/test.php.

<html> 
  <?php $name = "Kasim"; ?> // declaration and initialization 
  <body> 
  Hello <?php echo $name; ?>! 
  </body> 
</html>

Arithmetic Operators

Operators such as addition, subtraction, multiplication and division can be used to perform simple arithmetic operations. We can also print out PHP variables using the echo command. For example, let's sum up two numbers, put the result in a new variable, and print out the result. Don't forget the PHP opening and closing tags.

$a = 15;
$b = 20;
$sum = $x + $y;
echo $sum;       // prints out 35
	

PHP double quoted strings can format strings using defined variables. For example:

$name = "Kasim";
echo "Your name is $name.";
Exercise

1. Define the variables name and age and print out the following sentence using the variables:

Hello Kasim. You are 40 years old.

2. Calculate the following expression. z = a ÷ (b + c) × (d2 - e) × f where a = 15, b = 3, c = 2, d = 4, e = 12, f = 4.

Arrays

Arrays are a special type of variable that can contain many variables and hold them in a list. For example, if we want to create a list of numbers from 1 to 10. We can create an array consists of 10 elements and assign the numbers to that elements. Each element has an index that can used to access the element. Note that index start with 0. In the example we display the content of the first and last elements

$numbers=[1,2,3,4,5,6,7,8,9,10];
echo $numbers[0] . "\n";
echo $numbers[9] . "\n";
	

Associative Array is an array with a string index. Instead of numeric index, each element can be assigned a specific key. A good example for using arrays with keys is a phone book. Let's say we want to save the phone numbers of people in a class.

$phonebooks = [
  "Kasim" => "012-4598976",
  "Lee" => "016-3573367",
];
echo $phonebooks["Kasim"] . "\n";
echo $phonebooks["Lee"] . "\n";
	
Exercise

Add a number to the phone book for Lakshmi, with the number 019-5086743, either by adding it to the array definition, or as a separate code line.

Loops

For loops are simple loops which can be used to repeat statement(s) There are two types of for loops - a simple (C style) for loop and foreach. Another type of loop is the While loop which is a simple blocks that execute repeatedly until the while loop condition is not met. This is a typical for loop that display 0 to 9.

for ($i = 0; $i < 10; $i=$i+1) {
  echo $i . "\n"; 
} 
	

The foreach loop iterates over an iterable element such as an array or an object, providing the members in a specific variable one at a time. For example, we have an array containing 0 to 9 and we want to print them out one by one. This time, we will be using the foreach statement instead of a regular for loop wih an iterator variable. Instead of using the iterator variable as an index to the array, we get the item from the array directly into the $n variable.

$numbers = [0,1,2,3,4,5,6,7,8,9];
foreach($numbers as $n) {
  echo $n. "\n";
}

Forms Processing

Forms are used to get input from the user and submit it to the web server for processing. A form is an HTML tag that contains graphical user interface items such as input box, check boxes radio buttons etc. The form is defined using the <form>...</form> tags and GUI items are defined using form elements such as input. We will use HTML tags to create a simple form.

<html> <!-- form.html --> 
<head><title>Registration Form</title></head> 
<body> 
	<h1>Registration Form</h1> 
	<p>Please fill in all fields</p> 
	<form method="post" action="form.php"> 
	<h2>User Information</h2> 
	<label style="width:5em;float:left;">First name:</label> 
	<input type="text" name="fname"></br></br> 
	<label style="width:5em;float:left;">Last name:</label> 
	<input type="text" name="lname"></br></br> 
	<label style="width:5em;float:left;">Phone:</label> 
	<input type="text" name="phone" placeholder="(XXX)XXX- XXXX"></br></br> 
	<input type="submit" name="submit" value="Register"></br> 
</form> 
</body> 
</html> 
	

<form…>…</form> are the opening and closing form tags action="form.php" method="POST"< specifies the PHP page that will handle the form and the submission method. <input type="submit" value="Submit"> is the button to submit the form to the server for processing

<html> <!-- form.php --> 
<head><title>Form Processing</title></head> 
<body> 
<p>Hi <?php print($_POST["fname"] . " " . $_POST["lname"]); ?></p> 
<p>Your phone number is <?php print($_POST["phone"]); ?></p> 
</body> 
</html> 

PHP POST method is the built in PHP super global array variable that is used to get values submitted via HTTP POST method. “$_POST[…]” is the PHP array and the key is the value of attribute name of the input element.

Cookies

A cookie is a small file that the server embeds on the user's computer. It is used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time. Cookies are commonly used for user preferences, themes shopping cart, and recording and analyzing user behavior. A PHP script that sets a cookie might send headers that look something like this.

HTTP/1.1 200 OK
Date: Fri, 07 Feb 2019 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=abc; expires=Friday, 08-Feb-19 22:03:38 GMT;
path=/; domain=usm.com
Connection: close
Content-Type: text/html

The browser will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this.

HTTP/1.1 200 OK
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=abc

The following example store the user's name and age in the cookie. This information is retrieve in a page (info.php) as user identification for personalization.

<body> <!-- index.php ->
  <?php 
  setcookie("name", "Ahmad", time()+3600, "/","", 0); 
  setcookie("age", "38", time()+3600, "/", "", 0); 
  ?>
  Welcome to e-shop! 
  <a href=info.php >info<a>
</body>
	

In the info.php, isset is used to check if a cookie is set or not. If a cookie is set, the information is retrieved.

<body> <!-- info.php -->
<?php 
if( isset($_COOKIE["name"])) 
  echo "Welcome " . $_COOKIE["name"] . "/" . $_COOKIE["age"] . "<br />"; 
else 
  echo "Sorry... Not recognized" . "<br />"; ?> 
</body> 
	

Sessions

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer – it is stored in temporarily on the server. This information will be available to all pages on the site during that visit.

The following example asks users to login by entering username and password. The sessions variables are set if the login information is correct, and the user is redirect to a (protected) page.

<!-- index.php -->
<body> <h2>Enter Username and Password</h2>
<?php
session_start();
$msg = '';
if(isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password'])) {
  if($_POST['username'] == 'admin' && $_POST['password'] == '1234') {
    $_SESSION['valid'] = true;
    $_SESSION['timeout'] = time();
    $_SESSION['username'] = 'admin’;
    $msg = 'You have entered valid use name and password';
    header('Location: info.php’);
} else {
  $msg = 'Wrong username or password'; } }
  ?>
  <div class = "container">
  <form action="/index.php" method="post">
  <input type="text" name="username" placeholder="username=admin" required></br>
  <input type="password" name="password" placeholder="password=1234" required>
  <button type="submit" name="login">Login</button>
  </form>
  <p><?php echo $msg; ?></p>
  Click here to clean <a href = "logout.php">session</a>
  </div>
  </body>
	

In the info.php, isset is used to check if sessions variables are set or not.

<body>
<?php session_start();
if(isset($_SESSION['username'])) {
  echo '<p>Welcome ' . $_SESSION['username’];
} else {
  header('Location: index.php’);
} ?
<br><br>
<a href='logout.php'>Logout</a>
</body>
	

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

<body>
<?php
session_start();
echo '<p>Goodbye...</p>’;
session_unset();
session_destroy();
header('Location: index.php’);
?>
</body>