Chapter 6 Server Side
Chapter 6 Server Side
Chapter 6 Server Side
• PHP is a server-side technology. Therefore, you need to have a server to run PHP.
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code are executed on the server, and the result is returned to the browser as
plain HTML
• PHP files have extension ".php“
What Can PHP Do?
• PHP can generate dynamic page content.
• PHP can create, open, read, write, delete, and close files on the server.
• PHP can collect form data.
• PHP can send and receive cookies.
• PHP can add, delete, modify data in your database.
• PHP can restrict users to access some pages on your website.
• PHP can encrypt data.
Why We use PHP?
• A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to
be read by someone who is editing the code!
Comments are useful for:
To let others understand what you are doing .
To remind yourself what you did .
• PHP supports three ways of commenting:
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single line comment
# This is also a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
</body>
PHP Case Sensitivity
• In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo,
etc.) are NOT case-sensitive.
• In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
• However; in PHP, all variables are case-sensitive.
Cont…
• However; in PHP, all variables are case-sensitive.
• Example
• <!DOCTYPE html>
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
PHP Variables
• Variables are "containers" for storing information:
Cont…
Example
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Rules for PHP variables:
• 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 ($y and $Y are two different variables)
NOTE: Remember that PHP variable names are case-sensitive!
Declaring PHP Variables
• PHP has no command for declaring a variable.
• A variable is created the moment you first assign a value to it:
Example
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
Note: When you assign a text value to a variable, put quotes around the value.
PHP is a Loosely Type Language
PHP automatically converts the variable to the correct data type, depending on its
value.
PHP Variables Scope
• 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:
Cont…
• local
• global
• static
Local and Global Scope
• 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.
• The following example tests variables with local and global scope:
• Example
• <?php
$x=5; // global scope
function myTest() {
$y=10; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
• The following example shows how to display strings and variables with the echo
command:
Example
<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
echo "<br>";
echo "Study PHP at $txt2";
echo "My car is a {$cars[0]}";
?>
The PHP print Statement
print is also a language construct, and can be used with or without parentheses: print
or print().
Cont…
Example
<?php
print "<h2>PHP is fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
PHP Data Types
• String, Integer, Floating point numbers, Boolean, Array, Object, NULL.
PHP Strings
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:
Cont…
• Example
• <?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
PHP Integers
• An integer is a number without decimals.
• Rules for integers:
• An integer must have at least one digit (0-9)
• An integer cannot contain comma or blanks
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)
Cont…
• The PHP var_dump() function returns the data type and value of variables:
Example
<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>
PHP Floating Point Numbers
• The special NULL value represents that a variable has no value. NULL is the only
possible value of data type NULL.
• The NULL value identifies whether a variable is empty or not. Also useful to
differentiate between the empty string and null values of databases.
• Variables can be emptied by setting the value to NULL:
Example
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>
PHP String Functions
A string is a sequence of characters, like "Hello world!".
• Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
• In PHP we have the following conditional statements:
• if statement - executes some code only if a specified condition is true
• if...else statement - executes some code if a condition is true and another code if
the condition is false
• if...elseif....else statement - selects one of several blocks of code to be executed
• switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
• The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
• The example below will output "Have a good day!" if the current time (HOUR) is
less than 20:
Cont…
Example
<?php
$t=date("H");
if ($t<"20") {
echo "Have a good day!";
}
?>
PHP switch Statement
• The switch statement is used to perform different actions based on different conditions.
• Use the switch statement to select one of many blocks of code to be executed.
• Syntax
• switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
• Example
• <?php
$favcolor="red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
PHP while Loops
• PHP while loops execute a block of code while the specified condition is true.
PHP Loops
• Often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal code-lines in a script, we can
use loops to perform a task like this.
• In PHP, we have the following looping statements:
• 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
• For each- loops through a block of code for each element in an array.
Cont..
• The while loop executes a block of code as long as the specified condition is true.
• Syntax
• while (condition is true) {
code to be executed;
}
• The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will
continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each
time the loop runs ($x++;):
Example
<?php
$x=1;
while($x<=5) {
echo "The number is: $x <br>";
$x++;
}
?>
Cont…
• The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
• Syntax
• do {
code to be executed;
} while (condition is true);
• The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the
condition is checked (is $x less than, or equal to 5?), and the loop will continue to
run as long as $x is less than, or equal to 5:
Example
<?php
$x=1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
Cont…
• Notice that in a do while loop the condition is tested AFTER executing the
statements within the loop. This means that the do while loop would execute its
statements at least once, even if the condition fails the first time.
PHP for Loops
• PHP for loops execute a block of code a specified number of times.
Syntax
• for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
Cont…
Example
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP for each Loop
. The for each loop works only on arrays, and is used to loop through each key/value
pair in an array.
Syntax
For each ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
Cont…
Example
<?php
$colors = array("red","green","blue","yellow");
for each ($colors as $value) {
echo "$value <br>";
}
?>
PHP Functions
• The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the
default value as argument:
Example
<?php
function setHeight($minheight=50) {
echo "The height is : $minheight<br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
To loop through and print all the values of an indexed array, you could use a for loop,
like this:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
• Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
• $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Cont…
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could
use a foreach loop, like this:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
PHP Global Variables - Superglobals
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
• PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.
Example
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
$name = $_POST['fname'];
echo $name;
?>
</body>
</html>
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
PHP Cookies
What is a Cookie?
• 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 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.
• Session variables hold information about one single user, and are available to all pages in one application.
• If you need a permanent storage, you may want to store the data in a database.
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
Example
<?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>
Cont…
• Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
• Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the session, use session_unset() and session_destroy():
Cont…
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
PHP MySQL Database
What is MySQL?
• MySQL is a database system used on the web
• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
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.
Database Queries
• A query is a question or a request.
• We can query a database for specific information and have a record set returned.
Example:
SELECT LastName FROM Employees