Chapter 5 - PHP

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Chapter 5 – PHP

Introduction
PHP is an acronym for "Hypertext Preprocessor". It is a widely-used, open source scripting language. PHP
scripts are executed on the server and it is free to download and use. PHP can generate dynamic page
content. It can create, open, read, write, delete, and close files on the server. PHP can collect form data,
send and receive cookies, add, delete, and modify data in your database. It controls user-access and can
encrypt data. With PHP you are not limited to output HTML. You can output images or PDF files.

PHP is one of the best server side scripting languages, because:

 It runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.),


 It is compatible with almost all servers used today such as (Apache, IIS, etc.),
 It supports a wide range of databases,
 It is free to download from the official PHP resource: www.php.net,
 It is easy to learn and runs efficiently on the server side.

PHP Syntax
A PHP script can be placed anywhere in the document.

PHP script starts with <?php and ends with ?>.

<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP
scripting code. PHP statements end with a semicolon (;). In PHP, keywords (e.g. if, else, while, echo, etc.),
classes, functions, and user-defined functions are not case-sensitive. However; all variable names are case-
sensitive!

PHP Comments
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be read
by someone who is looking at the code. Comments can be used to Let others understand your code,
Remind yourself of what you did - Most programmers have experienced coming back to their own work a
year or two later and having to re-figure out what they did. Comments can remind you of what you were
thinking when you wrote the code.

PHP supports several ways of commenting:


// This is a single-line comment
# This is also a single-line comment
/*
this is a multiple-lines comment block
that spans over multiple
lines
*/

PHP echo and print Statements


With PHP, there are two basic ways to get output: echo and print. They are both used to output data to the
screen. “echo” has no return value while print has a return value of 1 so it can be used in expressions.
“echo” can take multiple parameters while print can take one argument. “echo” is marginally faster than
print.

The echo statement can be used with or without parentheses: echo or echo().

$x=2;
Echo "Hello world!<br>";
print "Hello world!<br>";
print "Study PHP " .$x."<br>";

PHP Variables
Variables are "containers" for storing information. In PHP, a variable starts with the $ sign, followed by the
name of the variable. A variable name must start with a letter or the underscore character. A variable name
cannot start with a number. A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _). Variable names are case-sensitive.

When you assign a text value to a variable, put quotes around the value. Unlike other programming
languages, PHP has no command for declaring a variable. It is created the moment you first assign a value
to it.

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script
where the variable can be referenced/used. PHP has three different variable scopes: local, global and static.
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. A
variable declared within a function has a LOCAL SCOPE and can only be accessed within that function. You
can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared.

The global keyword is used to access a global variable from within a function. To do this, use the global
keyword before the variables (inside the function): PHP also stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within
functions and can be used to update global variables directly.

Example:

<?php
$x = 5;
$y = 10;

function myTest() {
$x = 6; // local variable
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];//array stores global variables
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we
want a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword
when you first declare the variable. Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid
constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike
variables, constants are automatically global across the entire script.

To create a constant, use the define() function.

define(name, value, case-insensitive)

define("GREETING", "Welcome to W3Schools.com!");


echo GREETING;
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
Variables can store data of different types, and different data types can do different things.

PHP supports String, Integer, Float (double), Boolean, Array, Object, NULL, Resource data types.
 A string can be any text inside quotes. You can use single or double quotes.
$x = "Hello world!";
 An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
$x = 5985;
 A float (floating point number) is a number with a decimal point or a number in exponential form.
$x = 10.365;
 A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional
testing.
$x = true;
$y = false;
 An array stores multiple values in one single variable. In PHP, the array() function is used to create
an array. The count() function is used to return the length (the number of elements) of an array.
$cars = array("Volvo","BMW","Toyota");
echo count($cars);
In PHP, there are three types of arrays:
- Indexed arrays - Arrays with a numeric index
$cars = array("Volvo", "BMW", "Toyota");
- Associative arrays - Arrays with named keys
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); or
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
- Multidimensional arrays - Arrays containing one or more arrays
- The elements in an array can be sorted in alphabetical or numerical order, descending or
ascending.
o sort() - sort arrays in ascending order
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
o rsort() - sort arrays in descending order
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
o asort() - sort associative arrays in ascending order, according to the value
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
o ksort() - sort associative arrays in ascending order, according to the key
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
o arsort() - sort associative arrays in descending order, according to the value
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
o krsort() - sort associative arrays in descending order, according to the key
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
 The PHP var_dump() function returns the data type and value.
 PHP Object
