SlideShare ist ein Scribd-Unternehmen logo
1 von 66
1
Outline
 History of PHP
 PHP Introduction
 Running XAMPP
 Dreamweaver Site Setup
 PHP file, PHP workings, running PHP.
 Some useful PHP functions
 Basic PHP syntax
 variables, operators, if...else...and switch, for, while, do while,
for, functions, Cookies and Sessions .
By: Eng Mohammed Hussein 2
History of PHP
 PHP developed into full-featured, scripting language for server-side
programming.
 Rasmus Lerdorf has invented PHP/FI language (1994-1995) using Perl
language.
 PHP/FI has developed to PHP/FI2 using C language (1997).
 PHP3 developed by (Rasmus Lerdorf, Zeev Suraski, Andi Gutmans) with
support connect to Database (1998).
 PHP4 emerged with more properties to PHP3 such as:
 Object oriented , free, open-source
 More support to database
 Sessions
 XML and JavaScript supported
 …
 PHP5
 Current version
3By: Eng Mohammed Hussein
PHP Introduction
 What is PHP?
 PHP stands for PHP: Hypertext Preprocessor.
 PHP is a server-side scripting language, like ASP.
 PHP scripts are executed on the server.
 PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
 PHP is an open source software.
 PHP is free to download and use.
 PHP is similar to JavaScript, only on a server-side language.
 PHP code is embedded in HTML using tags.
4By: Eng Mohammed Hussein
PHP Introduction
 What is a PHP File?
 PHP files can contain text, HTML tags and scripts
 PHP files are returned to the browser as plain HTML
 PHP files have a file extension of ".php", ".php3", or ".phtml"
 When a page was requested, the server recognizes PHP
content via the file extension (.php).
 The server executes the PHP code, and the PHP page results
is showing to the client as HTML page.
 the PHP code never appear to users, only the output in the
