Documente Academic
Documente Profesional
Documente Cultură
PHP5
What is PHP?
When someone visits your PHP webpage, your web server processes the
PHP code. It then sees which parts it needs to show to visitors(content
and pictures) and hides the other stuff(file operations, math calculations,
etc.) then translates your PHP into HTML. After the translation into
HTML, it sends the webpage to your visitor's web browser.
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 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 be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
Where to Start?
Install Apache (or IIS) on your own server, install PHP, and MySQL
Or install wampserver.
Or find a web hosting plan with PHP and MySQL support
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
?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP
scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to
the browser:
<html>
<body>
<?php
echo "Hello World ";
?>
</body>
</html>
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
above 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.
Comments in PHP
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html> -
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Variables in PHP
Variables are used for storing a values, like text strings, numbers or
arrays.
$var_name = value;
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;
?>
In the example below, only the first statement will display the value of
the $color variable (this is because $color, $COLOR, and $coLOR are
treated as three different variables):
<!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>
In PHP, a variable does not need to be declared before adding a value to it.
In the example above, you see 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 a strongly typed programming language, you have to declare (define) the type and
name of the variable before using it.
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
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:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
PHP - Echo
As you saw in the above examples, the PHP command echo is a means of outputting text
to the web browser. Throughout your PHP career you will be using the echo command
more than any other.
Outputting a String
You can place either a string variable or you can use quotes, like we do below, to create a
string that the echo function will output.
PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>
Display:
Hello!
In the above example we output "Hello!" without a hitch. The text we are outputting is
being sent to the user in the form of a web page, so it is important that we use proper
HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To
do this we simply put the <h5> at the beginning of the string and closed it at the end of
the string. Just because you're using PHP to make web pages does not mean you can
forget about HTML syntax!
It is pretty cool that you can output HTML with PHP. However, you must be careful
when using HTML code or any other string that includes quotes! Echo uses quotes to
define the beginning and end of the string, so you must use one of the following tactics if
your string contains quotations:
See our example below for the right and wrong use of echo:
PHP Code:
<?php
// This won't work because of the quotes around
specialH5!
echo "<h5 class="specialH5">I love using PHP!
</h5>";
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or
escape the quotations by placing a backslash in front of it ( \" ). The backslash will tell
PHP that you want the quotation to be used within the string and NOT to be used to end
echo's string.
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the
common task of echoing all variables nearly foolproof! No quotations are required, even
if the variable does not hold a string. Below is the correct format for echoing a variable.
PHP Code:
<?php
$my_string = "Hello Mr. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Mr. My name is: 4a
PHP Code:
<?php
$my_string = "Hello Amit. My name is: ";
echo "$my_string Sachin <br />";
echo "Hi, I'm Amit. Who are you? $my_string <br />";
echo "Hi, I'm Amit. Who are you? $my_string Sachin";
?>
Display:
Hello Amit. My name is: Sachin
Hi, I'm Amit. Who are you? Hello Amit. My name is:
Hi, I'm Amit. Who are you? Hello Amit. My name is: Sachin
By placing variables inside a string you can save yourself some time and make your code
easier to read, though it does take some getting used to. Remember to use double-quotes,
single-quotes will not grab the value of the string. Single-quotes will just output the
variable name to the string, like )$my_string), rather than (Hello Amit. My name is: ).
PHP Operators
Arithmetic Operators
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division 5%2 1
remainder) 10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment Operators
Comparison Operators
Logical Operators
y=3
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions.
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code
only if the specified condition is true.
Use the if....else statement to execute some code if a condition is true and another code if
a condition is false.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will 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>
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
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>
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;
default:
code to be executed if n is different from both label1 and
label2;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Example
<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>
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 lines in a script we can use loops to
perform a task like this.
Syntax
while (condition)
{
code to be executed;
}
Example
The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
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.
Syntax
do
{
code to be executed;
Prepared By: Mahesh Manchanda Department of CS & IT 18
Graphic Era Hill University, Dehradun
}
while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and
write some output. Then the condition is checked, and the loop will continue to run as
long as i is less than, or equal to 5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:
Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Syntax
foreach ($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) - so on the next loop iteration, you'll be looking at the
next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two",3);
foreach ($x as $value)
{
echo $value . "<br />";
}
?>
</body>
</html>
Output:
One
two
three
PHP ARRAY
There are three different kind of arrays and each array value is accessed
using an ID c which is called array index.
$list = array( );
First you type out what you want your array to be called ($list, in the array above) and,
after an equals sign, you type this:
array( );
So setting up an array just involves typing the word array followed by a pair of round
brackets. This is enough to tell PHP that you want to set up the array. But there's nothing
in the array yet. All we're doing with our line of code is telling PHP to set up an array,
and give it the name $list.
You can use two basic methods to put something into an array.
The first method involves typing your values between the round brackets of array(). In
the code below, we're setting up an array to hold the seasons of the year:
Arrays work by having a position, and some data for that position. In the above array,
"Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and
"Summer" is in position 3.
The first position is always zero, unless you tell PHP otherwise. But the position is know
as a Key. The Key then has a value attached to it. You can specify your own numbers for
the Keys. If so, you do it like this:
Because no keys were specified, PHP will set your array up like this:
0=> 10,
1=> 20,
2=> 30,
3=> 40
Here's the same array again, only this time we're specifying our own key:
$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
This array will then look like this:
1=> 10,
2=> 20,
3=> 30,
4=> 40
So the key name is typed before the => symbol, and the data stored under this key is to
the right.
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
$seasons = array();
$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";
Here, the array is first set up with $seasons = array();. This tells PHP that you want to
create an array with the name of $seasons. To store values in the array you first type the
name of the array, followed by a pair of square brackets:
$seasons[ ]
After the equals sign, you type out what you want to store in this position. Because no
numbers were typed in between the square brackets, PHP will assign the number 0 as the
first key:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
This is exactly the same as the array you saw earlier. If you want different numbers for
your keys, then simply type them between the square brackets:
$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so
that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative
array, and the value would be their respective salary.
NOTE: Don't keep associative array inside double quote while printing otheriwse it
would not return any value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"Ayush" => 20000,
"Amit" => 10000,
"Sachin" => 5000
);
Multidimensional Arrays
A multi-dimensional 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. Values in the multi-dimensional array are accessed using
multiple index.
$matrix = array(
array(5,5,5,5,),
array(6,6,6,6),
array(7,7,7,7)
)
Example
In this example we create a two dimensional array to store marks of three students in
three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"Ayush" => array("physics" => 35,"maths" => 30,
35 39
Ayush
30
30 29
Amit 32
31 39
Sachin 22
PHP Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and
returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call
them according to your requirement.
Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice
time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the variable
name in either the function call or the function definition.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
Original Value is 15
Original Value is 21
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from
a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
This is test
It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself. Following example
depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Hello
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.
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action="http://localhost/CS/welcome.php"
method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent
to a PHP file, called "welcome.php":
<html>
<body>
</body>
</html>
Welcome John!
You are 28 years old.
Form Validation
User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A
good way to validate a form on the server is to post the form to itself, instead of jumping
to a different page. The user will then get the error messages on the same page as the
form. This makes it easier to discover the error.
PHP $_GET
The built-in $_GET function is used to collect values in a form with method="get".
The built-in $_GET function is used to collect values from a form sent 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 (max. 200 characters).
Example
<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/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET function to collect form data (the names
of the form fields will automatically be the keys in the $_GET array):
Both GET and POST create an array (e.g. array( key => value, 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 superglobals, 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.
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 large variable values; the value cannot exceed
200 characters.
The built-in $_POST function is used to collect values in a form with method="post".
The built-in $_POST function is used to collect values from a form sent 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).
Example
<form action="welcome.php" method="post">
When the user clicks the "Submit" button, the URL will look like this:
http://localhost/GEHU/welcome.php
The "welcome.php" file can now use the $_POST function to collect
form data (the names of the form fields will automatically be the keys
in the $_POST array):
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 built-in $_REQUEST function contains the contents of both $_GET, $_POST,
and $_COOKIE.
The $_REQUEST function can be used to collect form data sent with both the GET and
POST methods.
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
First we will look at the plain HTML code for the form:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
Prepared By: Mahesh Manchanda Department of CS & IT 39
Graphic Era Hill University, Dehradun
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
When the form is submitted, the form data is sent with method="post".
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] sends the 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.
If PHP_SELF is used in your page then a user can enter a slash (/) and
then some Cross Site Scripting (XSS) commands to execute.
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.
Now, if a user enters the normal URL in the address bar like
"http://localhost/test_form.php", the above code will be translated
to:
However, consider that a user enters the following URL in the address bar:
http://localhost/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>
This code adds a script tag and an alert command. And when the page loads, the
JavaScript code will be executed (the user will see an alert box). This is just a simple and
harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker
can redirect the user to a file on another server, and that file can hold malicious code that
can alter the global variables or submit the form to another address to save the user data,
for example.
<script>location.href('http://www.hacked.com')</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/"><script>alert('hacked')</script>">
The first thing we will do is to pass all variables through PHP's htmlspecialchars()
function.
When we use the htmlspecialchars() function; then if a user tries to submit the following
in a text field:
<script>location.href('http://www.hacked.com')</script>
this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data
(with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)
The next step is to create a function that will do all the checking for us (which is much
more convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and the script
looks like this:
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
In the abovecode we have added some new variables: $nameErr, $emailErr, $genderErr,
and $websiteErr. These error variables will hold error messages for the required fields.
We have also added an if else statement for each $_POST variable. This checks if the
$_POST variable is empty (with the PHP empty() function). If it is empty, an error
message is stored in the different error variables, and if it is not empty, it sends the user
input data through the test_input() function:
Then in the HTML form, we add a little script after each required field, which generates
the correct error message if needed (that is if the user tries to submit the form without
filling out the required fields):
</form>
The next step is to validate the input data, that is "Does the Name field contain only
letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".
Validate Name
The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.
Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to use
PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then
store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
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:
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).
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.
Example 1
Assume that you have a standard header file, called "header.php". To include the header
file in a page, use the include() function:
<html>
<body>
<?php
include("menu.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
Prepared By: Mahesh Manchanda Department of CS & IT 47
Graphic Era Hill University, Dehradun
</html>
Example 2
Assume we have a standard menu file, called "menu.php", that should be used on all
pages:
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
All pages in the Web site should include this menu file. Here is how it
can be done:
<html>
<body>
</body>
</html>
If you look at the source code of the page above (in a browser), it will
look like this:
<html>
<body>
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
</body>
</html>
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.
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Hello World!
Notice that the echo statement is executed! This is because a Warning does not stop the
script execution.
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
The echo statement is not executed, because the script execution stopped after the fatal
error.
PHP STRING
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their
values.
To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
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.
Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.
<?php
echo strlen("Hello world!");
?>
12
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)
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If
no match is found, it will return FALSE.
<?php
echo strpos("Hello world!","world");
?>
As you see the position of the string "world" in our string is position 6. The reason that it
is 6, and not 7, is that the first position in the string is 0, and not 1.
chr
$ascii = 65
echo chr ( $ascii )
OUTPUT
A
$string = “A”
Echo ord ( string $string )
OUTPUT
65
ltrim — Strip whitespace (or other characters) from the beginning of a string
rtrim — Strip whitespace (or other characters) from the end of a string
str_replace — Replace all occurrences of the search string with the replacement string
string
trim — Strip whitespace (or other characters) from the beginning and end of a string
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
Format Required. Specifies the format of the timestamp
Timestamp Optional. Specifies a timestamp. Default is the current date and time
The required format parameter in the date() function specifies how to format the
date/time.
A list of all the characters that can be used in the format parameter is listed below:
Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:
<?php
echo date("Y/m/d", ) . "<br />";
2014/05/12
2014.05.12
2014-05-12
The optional timestamp parameter in the date() function specifies a timestamp. If you do
not specify a timestamp, the current date and time will be used.
The Unix timestamp contains the number of seconds between the Unix time (January 1
1970 00:00:00 GMT) and the time specified.
To go one day in the future we simply add one to the day argument of mktime():
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
Tomorrow is 20014/6/05
Dates are so much part of everyday life that it becomes easy to work with them without
thinking. PHP also provides powerful tools for date arithmetic that make manipulating
dates easy.
PHP's time() function gives you all the information that you need about the current date
and time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight
GMT on January 1, 1970. This moment is known as the UNIX time, and the number of
seconds that have elapsed since then is referred to as a time stamp.
<?php
//print time();
Echo time();
?>
948316201
This is something difficult to understand. But PHP offers excellent tools to convert a time
stamp into a form that humans are comfortable with.
0 Timestamp 948370048
Now you have complete control over date and time. You can format this date and time in
whatever format you want.
Example:
<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
print "$key = $val<br />";
}
$formated_date = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];
print $formated_date;
?>
seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007
The date() function returns a formatted string representing a date. You can exercise an
enormous amount of control over the format that date() returns with a string argument
that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if omitted then current date and time will be
used. Any other data you include in the format string passed to date() will be included in
the return value.
Following table lists the codes that a format string can contain:
I Minutes ( 0 - 59 ) 23
S Seconds of hour 20
Example:
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \t g.i a", time());
?>
05/12/14 16.27:55
Today is 12 of May 2014, 4.27 pm
PHP Superglobals
Variable Description
An associative array of items uploaded to the current script via the HTTP
$_FILES
POST method.
Variable Description
ADVANCE PHP
In your "php.ini" file, search for the file_uploads directive, and set it to
On:
file_uploads = On
To allow users to upload files from a form can be very useful. Look at the following
HTML form for uploading files:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
By using the global PHP $_FILES array you can upload files from a client computer
to the remote server.
The first parameter is the form's input name and the second index can be either
"name", "type", "size", "tmp_name" or "error". Like this:
Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.
First, we will check if the file already exists in the "uploads" folder. If it does, an error
message is displayed, and $uploadOk is set to 0:
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500kb, an error
message is displayed, and $uploadOk is set to 0:
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other
file types gives an error message before setting $uploadOk to 0:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
The examples above create a temporary copy of the uploaded files in the PHP temp folder
on the server.
The temporary copied files disappears when the script ends. To store the uploaded file we
need to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg"))
&& ($_FILES["file"]["size"] < 20000))
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("c:/wamp/www/CS/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The script above checks if the file already exists, if it does not, it copies the file to the
specified folder.
Note: This example saves the file to a new folder called "upload"
PHP Cookies
A cookie is often used to identify a user.
What is a Cookie?
PHP provided setcookie() function to set a cookie. This function requires upto
six arguments and should be called before <html> tag. For each cookie this function has
to be called separately.
Syntax
setcookie(name, value, expire, path, domain, secure, httponl
y)
Parameters
Which type
Parameter Description
of data
name Name of the cookie. String
value Value of the cookie, stored in clients computer. String
Unix timestamp, i.e. number of seconds since January 1st, 1970
expire Integer
(called as Unix Epoch).
path Server path in which the cookie will be available. String
domain To which domain the cookie is available. String
secure If set true, the cookie is available over secure connection only. Boolean
If set true, the cookie is available over HTTP protocol only.
httponly Scripting languages like JavaScript won't be able to access the
cookie.
Example 1 Cookie
<?php
$username = 'Ankit';
setcookie('userid', $username);
?>
In the example above, we will create a cookie named "userid" and assign the value
"Ankit" to it.
As this cookie does not have an expiry time, then the cookie will be deleted once the user
closes their browser. This can be very useful for keeping a user logged in for an indefinite
amount of time, however, as soon as they close their browser (hence, have left the site),
the cookie is removed.
There are two very important things to abide by when using cookies. Firstly, there are
can be no HTML, text or white-space output before calling the setcookie() function. This
is due to a 'protocol restriction' and you will find that header() and session_start()
functions must also follow this rule.
Note: The value of the cookie is automatically URLencoded when sending the cookie,
and automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
Note: The setcookie() function must appear BEFORE the <html> tag.
?>
This code uses the $_COOKIE superglobal to access any cookies set in the current
domain. If we were to run this script, it would output Ankit
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["userid"]))
echo "Page Visited" . $_COOKIE["userid"] +1 ;
else
Prepared By: Mahesh Manchanda Department of CS & IT 70
Graphic Era Hill University, Dehradun
</html>
You can also set the expiration time of the cookie in another way. It may be easier than
using seconds.
Example 2
<?php
$expire=time()+60*60*24*30;
setcookie("userid", "Ankit", $expire);
?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours *
30 days).
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("userid", "ankit", time()-3600);
?>
User Logon
To give a more detailed look into how to use cookies, I am going to show you how to
create a little login form so that you can store the username and password in a cookie.
We will use more complicated cookies now so that you can learn the full use of
setcookie().
Login.html
<html>
<head>
<title>User Logon</title>
</head>
<body>
<h2>User Login </h2>
<form name="login" method="post"
action="http://localhost/cs/login.php">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
Remember Me: <input type="checkbox" name="rememberme"
value="1"><br>
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>
Output
Now that we have our form, we will create our login script. We must decide what
restrictions we are going to place on the cookie.
I have decided that this will only run on the www.example.com domain and in the
/account directory only. Hence,
Login.php
<?php
/* These are our valid username and passwords */
$user = 'Ankit';
$pass = 'Ankit123';
if (isset($_POST['username']) && isset($_POST['password'))
{
if (($_POST['username'] == $user) && ($_POST['password'] == $pass))
{
if (isset($_POST['rememberme']))
{
/* Set cookie to last 1 year */
setcookie('username', $_POST['username'], time()+60*60*24*365, '/account', '
www.example.com');
setcookie('password', md5($_POST['password']), time()+60*60*24*365,
'/account', 'www.example.com');
}
else
{
/* Cookie expires when browser closes *
setcookie('username', $_POST['username'], false, '/account',
'www.example.com');
setcookie('password', md5($_POST['password']), false, '/account',
'www.example.com');
}
header('Location: index.php');
}
else
{
echo 'Username/Password Invalid';
}
}
else
{
echo 'You must supply a username and password.';
}
?>
?>
Explanations:
In this script, we just check that the cookie exists and is valid. If they aren't, then the
user is redirected back to the login form.
Otherwise a welcome message is included. The only important thing to notice is how we
have validated the password. Before on the login.php script, we have encrypted our
password using md5() and as this encryption cannot be undone,
we must compare encrypted versions. Hence, we encrypt our preset value and compare
it to the already hashed cookie value. This way, there is no chance of the original
password becoming available.
PHP Sessions
PHP first creates a unique identifier for that particular session which is a random string
of 32 hexadecimal numbers such.
A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
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.
A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP
automatically gets the unique session identifier string from the PHPSESSID cookie and
then looks in its temporary directory for the file bearing that name and a validation can
be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes
duration.
one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables
can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is
incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
Prepared By: Mahesh Manchanda Department of CS & IT 76
Graphic Era Hill University, Dehradun
A PHP session can be destroyed by session_destroy() function. This function does not
need any argument and a single call can destroy all the session variables. If you want to
destroy a single session variable then you can use unset() function to unset a session
variable.
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
session_destroy();
?>
By default, session variables last until the user closes the browser.
Session variables hold information about one single user, and are available to all
pages in one application.
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.
The PHP mail() function is used to send emails from inside a script.
Syntax
mail(to,subject,message,headers,parameters)
Parameter Description
To Required. Spe1cifies the receiver / receivers of the email
Subject Required. Specifies the subject of the email. Note: This parameter
cannot contain any newline characters
Message Required. Defines the message to be sent. Each line should be separated
with a LF (\n). Lines should not exceed 70 characters
Headers Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n)
Parameters Optional. Specifies an additional parameter to the sendmail program
Note: For the mail functions to be available, PHP requires an installed and working email
system. The program to be used is defined by the configuration settings in the php.ini file.
The simplest way to send an email with PHP is to send a text email.
In the example below we first declare the variables ($to, $subject, $message, $from,
$headers), then we use the variables in the mail() function to send an e-mail:
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
With PHP, you can create a feedback-form on your website. The example below sends a
text message to a specified e-mail address:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>