Classes and objects are the two main aspects of object-oriented programming. A class is a template
for objects, and an object is an instance of a class. When the individual objects are created, they
inherit all the properties and behaviors from the class, but each object will have different values for
the properties. Let's assume we have a class named Car. A Car can have properties like model,
color, etc. We can define variables like $model, $color, and so on, to hold the values of these
properties. When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties. If you create a __construct() function, PHP will automatically call this function when you
create an object from a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color." " .$this->model. "!";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
 PHP NULL Value
Null is a special data type which can have only one value: NULL. A variable of data type NULL is a
variable that has no value assigned to it. If a variable is created without a value, it is automatically
assigned a value of NULL. Variables can also be emptied by setting the value to NULL.
$x = null;

PHP Strings
 The PHP strlen() function returns the length of a string.
echo strlen("Hello world!"); // outputs 12
 The PHP str_word_count() function counts the number of words in a string.
echo str_word_count("Hello world!"); // outputs 2
 The PHP strrev() function reverses a string.
echo strrev("Hello world!"); // outputs !dlrow olleH
 The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return FALSE.
The first character position in a string is 0.
echo strpos("Hello world!", "world"); // outputs 6
 The PHP str_replace() function replaces some characters with some other characters in a string.
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!

PHP Numbers
 PHP uses is_int() function to check if the type of a variable is integer.
$x = 59.85;
var_dump(is_int($x));
 The pi() function returns the value of PI:
echo(pi()); // returns 3.1415926535898
 The min() and max() functions can be used to find the lowest or highest value in a list of arguments:
echo(min(0, 150, 30, 20, -8, -200)); // returns -200
echo(max(0, 150, 30, 20, -8, -200)); // returns 150
 The sqrt() function returns the square root of a number:
echo(sqrt(64)); // returns 8
 The round() function rounds a floating-point number to its nearest integer:
echo(round(0.60)); // returns 1
echo(round(0.49)); // returns 0
HOW echo(round(0.5));???
 The rand() function generates a random number:
echo(rand());
To get more control over the random number, you can add the optional min and max parameters to
specify the lowest integer and the highest integer to be returned.
echo(rand(10, 100));

PHP Operators
Arithmetic Name Example Result
Operator
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Comparison Name Example Result
Operator
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x=== $y Returns true if $x is equal to $y, and they are of
the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are
not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x<=> $y Returns an integer less than, equal to, or greater
than zero, depending on if $x is less than, equal
to, or greater than $y. Introduced in PHP 7.
Increment Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Logical Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

Example: Operators

<?php
$x=2; $y=4; // //Assignment operator
echo "Sum=".($x + $y) ."<br>"; // arithmetic operation
echo "Exponent=".($x**$y)."<br>"; // x to the power of y
echo "Short form=".($x+=$y)."<br>"; // $x = $x + $y;
echo "Comparision=".($x >= $y)."<br>" ; // Comparision operator
echo "Spaceship=".(3 <=> 4)."<br>"; // equal gives 0. Left is greater gives 1. Right greater gives -1
echo "Post increment:".$x++."<br>"; // Post increment returns $x and then increments $x
echo "Pre increment:".++$x."<br>"; // Pre increment increments $x and then returns $x
echo "Logical operation:".((3 > 4) || (2 == 2))."<br>"; // Logical operation
?>
PHP conditional Statements
Conditional statements are used to perform different actions based on different conditions. Very often
when you write code, you want to perform different actions for different conditions. You can use
conditional statements in your code to do this.