HTML page.
By: Eng Mohammed Hussein 5
What is MySQL?
 MySQL is a database server.
 MySQL is ideal for both small and large applications.
 MySQL supports standard SQL.
 MySQL compiles on a number of platforms.
 MySQL is free to download and use.
 PHP + MySQL
 PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform).
 Why PHP?
 PHP runs on different platforms (Windows, Linux, Unix, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP is FREE to download from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
6By: Eng Mohammed Hussein
Where to Start?
 What do you Need?
 If your server supports PHP you don't need to do anything.
 Just create some .php files in your web directory, and the server will parse
them for you. Because it is free, most web hosts offer PHP support.
 However, if your server does not support PHP, you must install PHP.
 Here is a link to a good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
 To get access to a web server with PHP support, you can:
 Install XAMPP Apache (or IIS) on your own server, install PHP, and
MySQL
 Or find a web hosting plan with PHP and MySQL support.
 If you download and Install XAMPP Apache server, you will find PHP, and
MySql already existed inside the XAMPP application. But if you want to
install each one separately then follow these links:
 Download PHP for free here: http://www.php.net/downloads.php
 Download MySQL for free here: http://www.mysql.com/downloads/
7By: Eng Mohammed Hussein
Running XAMPP
8By: Eng Mohammed Hussein
Just click on Admin then the
default browser will appear.
Security settings
 Security console MySQL & XAMPP directory protection
By: Eng Mohammed Hussein 9
http://localhost/security/xamppsecurity.php
User: root
password: root
MySQL database
 Use this link for accessing the
MySQL database:
 http://localhost/phpmyadmin/
By: Eng Mohammed Hussein 10
Running PHP Examples
 Write in the browser URL bar http://localhost
 Put your site folder into this path :
 C:xampphtdocsyour folder
 Then in the browser URL, write your folder name after
localhost as: http://localhost/your folder/
 To run a.php file on local server, just add the name of the file
as the following example:
 http://localhost/php/a.php
11By: Eng Mohammed Hussein
Dreamweaver –Site Setup
 The pictures below will show you the steps that used to
setup your site inside local server in order to run php files
using Adobe Dreamweaver.
12By: Eng Mohammed Hussein
Dreamweaver -Site
13By: Eng Mohammed Hussein
Dreamweaver -Servers
14By: Eng Mohammed Hussein
Here, how to add, delete and edit the servers information
Dreamweaver -Servers
15By: Eng Mohammed Hussein
Dreamweaver -Servers
16By: Eng Mohammed Hussein
PHP Syntax
 PHP code is executed on the server, and
the plain HTML result is sent to the
browser.
 Basic PHP Syntax
 A PHP scripting block always starts with
<?php and ends with ?>. A PHP
scripting block can be placed anywhere in
the document.
 On servers with shorthand support
enabled you can start a scripting block
with <? and end with ?>.
 For maximum compatibility, we
recommend that you use the standard
form (<?php) rather than the shorthand
form.
<?php
?>
17By: Eng Mohammed Hussein
Example 1
PHP Syntax
 A PHP file normally contains HTML tags, just like an
HTML file, and some PHP scripting code.
 We have an example of a simple PHP script which sends
the text "Hello World" to the browser.
 Each code line in PHP must end with a semicolon. The
semicolon is a separator and is used to distinguish one
set of instructions from another.
 There are two basic statements to output text with PHP:
echo and print. In the example we have used the echo
statement to output the text "Hello World".
 Note: The file must have a .php extension. If the file has
a .html extension, the PHP code will not be executed.
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
18By: Eng Mohammed Hussein
Comments in PHP
 In PHP, we use // to make a single-line comment
 or /* and */ to make a large comment block.
<html>
<body>
<?php
//This is a comment
/* This is
a comment
block */
?>
</body>
</html>
19By: Eng Mohammed Hussein
PHP Variables
 A variable is used to store information.
 Variables in PHP
 Variables are used for storing values, like text strings, numbers or
arrays.
 When a variable is declared, it can be used over and over again in
your script.
 All variables in PHP start with a $ sign symbol.
 The correct way of declaring a variable in PHP
$var_name = value;
20By: Eng Mohammed Hussein
PHP Variables
 New PHP programmers often forget the $ sign at the
beginning of the variable. In that case it will not work.
 Let's try creating a variable containing a string, and a variable
containing a number:
<?php
$txt="Hello World!";
$x=16;
echo $txt;
echo "<br>";
echo $x;
?>
21By: Eng Mohammed Hussein
PHP is a Loosely Typed Language
 In PHP, a variable does not need to be declared before adding a value to it. In the
previous slide example , you have seen that you do not have to tell PHP which data
type the variable is ? . PHP automatically converts the variable to the correct data
type, depending on its value.
 In an other programming language, you have to declare (define) the type and name
of the variable before using it. In PHP, the variable is declared automatically when
you use it.
 Rules for Variables
 A variable name must start with a letter or an underscore "_"
 A variable name can only contain alpha-numeric characters and underscores (a-
z, A-Z, 0-9, and _ )
 A variable name should not contain spaces. If a variable name is more than one
word, it should be separated with an underscore ($my_string), or with
capitalization ($myString)
22By: Eng Mohammed Hussein
PHP String Variables
A string variable is used to store and manipulate text.
 String Variables in PHP
 String variables are used for values that contain characters.
 In this slide we are going to look at the most common
functions and operators used to manipulate strings in PHP.
 After we create a string we can manipulate it. A string can be
used directly in a function or it can be stored in a variable.
 Below, the PHP script assigns the text "Hello World" to a
string variable called $txt.
<?php
$r = “This is”BAD”; // ‫خطأ‬
$t = "This is „good"; // ‫صحيح‬
?>
<?php
$txt="Hello World";
echo $txt;
?>
23By: Eng Mohammed Hussein
The Concatenation Operator
 There is only one string operator in PHP.
 The concatenation operator (.) is used to put two string values
together.
 To concatenate two string variables together, use the concatenation
operator
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
If we look at the code above you see that we used the concatenation
operator two times. This is because we had to insert a third string (a
space character), to separate the two strings.
24By: Eng Mohammed Hussein
PHP String functions
 The strlen() function
 The strlen() function is used to return the length of a string.
 Let's find the length of a string:
<?php
echo strlen("Hello world!");
?>
The length of a string is often used in loops or other functions,
when it is important to know when the string ends. (i.e. in a loop,
we would want to stop the loop after the last character in the
string).
25By: Eng Mohammed Hussein
PHP String functions
 The strpos() function
 The strpos() function is used to search for a character/text within
a string.
 If a match is found, this function will return the character position
of the first match. If no match is found, it will return FALSE.
 Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
The position of the string "world" in the example above is
6. The reason that it is 6 (and not 7), is that the first
character position in the string is 0, and not 1.
26By: Eng Mohammed Hussein
Complete PHP String Reference
Functions Description PHP
echo() Outputs strings 3
chr() Returns a character from a specified ASCII value 3
fprintf() Writes a formatted string to a specified output stream 5
substr_compare() Compares two strings from a specified start position
(binary safe and optionally case-sensitive)
5
strip_tags() Strips HTML and PHP tags from a string 3
str_split() Splits a string into an array 5
print() Outputs a string 3
ord() Returns the ASCII value of the first character of a
string
3
number_format() Formats a number with grouped thousands 3
htmlspecialchars_
decode()
Converts some predefined HTML entities to characters 5
ereg_replace() filter everything but numbers and used for security
27By: Eng Mohammed Hussein
PHP Operators
 Operators are used to operate on values.
Operator Description Example Result
+ Addition x=2  x+2 4
- Subtraction x=2  5-x 3
* Multiplication x=4  x*5 20
/ Division 15/5 , 5/2 3 , 2.5
% Modulus (division remainder) 5%2
10%8
10%2
1
2
0
++ Increment x=5  x++ x=6
-- Decrement x=5  x-- x=4
28By: Eng Mohammed Hussein
PHP-Assignment Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
29By: Eng Mohammed Hussein
PHP-Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than
or equal to
5>=8 returns false
<= is less than or
equal to
5<=8 returns true
30By: Eng Mohammed Hussein
PHP-Logical Operators
Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
31By: Eng Mohammed Hussein
PHP If...Else Statements
 Conditional statements are used to perform different actions based
on different conditions.
 Conditional Statements
 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 - use this statement to execute some code only if a
specified condition is true
 if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false
 if...elseif....else statement - use this statement to select one of several
blocks of code to be executed
 switch statement - use this statement to select one of many blocks of
code to be executed
32By: Eng Mohammed Hussein
The if Statement
 Use the if statement to execute some code only if a specified
condition is true.
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice
weekend!";
?>
</body>
</html>
33By: Eng Mohammed Hussein
The if...else Statement
 Use the if....else statement to execute some code if a condition is true
and another code if a condition is false.
 if a condition is true/false, the output "Have a nice weekend!" if the
current day is Friday, otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
34By: Eng Mohammed Hussein
The if...elseif....else Statement
The following example will
output "Have a nice
weekend!" if the current day is
Friday, and "Have a nice
Sunday!" if the current day is
Sunday. Otherwise it will
output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
35By: Eng Mohammed Hussein
PHP Switch Statement
 Conditional statements are used
to perform different actions based
on different conditions.
 Use the switch statement to select
one of many blocks of code to be
executed.
<html>
<body>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and
3";
}
?>
</body>
</html>
36By: Eng Mohammed Hussein
PHP - For Loops
 For Loops
 Loops execute a block of code a specified number of times, or while a
