1
CS428 Web Engineering Lecture 10
Data Types , Arrays, SuperGlobal Arrays Include, require, Cookies & Sessions
STRINGS
• <?php
echo “Hello World <br />”;
echo ‘Hello World <br />’;
$my_variable = “Hello World”;
echo $my_variable;
echo $my_variable . “ Again”;
?>
• Output: Hello World Again
HTML tags can also be
used in strings
We can also concatenate
EXAMPLE
• We can use variable in double quotes as well.
• <?php
$my_variable = “Hello World”; ?>
• <?php
echo “$my_variable Again.”; ?>
String Functions
• <?php
$firstString = “The quick brown tiger”;
$secondString = “ jumped over the lazy cat”; ?>
• <?php
$thirdString = $firstString;
$thirdString .= $secondString;
echo $thirdString; ?>
• Output: The quick brown tiger jumped over the lazy cat.
Another way of
• <?php $firstString = “The quick brown tiger”; ?> <br />
• Lower case:
<?php echo strtolower($firstString); ?><br />
• Upper case:
<?php echo strtoupper($firstString); ?><br />
• Uppercase first-letter:
<?php echo ucfirst($firstString); ?><br />
• Uppercase words:
• Length:
<?php echo strlen($firstString); ?><br/>
• Trim:
<?php echo $fourthString = $firstString .
Trim(secondString); ?><br/>
• Find:
<?php echo strstr($thirdString, “brown”); ?><br />
• Replace by String:
<?php echo str_replace(“quick”, “super-fast”, $thirdString); ?>
MORE STRING FUNCTIONS
• Repeat:str_repeat($thirdString, 2);
• Make substring:
substr($thirdString, 5, 10);
• Find position:
strpos($thirdString, “brown”);
• Find character:
Numbers
• <?php
$var1 = 3; $var2 = 4;
?>
Basic Math:
<?php echo ((1 + 2 + $var1)* var2) / 2 -5; ?>
<br />
EXAMPLE
• <?php
$var1 = 3; $var2 = 4;
?>
+=: <?php
$var2 += 4;
echo $var2;
?>
• Output: +=: 8
You can add any value and
• +=: <?php $var2 += 4; echo $var2; ?> <br/> • -=: <?php $var2 -= 4; echo $var2; ?> <br/> • *=: <?php $var2 *= 3; echo $var2; ?> <br/> • /=: <?php $var2 /= 4; echo $var2; ?> <br/>
• Output: +=: 8 -=: 4
INCREMENT & DECREMENT
• Increment by 1.
Increment: <?php $var2++; echo $var2; ?>
• Decrement by 1.
FLOATING POINT NUMBERS
• <?php $var1 = 3.14; ?>
• Floating Point: <?php echo $myFloat = 3.14; ?>
• Round: <?php echo round($myFloat, 1); ?>
• Ceiling: <?php echo ceil($myFloat); ?>
• Floor: <?php echo floor($myFloat); ?>
• Output: Floating Point: 3.14 Round: 3.1
FLOATING POINT FUNCTIONS
Absolute Value: abs(0 - 300);
Exponential: pow(2, 8);
Square Root: sqrt(100);
Modulo: fmod(20, 7);
Random (any): rand();
ARRAYS
• You can think of an array is a variable, in which you can assign multiple values.
• <?php $array = array(4, 8, 16, 17 , 23, 42); ?> <?php echo $array[1]; ?>
Output: 8
EXAMPLE
• <?php
$array2 = array(6, “amjad”, “aslam”, array(“x”, “y”, “z”)); ?>
<?php echo $array2[2]; ?> <br/> <?php echo $array2[3]; ?>
<?php echo $array2[3][1]; ?>
• Output: aslam Array
ADD/UPDATE THE VALUE OF ARRAY
• <?php
$array2[3] = “cat”;
?>
<br />
• <?php
echo $array2[3];
ASSOCIATIVE ARRAY
• <?php $array3 = array(“first_name” => “Yasir”, “last_name” => “Naeem”);
?>
• <?php echo $array3[“first_name”]; ?> <br/> • <?php echo $array3[“first_name”] . “ ” .
$array3[“last_name”]; ?>
• Output: Yasir
Yasir Naeem
• <?php $array3[“first_name”] = “Kashif”; ?>
• <?php echo $array3[“first_name”] . “ ” . $array3[“last_name”]; ?>
• Output: Kashif Naeem
• <pre><?php print_r($array2); ?></pre>
Print readable command gives
contents of an array in readable form
ARRAY FUNCTIONS
• <?php $array1 = array(4, 8, 15, 16, 23, 42); ?> Count: <?php echo count($array1); ?><br/>
Max value: <?php echo max($array1); ?><br/>
Min value: <?php echo min($array1); ?><br/>
Sort: <?php sort($array1); print_r($array1); ?>
• Implode: <?php echo $string1 = implode(“*”, $array1); ?> <br/>
Implode function is used to separate the array by * to make a string.
• Explode: <?php print_r(explode(“ * ”, $string1)); ?>
It does the reverse, it takes the string that we just created find every instance,
• In array: <?php
echo in_array(3, $array1);
?>
This function help us to find a
particular string or value in our array.
BOOLEANS
• <?php
$bool1 = true; $bool2 = false;
?>
$bool1: <?php echo $bool1; ?><br/> $bool2: <?php echo $bool2; ?><br/>
• Output: $bool1: 1 $bool2:
true/false doesn’t mean it’s a string. When we type true, php understands its
• <?php
$var1 = 3;
$var2 = “cat”;
?>
$var1 is set: <?php echo isset($var1); ?>
$var2 is set: <?php echo isset($var2); ?>
• Note: isset() is very useful function, which
we can use with conditional statements.
Through this function we are asking, is the value of the variable is set or not. It will
• <?php unset($var1); ?>
$var1 is set: <?php echo isset($var1); ?>
$var2 is set: <?php echo isset($var2); ?>
• Output: $var1 is set: $var2 is set: 1
This function will unset the value of a
• <?php
var4 = 0; var5 = “0”;
var6 = NULL;
?>
• <?php echo is_array($var1); ?><br/>
• <?php echo is_bool($var1); ?><br/>
• <?php echo is_float($var1); ?><br/>
• <?php echo is_int($var1); ?><br/>
• <?php echo is_null($var1); ?><br/>
• <?php echo is_numeric($var1); ?><br/>
CONSTANTS
• <?php
$max_width = 980;
define(“MAX_WIDTH”, 980);
echo MAX_WIDTH; echo “<br />” // MAX_WIDTH += 1;
// echo MAX_WIDTH; $max_width += 1;
echo $max_width;
?>
Error: Cannot apply += to constant. Because
MAX_WIDTH is fixed and unchangeable
It should be in all caps, and shouldn’t have $ sign
SuperGlobal Arrays
• In PHP, there is pre-defined array variables
present that is called superglobals.
Array Details
$_GET Store data that is sent from URL as query string
$_POST Data from FORM fields store in this array
$_COOKIE Data from Cookie store in this array e.g. you login to
hotmail.com, you provide username and password below it there is a checkbox and when you check this checkbox your username and password stored in cookie, next time to log on you don’t need to provide username and password it
retrieve from cookie.
$_FILES When through POST method we upload any file its
information stored in this array
$_SESSION
$_REQUEST Data in $_POST, $_GET, $_COOKIE store in this array, 3 in 1.
$_POST
• We use post method in a form. When we submit the button of form, all the data of form is send to $_POST array.
<form method=“post” action=“process.php”>
EXAMPLE
• Forms.php
• <form action = “process.php” method=“post”>
Username: <input type=“text” name=“username”
value=“” /> <br />
Password: <input type=“password” name=“password” value=“” /> <br />
<input type=“submit” name=“submit” value=“Submit” />
• Process.php (we just want to display values back to our page)
• <?php
$username = $_POST[‘username’]; $password = $_POST[‘password’];
echo “{$username}: {$password}”;
$_GET
• The data that we send through URL also known as
query string is stored in this super global array $_GET.
http://www.example.com/search.php?keyword=pakistan
• Query string started in URL after ? Sign.
• In a URL there may be more than one query string.
http://www.example.com/search.php?
HOW TO USE PHP WITH LINKS/URL’s
• <a href=“secondpage.php?id=1”>Second Page </a>
• What if instead on second page grasp this value of id, and be able to work with it.
EXAMPLE
• Firstpage.php
<a href=“secondpage.php?name=Yasir”>Second Page</a>
• Secondpage.php
<?php
print_r($_GET);
$name = $_GET[‘name’];
echo “<br/><strong>” . $name . “</strong>”;
?>
• When after ? You insert key value pair, PHP converts it into an array and we get the value of array in second page. This array is called super global. It is called
super global because it creates before the load of the page.
• We can access this super global array through $_GET
EXAMPLE
• Multiple values from URL, & is use to separate values.
• Firstpage.php
<a href=“secondpage.php?name=Yasir&id=1”>Second Page</a>
• Secondpage.php <?php
print_r($_GET);
$id = $_GET[‘id’];
$name = $_GET[‘name’];
echo “<br/><strong>” . $id . “: {$name} </strong>”; ?>
urlencode()
• What if the & is included in the name. we could come with some kind of string that we passes &, % # sign.
• Firstpage.php
<a href=“secondpage.php?name=<?php echo
urlencode(“Yasir&”); ?>&id=42”>Second Page</a>
• Secondpage.php
<?php
print_r($_GET); $id = $_GET[‘id’];
$name = $_GET[‘name’];
$_FILES
• When we upload a file or an image to server, it stores in $_FILES array.
• Example:
• User uploads a file from his computer c:\ docs\project.zip
• Its size is 20,000 bytes
• C:\docs\project.zip : $_FILES[userfile][name]
20000 : $_FILES[userfile][size]
• $file_name = $_FILES[‘userfile’][‘name’];
• $file_tmp_name = $_FILES[‘userfile’][‘tmp_name’]; • $file_size = $_FILES[‘userfile’][‘size’];
• $file_type = $_FILES[‘userfile’][‘type’];
• Because the file is uploaded on a
EXAMPLE
• Upload_form.php<html> <head>
<title>Upload File</title> </head>
<body>
<form method=“post” action=“upload.php” enctype=“multipart/form-data”>
<input type=“file” name=“userfile” />
<input type=“submit” value=“Upload” name=“action” /> </form>
• Upload.php
<?php
$upload_dir = “./user_files”;
$file_name = $_FILES[‘userfile’][‘name’];
$file_tmp_name = $_FILES[‘userfile’][‘tmp_name’]; $file_size = $_FILES[‘userfile’][‘size’];
$file_type = $_FILES[‘userfile’][‘type’];
if($file_size <= 0){
die(“cannot upload empty file”); }
if(is_uploaded_file($_FILES[‘userfile’][‘tmp_name’])){
move_uploaded_file($file_tmp_name, “$upload_dir/$file_name”); echo “$file_name has been successfully uploaded.”;
}else{
die(“possible file upload attack”); }
• There are three ways that we get data from our users on the web. User can provide
information to server through three ways.
• URL’s/Links GET
• Forms POST
• Cookies COOKIE
FORMS
• Forms are also known as POST method, because when user enter any data in form,
it is posted to our web server.
• When data is submitted to server, you can do lots of things with data i.e. You can
display on the web page, you can save it
in the database, you can give
COOKIE
• Another way to interact with our users in user’s browser is COOKIES.
• Cookies are very useful, putting data on user’s browser.
• Our web server make a request to their web browser to send back a cookie.
• Cookies are going to be access in the same way as POST.
SETTING COOKIE
• Format
setcookie($name, $value, $expire);
EXAMPLE
• <?php
setcookie(‘test’, 42, time()+(60*60*24*7));
?>
This command means our
cookie date of birth is declared
Expiration that we set in
READING COOKIES
• <?php
$var1 = $_COOKIE[‘test’]; echo $var1;
?>
• Deleting cookies
<?php
// this will delete the cookie
setcookie(‘test’, 0, time()-(60*60*24*7));
?>
DELETING COOKIE
• Whenever we read a cookie, its going to be a very good practice.
• <?php
$var1 = 0;
if(isset($_COOKIE[‘test’])) { $var1 = $_COOKIE[‘test’]; }
echo $var1; ?>
<?php
SESSION
• Session is a file that store on web server. And in
that file we can store whatever information we want.
• The way we find out which file belongs to which user is by using a cookie.
• So we set a special session cookie on their
• So, in order to use the session, we are going to have the first create this file and set the cookie on user’s machine. Or if we already done that. We are going to need to find that cookie and than find that
EXAMPLE
• We will go above the HTML and make sure the session start commands.
• <?php
// this command is going to say, PHP go to their
browser. Get the ID number for this session cookie. Come back find the file. Open it up, so we can use it.
session_start();
?>
<html> ……
HEADERS & PAGE REDIRECTION
• Whenever a server make a request to a PHP page, Before the server response to user browser’s request the HTML. It is
going to construct a set of headers. This is send these headers along to their web
page first.
• There are high level types of header commands we can get.
header( header information );
• Example:
header(“Content-type: application/pdf”);
header(“Content-type: application/vnd.ms-excel; name=‘excel’”);
• We going to sent PDF, say content type coming going to be a PDF to tell the
browser to take appropriate steps for pdf.
• For excel file, we will use second
• Because headers are very first thing is being sent. We want to make any
manipulation to headers whatsoever. It has to occur before anything else.
Remember we are telling their browser,
here is coming down to pipe. Get ready for it and then we send it. So we need to have headers at very beginning.
• <?php
// this is how you return 404 error
header(“HTTP/1.0 404 Not Found”);
exit;
?>
<html> …
EXAMPLE
• <?php
// this is how you redirect a page
header(“Location: basic.html”);
exit;
?>
<html> …
INCLUDE
• Through include feature you may include another PHP file in our PHP.
EXAMPLE
• Includes.php
<?php
include(“included_func.php”);
?>
• Included_func.php
EXAMPLE
• Includes.php<?php
include(“included_func.php”);
?>
<?php hello(“Everyone”); ?>
• Included_func.php <?php
function hello($name) { echo “Hello {$name}!”; }
• We can develop a one file which includes all of our functions. Or all of our functions which is related to certain types. E.g. functions related to filling of forms. Or functions related to
retrieving information from session variables.
• Included files includes another files.
• This is how we able to structure our code such a way, we don’t have to added the hello
• Now there is variation in include, there is also be using REQUIRE.
• <?php
require(“included_func.php”);
?>
• We can handle with require whenever
something like functions that is definitely going to be required. And use include whenever we are loading HTML or something that’s not
absolutely essential.
• There is one last variation in include and require, which is require_once.
• <?php