In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that condition is
false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed
<?php
$t=date("D");
if($t=="Mon"){
echo "We have Security class today"."<br>";
}
else if($t=="Tue"){
echo "We have Internet programming class today"."<br>";
}
else if($t=="Wed"){
echo "We have data structure class today"."<br>";
}
else if($t=="Thu"){
echo "We have requirement class today"."<br>";
}
else if($t=="Fri"){
echo "We have no class today"."<br>";
}
switch($t){
case "Mon": echo "We have Security class today"."<br>";
break;
case "Tue": echo "We have Internet programming class today"."<br>";
break;
case "Wed": echo "We have data structure calss today"."<br>";
break;
case "Thu": echo "We have requirement class today"."<br>";
break;
case "Fri": echo "We have no class today"."<br>";
break;
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain number
of times. So, instead of adding several almost equal code-lines in a script, we can use loops. Loops are used
to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array
 The break statement is used to jump out of a loop.
 The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example:
<?php
$x=1; $sum=0;
//*****************************
while($x<10){
if($x==5) break;
$sum=$sum+$x;
$x++; }
echo "While SUM=".$sum."<br>";
//****************************
$sum=0;
for($x=1; $x<10; $x++){
if($x==6){continue;}
$sum=$sum+$x;}
echo "For SUM=".$sum."<br>";
//**************************
$x=1; $sum=0;
do{
if($x==4) break;
$sum=$sum+$x;
$x++;
}while($x<10);
echo "Dowhile SUM=".$sum."<br>";
//****************************
echo "Fruits:"."<br>";
$fruits=array("Banana","Organe","Apple");
foreach($fruits as $v){
echo $v."<br>";
}
?>
PHP Functions
A user-defined function declaration starts with the word function:
function functionName() {
code to be executed;
}
Information can be passed to functions through arguments. An argument is just like a variable. Arguments
are specified after the function name, inside the parentheses. You can add as many arguments as you
want, just separate them with a comma.

Example:
<?php
function msg(){ // Function without parameters
echo "Let me tell your age"."<br>";
}
function age($a) { // Function with parameter
echo "You are ".$a." years old"."<br>";
}
function sum($x,$y){
return $x+$y; // Function with return values
}
echo "Sum of 4 and 5 is:".sum(4,5)."<br>";
msg();
age(20);
age(21);
?>
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function
and the variable that was passed into the function cannot be changed. When a function argument is passed
by reference, changes to the argument also change the variable that was passed in. To turn a function
argument into a reference, the & operator is used.

<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
PHP Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a
text, you can use this search pattern to describe what you are searching for. A regular expression can be a
single character, or a more complicated pattern. Regular expressions can be used to perform all types of
text search and text replace operations. In PHP, regular expressions are strings composed of delimiters, a
pattern and optional modifiers.

Example:
$exp = "/w3schools/i";

In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a
modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common
delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose
other delimiters such as # or ~.

PHP provides a variety of functions that allow you to use regular expressions. The preg_match(),
preg_match_all() and preg_replace() functions are some of the most commonly used ones:

 preg_match() Returns 1 if the pattern was found in the string and 0 if not
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>
 preg_match_all() Returns the number of times the pattern was found in the string
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
 preg_replace() Returns a new string where matched patterns have been replaced with another
string

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
?>

 Modifiers can change how a search is performed.


o i-Performs a case-insensitive search
o m-Performs a multiline search (patterns that search for the beginning or end of a string will
match the beginning or end of each line)
o u-Enables correct matching of UTF-8 encoded patterns
 Brackets are used to find a range of characters:
o [abc] Find one character from the options between the brackets
o [^abc] Find any character NOT between the brackets
o [0-9] Find one character from the range 0 to 9
 Metacharacters are characters with a special meaning:
o | Find a match for any one of the patterns separated by | as in: cat|dog|fish
o . Find just one instance of any character
o ^ Finds a match as the beginning of a string as in: ^Hello
o $ Finds a match at the end of the string as in: World$
o \d Find a digit
o \s Find a whitespace character
o \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word
like this: WORD\b
o \uxxxx Find the Unicode character specified by the hexadecimal number xxxx
 Quantifiers define quantities:
o n+ Matches any string that contains at least one n
o n* Matches any string that contains zero or more occurrences of n
o n? Matches any string that contains zero or one occurrences of n
o n{x} Matches any string that contains a sequence of X n's
o n{x,y} Matches any string that contains a sequence of X to Y n's
o n{x,} Matches any string that contains a sequence of at least X n's
If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape
them. For example, to search for one or more question marks you can use the following expression:
$pattern = '/\?+/';
 You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts
of the pattern to be used as a match.
Example:
Use grouping to search for the word "banana" by looking for ba followed by two instances of na:

o <?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1
?>

PHP Form Handling


The PHP super globals $_GET and $_POST are used to collect form-data. Both GET and POST create an array
(e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where
keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are super global, which means that they are
always accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special

$_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of
variables passed to the current script via the HTTP POST method.

Information sent from a form with the GET method is visible to everyone (all variable names and values are
displayed in the URL). GET also has limits on the amount of information to send. The limitation is about

2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases. GET may be used for sending non-sensitive data. GET should NEVER
be used for sending passwords or other sensitive information!

Information sent from a form with the POST method is invisible to others (all names/values are embedded
within the body of the HTTP request) and has no limits on the amount of information to send. Moreover
POST supports advanced functionality such as support for multi-part binary input while uploading files to
server. However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.

The form in the source page looks like the following:


<form method="POST" action="welcome.php">
<label>Name:</label><input type="text" name="fname"> <br>
<label>Email:</label><input type="email" name="mail"> <br>
<input type="submit" value="Submit">
</form>
The code in the destination page (welcome.php) looks like the following:
<?php
echo "Welcome ".$_POST['fname'];
//echo "Welcome ".$_GET['fname'];
?>
 $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently
executing script. $_SERVER["PHP_SELF"] sends a submitted form data to the page itself, instead of
jumping to a different page. This way, the user will get error messages on the same page as the
form.
 htmlspecialchars() function converts special characters to HTML entities. This means that it will
replace HTML characters like < and > with &lt; and &gt; . This prevents attackers from exploiting the
code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
 Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web
applications. XSS enables attackers to inject client-side script into Web pages viewed by other users.
o Example:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
In this case, the above code will be translated to:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
The htmlspecialchars() function converts special characters to HTML entities. Now if the user
tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/
&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">
The exploit attempt fails, and no harm is done!
 PHP trim() function strips unnecessary characters (extra space, tab, newline) from the user input
data.
 PHP stripslashes() function removes backslashes (\) from the user input data
 Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been
submitted - and it should be validated. If it has not been submitted, skip the validation and display a
blank form.
 Example:
<?php
$name=$email=$nameerr=$emailerr="";
if($_SERVER['REQUEST_METHOD'] == "POST") {

if(empty($_POST['fname'])){
$nameerr="Please input your name";
}else{
$name=htmlspecialchars(stripslashes(trim($_POST['fname'])));
}
if(empty($_POST['mail'])){
$emailerr="Please input your email";
}else{
$email=htmlspecialchars(stripslashes(trim($_POST['mail'])));
}
if(empty($nameerr) && empty($emailerr)){
echo "Welcome ".$name."<br>";
echo "Your email ".$email." is recieved.";
}
}
?>
 The preg_match() function searches a string for pattern, returning true if the pattern exists, and
false otherwise. The code below shows a simple way to check if the name field only contains letters,
dashes, apostrophes and whitespaces.
$name = $_POST["name"];
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
 PHP's filter_var() function is the easiest and safest way to check whether an email address is well-
formed.
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP Date and Time
The PHP date() function is used to format a date and/or a time.

Syntax
date(format,timestamp)
format Specifies the format of the timestamp
timestamp Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at
which a certain event occurred.
Characters that are commonly used for dates are:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Example:

<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y") . "<br>";
echo "Today is " . date("m") . "<br>";
echo "Today is " . date("d") . "<br>";
echo "Today is " . date("l") . "<br>";
echo date("h:i:s"). "<br>";
?>
PHP include and require Statements
The include (or require) statement takes all the text/code/markup that exists in the specified file and
copies it into the file that uses the include statement. Including files is very useful when you want to
include the same PHP, HTML, or text on multiple pages of a website. It is possible to insert the content of
one PHP file into another PHP file (before the server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:

 require will produce a fatal error (E_COMPILE_ERROR) and stop the script
 include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use the
include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always
use the require statement to include a key file to the flow of execution. This will help avoid compromising
your application's security and integrity, just in-case one key file is accidentally missing.

Including files saves a lot of work. This means that you can create a standard header, footer, or menu file
for all your web pages. Then, when the header needs to be updated, you can only update the header
include file.
Syntax
include 'filename';
or
require 'filename';
PHP File Handling
File handling is an important part of any web application. You often need to open and process a file for
different tasks. PHP has several functions for creating, reading, uploading, and editing files.

When you are manipulating files you must be very careful. You can do a lot of damage if you do something
wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, and deleting the
content of a file by accident.

 The readfile() function reads a file and writes it to the output buffer.
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function returns the number of bytes read on success.
 A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function. The first parameter of fopen() contains the name of the file to be
opened and the second parameter specifies in which mode the file should be opened. The following
example also generates a message if the fopen() function is unable to open the specified file:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

The file may be opened in one of the following modes:

Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end
of the file. Creates a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end
of the file. Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists

 The fread() function reads from an open file.


The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read. The following PHP code reads the
"webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
 The fclose() function is used to close an open file.
 The fgets() function is used to read a single line from a file. After a call to the fgets() function, the
file pointer has moved to the next line.
 The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful
for looping through data of unknown length.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
 The fgetc() function is used to read a single character from a file.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
 A file is created using the same function used to open files. If you use fopen() on a file that does not
exist, it will create it, given that the file is opened for writing (w) or appending (a).
$myfile = fopen("testfile.txt", "w");
 The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of
the file to write to and the second parameter is the string to be written.
 You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the
file, while the "w" mode overrides (and erases) the old content of the file.

PHP Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.

A cookie is created with the setcookie() function.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1
day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
 To modify a cookie, just set (again) the cookie using the setcookie() function.
 To delete a cookie, use the setcookie() function with an expiration date in the past.

PHP 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 user’s computer. When you work with an application, you open it, do
some changes, and then you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet there is one problem: the
web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across multiple pages (e.g.
username, favorite color, etc). By default, session variables last until the user closes the browser. So;
Session variables hold information about one single user, and are available to all pages in one application.

A session is started with the session_start() function. Session variables are set with the PHP global variable:
$_SESSION. The session_start() function must be the very first thing in your document. Before any HTML
tags.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
 To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
PHP MySQL Database
With PHP, you can connect to and manipulate databases. MySQL is the most popular database system used
with PHP.
 MySQL is a database system used on the web. It is a database system that runs on a server and it is
ideal for both small and large applications. MySQL is very fast, reliable, and easy to use. ItL uses
standard SQL. MySQL compiles on a number of platforms. It is free to download and use. It is
developed, distributed, and supported by Oracle Corporation. MySQL is named after co-founder
Monty Widenius's daughter: My. PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)
 The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
 PHP 5 and later can work with a MySQL database using:
o MySQLi extension (the "i" stands for improved) and PDO (PHP Data Objects)
o Earlier versions of PHP used the MySQL extension. However, this extension was
deprecated in 2012.
o PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases. So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries. With
MySQLi, you will need to rewrite the entire code - queries included. Both are object-
oriented, but MySQLi also offers a procedural API. Both support Prepared Statements.
Prepared Statements protect from SQL injection, and are very important for web application
security.
o Using of Object-Oriented MySQLi to Connect to MySQL to PHP:
<?php
// Create connection
$conn = new mysqli("localhost", "root", " "); //server name, username
and password
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
o The connection will be closed automatically when the script ends. To close the connection
before, use the following:
 $conn->close(); // MySQLi Object-Oriented:
o The CREATE DATABASE statement is used to create a database in MySQL.
<?php
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
o The CREATE TABLE statement is used to create a table in MySQL.
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
o After a database and a table have been created, we can start adding data in them.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
o Multiple SQL statements must be executed with the mysqli_multi_query() function.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
o The SELECT statement is used to select data from one or more tables. We can use the *
character to select ALL columns from a table:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

You might also like