specified condition is true.
 The for loop is used when you know in advance how many times the
script should run.
 The foreach Loop
 The foreach loop is used to loop through arrays.
By: Eng Mohammed Hussein 37
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>
PHP – while
 The while Loop
 The while loop executes a block of code while a condition is true.
 The do...while Loop
 The do...while statement will always execute the block of code
once, it will then check the condition, and repeat the loop while
the condition is true.
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
By: Eng Mohammed Hussein 38
PHP Arrays
 An array stores multiple values in one single variable.
 A variable is a storage area holding a number or text. The
problem is, a variable will hold only one value.
 An array is a special variable, which can store multiple
values in one single variable.
 In PHP, there are three kind of arrays:
 Numeric array - An array with a numeric index
 Associative array - An array where each ID key is
associated with a value
 Multidimensional array - An array containing one or more
arrays
39By: Eng Mohammed Hussein
PHP- Numeric Arrays
 A numeric array stores each array element with a numeric
index.
 There are two methods to create a numeric array.
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>
<?php
$cars=array("Saab","Volvo","BMW","Toyota");
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>
1. In the example the
index are automatically
assigned (the index
starts at 0):
2. In the example we
assign the index
manually:
40By: Eng Mohammed Hussein
Associative Arrays
 An associative array, each ID key is associated with a value.
 When storing data about specific named values, a numerical
array is not always the best way to do it.
 With associative arrays we can use the values as keys and
assign values to them.
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
Example 1
Example 2
41By: Eng Mohammed Hussein
Multidimensional Arrays
 In a multidimensional array, each element in the main array can also
be an array. And each element in the sub-array can be an array, and
so on.
$families = array
(
"Griffin"=>array
( "Peter“, "Lois“, "Megan“ ),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
Example 2Example 1
42By: Eng Mohammed Hussein
PHP Include File
 Server Side Includes (SSI)
 You can insert the content of one PHP file into another PHP file before
the server executes it, with the include() or require() function.
 The two functions are identical in every way, except how they handle
errors:
 include() generates a warning, but the script will continue execution
 require() generates a fatal error, and the script will stop
 These two functions are used to create functions, headers, footers, or
elements that will be reused on multiple pages.
 Server side includes saves a lot of work. This means that you can
create a standard header, footer, or menu file for all your web pages.
When the header needs to be updated, you can only update the
include file, or when you add a new page to your site, you can
simply change the menu file (instead of updating the links on all
your web pages).
By: Eng Mohammed Hussein 43
PHP include() Function
 The include() function takes all the content in a specified
file and includes it in the current file.
 If an error occurs, the include() function generates a
warning, but the script will continue execution.
By: Eng Mohammed Hussein 44
<html>
<body>
<? php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
PHP require() Function
 The require() function is identical to include(), except that
it handles errors differently.
 If an error occurs, the include() function generates a
warning, but the script will continue execution. The
require() generates a fatal error, and the script will stop.
By: Eng Mohammed Hussein 45
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error Example include() Function Error Example require() Function
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
PHP Functions
 In PHP, there are more than 700
built-in functions.
 A function will be executed by a
call to the function.
 You may call a function from
anywhere within a page.
By: Eng Mohammed Hussein 46
<html>
<body>
<?php
function writeName()
{
echo “Mohammed Hussein";
}
echo "My name is ";
writeName();
?>
</body>
</html>
PHP Function examples
By: Eng Mohammed Hussein 47
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
PHP Functions - Return values
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Hussein" . $punctuation .
"<br />";
}
echo "My name is ";
writeName(“Mohammed",".");
echo "My Son's name is ";
writeName(“Abdulkareem M","!");
echo "My brother's name is ";
writeName(“Ali","?");
?>
</body>
</html>
PHP Functions - Adding parameters
PHP Forms and User Input
 The PHP $_GET and $_POST variables are used to retrieve
information from forms, like user input.
 The most important thing to notice when dealing with HTML
forms and PHP is that any form element in an HTML page will
automatically be available to your PHP scripts.
By: Eng Mohammed Hussein 48
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
PHP Forms on submit button
 When a user fills out the form and click on the submit button,
the form data is sent to a PHP file, called "welcome.php":
By: Eng Mohammed Hussein 49
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
PHP $_GET
 In PHP, the predefined $_GET variable is used to collect
values in a form with method="get".
 Information sent from a form with the GET method is
visible to everyone (it will be displayed in the browser's
address bar) and has limits on the amount of information
to send.
By: Eng Mohammed Hussein 50
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent to the server
could look something like this:
http://localhost/php/ welcome.php?fname=Peter&age=37
PHP $_GET
 The "welcome.php" file can now use the $_GET variable
to collect form data (the names of the form fields will
automatically be the keys in the $_GET array):
By: Eng Mohammed Hussein 51
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
When to use method="get"?
When using method="get" in HTML forms, all variable names and
values are displayed in the URL.
Note: This method should not be used when sending passwords or
other sensitive information. However, because the variables are
displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases.
Note: The get method is not suitable for very large variable values.
It should not be used with values exceeding 2000 characters.
PHP $_POST
 In PHP, the predefined $_POST variable is used to collect
values in a form with method="post".
 Information sent from a form with the POST method is
invisible to others and has no limits on the amount of
information to send.
 Note: However, there is an 8 Mb max size for the POST
method, by default (can be changed by setting the
post_max_size in the php.ini file).
By: Eng Mohammed Hussein 52
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
PHP $_POST
 When the user clicks the "Submit" button, the URL will
look like this:
 The "welcome.php" file can now use the $_POST variable
to collect form data (the names of the form fields will
automatically be the keys in the $_POST array):
By: Eng Mohammed Hussein 53
http://localhost/php/ welcome.php
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
PHP $_POST
 When to use method="post"?
 Information sent from a form with the POST method is invisible to
others and has no limits on the amount of information to send.
 However, because the variables are not displayed in the URL, it is
not possible to bookmark the page.
 The PHP $_REQUEST Variable
 The predefined $_REQUEST variable contains the contents of both
$_GET, $_POST, and $_COOKIE.
 The $_REQUEST variable can be used to collect form data sent with
both the GET and POST methods.
By: Eng Mohammed Hussein 54
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
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.
 How to Create a Cookie?
 The setcookie() function is used to set a cookie.
 Note: The setcookie() function must appear BEFORE the
<html> tag.
By: Eng Mohammed Hussein 55
setcookie(name, value, expire, path, domain);Syntax:
Cookie Example 1
 In the example below, we will create a cookie named
"user" and assign the value “Mohammed" to it. We also
specify that the cookie should expire after one hour:
By: Eng Mohammed Hussein 56
<?php
setcookie("user", “Mohammed", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded
when sending the cookie, and automatically decoded when
received (to prevent URLencoding, use setrawcookie() instead).
Cookie Example 2
 In this example the expiration time is set to a month (60
sec * 60 min * 24 hours * 30 days).
By: Eng Mohammed Hussein 57
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
By: Eng Mohammed Hussein 58
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
In this example we use the isset()
function to find out if a cookie has
been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " .
$_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
How to Delete a Cookie?
 When deleting a cookie you should assure that the
expiration date is in the past.
By: Eng Mohammed Hussein 59
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
PHP Sessions
 A PHP session variable is used to store information about, or change
settings for a user session. Session variables hold information about one
single user, and are available to all pages in one application.
 PHP Session Variables
 When you are working 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
and what you do because the HTTP address doesn't maintain state.
 A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items, etc).
However, session information is temporary and will be deleted after the user
has left the website. If you need a permanent storage you may want to store
the data in a database.
By: Eng Mohammed Hussein 60
Starting a PHP Session
 Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
 Before you can store user information in your PHP session, you must first
start up the session.
By: Eng Mohammed Hussein 61
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code will register the user's session with the server, allow you to start
saving user information, and assign a UID for that user's session.
Storing a Session Variable
 The correct way to store and retrieve session variables is to
use the PHP $_SESSION variable:
By: Eng Mohammed Hussein 62
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Session example
 In the example below, we create a simple page-views
counter. The isset() function checks if the "views" variable
has already been set. If "views" has been set, we can
increment our counter. If "views" doesn't exist, we create a
"views" variable, and set it to 1:
By: Eng Mohammed Hussein 63
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
 If you wish to delete some session data, you can use the
unset() or the session_destroy() function.
 The unset() function is used to free the specified session
variable.
By: Eng Mohammed Hussein 64
<?php
unset($_SESSION['views']);
?>
<?php
session_destroy();
?>
You can also completely destroy the session by calling the
session_destroy() function.
Note: session_destroy() will reset your session and you will lose all
your stored session data.
PHP Sessions
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
<html>
<body>
<br>
<?php
echo "This is inside PHP<br>";
echo "Hello World!<br>";
$q= "How Are You Every Body?";
Echo $q;
?>
</body>
</html>
F5
Google Chrome
1
2
65By: Eng Mohammed Hussein
References
1) http://www.w3schools.com/php/php_ref_string.asp
2) http://www.w3schools.com/php/php_looping.asp
66By: Eng Mohammed Hussein

Weitere ähnliche Inhalte

Was ist angesagt? (20)

MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
POO - 22 - Tratamento de Exceções em Java
POO - 22 - Tratamento de Exceções em JavaPOO - 22 - Tratamento de Exceções em Java
POO - 22 - Tratamento de Exceções em Java
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP FormsPHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
 
Files in C
Files in CFiles in C
Files in C
 
Php famous built in functions
Php   famous built in functionsPhp   famous built in functions
Php famous built in functions
 
PHP.ppt
PHP.pptPHP.ppt
PHP.ppt
 
Operators php
Operators phpOperators php
Operators php
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Php
PhpPhp
Php
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
The World of PHP PSR Standards
The World of PHP PSR StandardsThe World of PHP PSR Standards
The World of PHP PSR Standards
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 

Andere mochten auch

String Manipulation in PHP
String Manipulation in PHPString Manipulation in PHP
String Manipulation in PHPSuraj Motee
 
Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasMongoDB
 
Character encoding standard(1)
Character encoding standard(1)Character encoding standard(1)
Character encoding standard(1)Pramila Selvaraj
 
Character Encoding issue with PHP
Character Encoding issue with PHPCharacter Encoding issue with PHP
Character Encoding issue with PHPRavi Raj
 
Slot marketing career path - as demonstrated by a band
Slot marketing career path - as demonstrated by a bandSlot marketing career path - as demonstrated by a band
Slot marketing career path - as demonstrated by a bandnluy
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPositive Hack Days
 
ADA programming language
ADA programming languageADA programming language
ADA programming languageAisha Kalsoom
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5julien pauli
 
How to choose right career path
How to choose right career pathHow to choose right career path
How to choose right career pathNisha Shetty
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advanceDhani Ahmad
 
Using XAMPP
Using XAMPPUsing XAMPP
Using XAMPPbutest
 
Install Word Press with xampp
Install Word Press with xamppInstall Word Press with xampp
Install Word Press with xamppMehdi Sharifirad
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Mohammed Hussein
 

Andere mochten auch (20)

String Manipulation in PHP
String Manipulation in PHPString Manipulation in PHP
String Manipulation in PHP
 
Php string
Php stringPhp string
Php string
 
Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible Schemas
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
Character encoding standard(1)
Character encoding standard(1)Character encoding standard(1)
Character encoding standard(1)
 
Character Encoding issue with PHP
Character Encoding issue with PHPCharacter Encoding issue with PHP
Character Encoding issue with PHP
 
Slot marketing career path - as demonstrated by a band
Slot marketing career path - as demonstrated by a bandSlot marketing career path - as demonstrated by a band
Slot marketing career path - as demonstrated by a band
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an Analysis
 
ADA programming language
ADA programming languageADA programming language
ADA programming language
 
PHP 7 performances from PHP 5
PHP 7 performances from PHP 5PHP 7 performances from PHP 5
PHP 7 performances from PHP 5
 
How to choose right career path
How to choose right career pathHow to choose right career path
How to choose right career path
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advance
 
Programming Languages
Programming LanguagesProgramming Languages
Programming Languages
 
Using XAMPP
Using XAMPPUsing XAMPP
Using XAMPP
 
Install Word Press with xampp
Install Word Press with xamppInstall Word Press with xampp
Install Word Press with xampp
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3
 
Lec3 Algott
Lec3 AlgottLec3 Algott
Lec3 Algott
 

Ähnlich wie PHP Guide for Beginners: Essential PHP Syntax, Functions & Concepts

Ähnlich wie PHP Guide for Beginners: Essential PHP Syntax, Functions & Concepts (20)

Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
PHP.docx
PHP.docxPHP.docx
PHP.docx
 
Introduction to PHP.ppt
Introduction to PHP.pptIntroduction to PHP.ppt
Introduction to PHP.ppt
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
PHP
PHPPHP
PHP
 
chapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdfchapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdf
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php Interview Questions
Php Interview QuestionsPhp Interview Questions
Php Interview Questions
 
Php
PhpPhp
Php
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php notes
Php notesPhp notes
Php notes
 
INTRODUCTION TO PHP.ppt
INTRODUCTION TO PHP.pptINTRODUCTION TO PHP.ppt
INTRODUCTION TO PHP.ppt
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Php unit i
Php unit iPhp unit i
Php unit i
 

Mehr von Mohammed Hussein

Mehr von Mohammed Hussein (11)

Comnet Network Simulation
Comnet Network SimulationComnet Network Simulation
Comnet Network Simulation
 
Multimedia lecture6
Multimedia lecture6Multimedia lecture6
Multimedia lecture6
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Multimedia Network
Multimedia NetworkMultimedia Network
Multimedia Network
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
 
Control system
Control systemControl system
Control system
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
 
Wireless lecture1
Wireless lecture1Wireless lecture1
Wireless lecture1
 
Algorithms Analysis
Algorithms Analysis Algorithms Analysis
Algorithms Analysis
 

Kürzlich hochgeladen

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Kürzlich hochgeladen (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

PHP Guide for Beginners: Essential PHP Syntax, Functions & Concepts

  • 1. 1
  • 2. Outline  History of PHP  PHP Introduction  Running XAMPP  Dreamweaver Site Setup  PHP file, PHP workings, running PHP.  Some useful PHP functions  Basic PHP syntax  variables, operators, if...else...and switch, for, while, do while, for, functions, Cookies and Sessions . By: Eng Mohammed Hussein 2
  • 3. History of PHP  PHP developed into full-featured, scripting language for server-side programming.  Rasmus Lerdorf has invented PHP/FI language (1994-1995) using Perl language.  PHP/FI has developed to PHP/FI2 using C language (1997).  PHP3 developed by (Rasmus Lerdorf, Zeev Suraski, Andi Gutmans) with support connect to Database (1998).  PHP4 emerged with more properties to PHP3 such as:  Object oriented , free, open-source  More support to database  Sessions  XML and JavaScript supported  …  PHP5  Current version 3By: Eng Mohammed Hussein
  • 4. PHP Introduction  What is PHP?  PHP stands for PHP: Hypertext Preprocessor.  PHP is a server-side scripting language, like ASP.  PHP scripts are executed on the server.  PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)  PHP is an open source software.  PHP is free to download and use.  PHP is similar to JavaScript, only on a server-side language.  PHP code is embedded in HTML using tags. 4By: Eng Mohammed Hussein
  • 5. PHP Introduction  What is a PHP File?  PHP files can contain text, HTML tags and scripts  PHP files are returned to the browser as plain HTML  PHP files have a file extension of ".php", ".php3", or ".phtml"  When a page was requested, the server recognizes PHP content via the file extension (.php).  The server executes the PHP code, and the PHP page results is showing to the client as HTML page.  the PHP code never appear to users, only the output in the HTML page. By: Eng Mohammed Hussein 5
  • 6. What is MySQL?  MySQL is a database server.  MySQL is ideal for both small and large applications.  MySQL supports standard SQL.  MySQL compiles on a number of platforms.  MySQL is free to download and use.  PHP + MySQL  PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform).  Why PHP?  PHP runs on different platforms (Windows, Linux, Unix, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP is FREE to download from the official PHP resource: www.php.net  PHP is easy to learn and runs efficiently on the server side 6By: Eng Mohammed Hussein
  • 7. Where to Start?  What do you Need?  If your server supports PHP you don't need to do anything.  Just create some .php files in your web directory, and the server will parse them for you. Because it is free, most web hosts offer PHP support.  However, if your server does not support PHP, you must install PHP.  Here is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php  To get access to a web server with PHP support, you can:  Install XAMPP Apache (or IIS) on your own server, install PHP, and MySQL  Or find a web hosting plan with PHP and MySQL support.  If you download and Install XAMPP Apache server, you will find PHP, and MySql already existed inside the XAMPP application. But if you want to install each one separately then follow these links:  Download PHP for free here: http://www.php.net/downloads.php  Download MySQL for free here: http://www.mysql.com/downloads/ 7By: Eng Mohammed Hussein
  • 8. Running XAMPP 8By: Eng Mohammed Hussein Just click on Admin then the default browser will appear.
  • 9. Security settings  Security console MySQL & XAMPP directory protection By: Eng Mohammed Hussein 9 http://localhost/security/xamppsecurity.php User: root password: root
  • 10. MySQL database  Use this link for accessing the MySQL database:  http://localhost/phpmyadmin/ By: Eng Mohammed Hussein 10
  • 11. Running PHP Examples  Write in the browser URL bar http://localhost  Put your site folder into this path :  C:xampphtdocsyour folder  Then in the browser URL, write your folder name after localhost as: http://localhost/your folder/  To run a.php file on local server, just add the name of the file as the following example:  http://localhost/php/a.php 11By: Eng Mohammed Hussein
  • 12. Dreamweaver –Site Setup  The pictures below will show you the steps that used to setup your site inside local server in order to run php files using Adobe Dreamweaver. 12By: Eng Mohammed Hussein
  • 13. Dreamweaver -Site 13By: Eng Mohammed Hussein
  • 14. Dreamweaver -Servers 14By: Eng Mohammed Hussein Here, how to add, delete and edit the servers information
  • 15. Dreamweaver -Servers 15By: Eng Mohammed Hussein
  • 16. Dreamweaver -Servers 16By: Eng Mohammed Hussein
  • 17. PHP Syntax  PHP code is executed on the server, and the plain HTML result is sent to the browser.  Basic PHP Syntax  A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.  On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.  For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. <?php ?> 17By: Eng Mohammed Hussein Example 1
  • 18. PHP Syntax  A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.  We have an example of a simple PHP script which sends the text "Hello World" to the browser.  Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.  There are two basic statements to output text with PHP: echo and print. In the example we have used the echo statement to output the text "Hello World".  Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed. <html> <body> <?php echo "Hello World"; ?> </body> </html> 18By: Eng Mohammed Hussein
  • 19. Comments in PHP  In PHP, we use // to make a single-line comment  or /* and */ to make a large comment block. <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html> 19By: Eng Mohammed Hussein
  • 20. PHP Variables  A variable is used to store information.  Variables in PHP  Variables are used for storing values, like text strings, numbers or arrays.  When a variable is declared, it can be used over and over again in your script.  All variables in PHP start with a $ sign symbol.  The correct way of declaring a variable in PHP $var_name = value; 20By: Eng Mohammed Hussein
  • 21. PHP Variables  New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.  Let's try creating a variable containing a string, and a variable containing a number: <?php $txt="Hello World!"; $x=16; echo $txt; echo "<br>"; echo $x; ?> 21By: Eng Mohammed Hussein
  • 22. PHP is a Loosely Typed Language  In PHP, a variable does not need to be declared before adding a value to it. In the previous slide example , you have seen that you do not have to tell PHP which data type the variable is ? . PHP automatically converts the variable to the correct data type, depending on its value.  In an other programming language, you have to declare (define) the type and name of the variable before using it. In PHP, the variable is declared automatically when you use it.  Rules for Variables  A variable name must start with a letter or an underscore "_"  A variable name can only contain alpha-numeric characters and underscores (a- z, A-Z, 0-9, and _ )  A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) 22By: Eng Mohammed Hussein
  • 23. PHP String Variables A string variable is used to store and manipulate text.  String Variables in PHP  String variables are used for values that contain characters.  In this slide we are going to look at the most common functions and operators used to manipulate strings in PHP.  After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable.  Below, the PHP script assigns the text "Hello World" to a string variable called $txt. <?php $r = “This is”BAD”; // ‫خطأ‬ $t = "This is „good"; // ‫صحيح‬ ?> <?php $txt="Hello World"; echo $txt; ?> 23By: Eng Mohammed Hussein
  • 24. The Concatenation Operator  There is only one string operator in PHP.  The concatenation operator (.) is used to put two string values together.  To concatenate two string variables together, use the concatenation operator <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings. 24By: Eng Mohammed Hussein
  • 25. PHP String functions  The strlen() function  The strlen() function is used to return the length of a string.  Let's find the length of a string: <?php echo strlen("Hello world!"); ?> The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string). 25By: Eng Mohammed Hussein
  • 26. PHP String functions  The strpos() function  The strpos() function is used to search for a character/text within a string.  If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE.  Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1. 26By: Eng Mohammed Hussein
  • 27. Complete PHP String Reference Functions Description PHP echo() Outputs strings 3 chr() Returns a character from a specified ASCII value 3 fprintf() Writes a formatted string to a specified output stream 5 substr_compare() Compares two strings from a specified start position (binary safe and optionally case-sensitive) 5 strip_tags() Strips HTML and PHP tags from a string 3 str_split() Splits a string into an array 5 print() Outputs a string 3 ord() Returns the ASCII value of the first character of a string 3 number_format() Formats a number with grouped thousands 3 htmlspecialchars_ decode() Converts some predefined HTML entities to characters 5 ereg_replace() filter everything but numbers and used for security 27By: Eng Mohammed Hussein
  • 28. PHP Operators  Operators are used to operate on values. Operator Description Example Result + Addition x=2  x+2 4 - Subtraction x=2  5-x 3 * Multiplication x=4  x*5 20 / Division 15/5 , 5/2 3 , 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5  x++ x=6 -- Decrement x=5  x-- x=4 28By: Eng Mohammed Hussein
  • 29. PHP-Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= x%=y x=x%y 29By: Eng Mohammed Hussein
  • 30. PHP-Comparison Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true <> is not equal 5<>8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true 30By: Eng Mohammed Hussein
  • 31. PHP-Logical Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true 31By: Eng Mohammed Hussein
  • 32. PHP If...Else Statements  Conditional statements are used to perform different actions based on different conditions.  Conditional Statements  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 - use this statement to execute some code only if a specified condition is true  if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false  if...elseif....else statement - use this statement to select one of several blocks of code to be executed  switch statement - use this statement to select one of many blocks of code to be executed 32By: Eng Mohammed Hussein
  • 33. The if Statement  Use the if statement to execute some code only if a specified condition is true. <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> 33By: Eng Mohammed Hussein
  • 34. The if...else Statement  Use the if....else statement to execute some code if a condition is true and another code if a condition is false.  if a condition is true/false, the output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> 34By: Eng Mohammed Hussein
  • 35. The if...elseif....else Statement The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> 35By: Eng Mohammed Hussein
  • 36. PHP Switch Statement  Conditional statements are used to perform different actions based on different conditions.  Use the switch statement to select one of many blocks of code to be executed. <html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html> 36By: Eng Mohammed Hussein
  • 37. PHP - For Loops  For Loops  Loops execute a block of code a specified number of times, or while a specified condition is true.  The for loop is used when you know in advance how many times the script should run.  The foreach Loop  The foreach loop is used to loop through arrays. By: Eng Mohammed Hussein 37 <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?>
  • 38. PHP – while  The while Loop  The while loop executes a block of code while a condition is true.  The do...while Loop  The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> By: Eng Mohammed Hussein 38
  • 39. PHP Arrays  An array stores multiple values in one single variable.  A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.  An array is a special variable, which can store multiple values in one single variable.  In PHP, there are three kind of arrays:  Numeric array - An array with a numeric index  Associative array - An array where each ID key is associated with a value  Multidimensional array - An array containing one or more arrays 39By: Eng Mohammed Hussein
  • 40. PHP- Numeric Arrays  A numeric array stores each array element with a numeric index.  There are two methods to create a numeric array. <?php $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?> <?php $cars=array("Saab","Volvo","BMW","Toyota"); echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?> 1. In the example the index are automatically assigned (the index starts at 0): 2. In the example we assign the index manually: 40By: Eng Mohammed Hussein
  • 41. Associative Arrays  An associative array, each ID key is associated with a value.  When storing data about specific named values, a numerical array is not always the best way to do it.  With associative arrays we can use the values as keys and assign values to them. $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> Example 1 Example 2 41By: Eng Mohammed Hussein
  • 42. Multidimensional Arrays  In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. $families = array ( "Griffin"=>array ( "Peter“, "Lois“, "Megan“ ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) ); echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; Example 2Example 1 42By: Eng Mohammed Hussein
  • 43. PHP Include File  Server Side Includes (SSI)  You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.  The two functions are identical in every way, except how they handle errors:  include() generates a warning, but the script will continue execution  require() generates a fatal error, and the script will stop  These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.  Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages). By: Eng Mohammed Hussein 43
  • 44. PHP include() Function  The include() function takes all the content in a specified file and includes it in the current file.  If an error occurs, the include() function generates a warning, but the script will continue execution. By: Eng Mohammed Hussein 44 <html> <body> <? php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html> <a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/about.php">About Us</a> <a href="/contact.php">Contact Us</a> <div class="leftmenu"> <?php include("menu.php"); ?> </div>
  • 45. PHP require() Function  The require() function is identical to include(), except that it handles errors differently.  If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop. By: Eng Mohammed Hussein 45 <html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body> </html> Error Example include() Function Error Example require() Function <html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html>
  • 46. PHP Functions  In PHP, there are more than 700 built-in functions.  A function will be executed by a call to the function.  You may call a function from anywhere within a page. By: Eng Mohammed Hussein 46 <html> <body> <?php function writeName() { echo “Mohammed Hussein"; } echo "My name is "; writeName(); ?> </body> </html>
  • 47. PHP Function examples By: Eng Mohammed Hussein 47 <html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> PHP Functions - Return values <html> <body> <?php function writeName($fname,$punctuation) { echo $fname . " Hussein" . $punctuation . "<br />"; } echo "My name is "; writeName(“Mohammed","."); echo "My Son's name is "; writeName(“Abdulkareem M","!"); echo "My brother's name is "; writeName(“Ali","?"); ?> </body> </html> PHP Functions - Adding parameters
  • 48. PHP Forms and User Input  The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.  The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. By: Eng Mohammed Hussein 48 <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
  • 49. PHP Forms on submit button  When a user fills out the form and click on the submit button, the form data is sent to a PHP file, called "welcome.php": By: Eng Mohammed Hussein 49 <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
  • 50. PHP $_GET  In PHP, the predefined $_GET variable is used to collect values in a form with method="get".  Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. By: Eng Mohammed Hussein 50 <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://localhost/php/ welcome.php?fname=Peter&age=37
  • 51. PHP $_GET  The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array): By: Eng Mohammed Hussein 51 Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.
  • 52. PHP $_POST  In PHP, the predefined $_POST variable is used to collect values in a form with method="post".  Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.  Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file). By: Eng Mohammed Hussein 52 <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>
  • 53. PHP $_POST  When the user clicks the "Submit" button, the URL will look like this:  The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array): By: Eng Mohammed Hussein 53 http://localhost/php/ welcome.php Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old.
  • 54. PHP $_POST  When to use method="post"?  Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.  However, because the variables are not displayed in the URL, it is not possible to bookmark the page.  The PHP $_REQUEST Variable  The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.  The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. By: Eng Mohammed Hussein 54 Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.
  • 55. 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.  How to Create a Cookie?  The setcookie() function is used to set a cookie.  Note: The setcookie() function must appear BEFORE the <html> tag. By: Eng Mohammed Hussein 55 setcookie(name, value, expire, path, domain);Syntax:
  • 56. Cookie Example 1  In the example below, we will create a cookie named "user" and assign the value “Mohammed" to it. We also specify that the cookie should expire after one hour: By: Eng Mohammed Hussein 56 <?php setcookie("user", “Mohammed", time()+3600); ?> <html> ..... Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
  • 57. Cookie Example 2  In this example the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days). By: Eng Mohammed Hussein 57 <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> .....
  • 58. How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. By: Eng Mohammed Hussein 58 <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> In this example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>
  • 59. How to Delete a Cookie?  When deleting a cookie you should assure that the expiration date is in the past. By: Eng Mohammed Hussein 59 <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
  • 60. PHP Sessions  A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.  PHP Session Variables  When you are working 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 and what you do because the HTTP address doesn't maintain state.  A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. By: Eng Mohammed Hussein 60
  • 61. Starting a PHP Session  Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.  Before you can store user information in your PHP session, you must first start up the session. By: Eng Mohammed Hussein 61 <?php session_start(); ?> <html> <body> </body> </html> The code will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.
  • 62. Storing a Session Variable  The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: By: Eng Mohammed Hussein 62 <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
  • 63. Session example  In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: By: Eng Mohammed Hussein 63 <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
  • 64. Destroying a Session  If you wish to delete some session data, you can use the unset() or the session_destroy() function.  The unset() function is used to free the specified session variable. By: Eng Mohammed Hussein 64 <?php unset($_SESSION['views']); ?> <?php session_destroy(); ?> You can also completely destroy the session by calling the session_destroy() function. Note: session_destroy() will reset your session and you will lose all your stored session data.
  • 65. PHP Sessions <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> <html> <body> <br> <?php echo "This is inside PHP<br>"; echo "Hello World!<br>"; $q= "How Are You Every Body?"; Echo $q; ?> </body> </html> F5 Google Chrome 1 2 65By: Eng Mohammed Hussein