0% found this document useful (0 votes)
9 views

IP - Chapter Two P2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

IP - Chapter Two P2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

St.

Mary’s University
Faculty of Informatics
Part 2
PHP 5 Functions

There are more than 1000 built in functions.


PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a
program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
PHP 5 Functions…
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as
you want, just separate them with a comma.
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Default Argument Value
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values

To let a function return a value, use the return statement


Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Arrays
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like
this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
7
Arrays…
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements)
of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?> 8
PHP 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.
 NOTE − Don't keep associative array inside double
quote while printing otherwise it would not return any
value
PHP Associative Arrays

There are two ways to create an associative array:


$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach
loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; 10
}
PHP 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.
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.
<?php
$marks = array(
"mohammad" => array ( "physics" => 55, "maths" => 60, "chemistry" => 59 ),
“Tolosa" => array ( "physics" => 45, "maths" => 62, "chemistry" => 49),
“Saron" => array ( "physics" => 42, "maths" => 72, "chemistry" => 66 ) );

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for Tolosa in maths : ";


echo $marks[‘Tolosa']['maths'] . "<br />";

echo "Marks for Saron in chemistry : " ;


echo $marks[‘Saron']['chemistry'] . "<br />";
?>
Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending


or ascending.
PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort()
The following example sorts the elements of the $cars array in ascending alphabetical
order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
13
?>
The following example sorts the elements of the $numbers array in
ascending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
14
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>

Sort Array in Ascending Order, According to Value - asort()


The following example sorts an associative array in ascending order, according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Sort Array in Ascending Order, According to Key - ksort()

The following example sorts an associative array in ascending order,


according to the key:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Sort Array in Descending Order, According to Value - arsort()


The following example sorts an associative array in descending order,
according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Sort Array in Descending Order, According to Key - krsort()

The following example sorts an associative array in descending order,


according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
• Using array() construct:
$products = array( array( “TIR”, “Tires”, 100 ),
array( “OIL”, “Oil”, 10 ),
array( “SPK”, “Spark Plugs”, 4 ) );
• Using assigning values:
• $product[0][0] = “TIR”;
• $product[0][1] = “Tires”;
• $product[0][2] = “100”;
• $product[1][0] = “OIL”;
• $product[1][1] = “Oil”;
• $product[1][2] = “10”;
• $product[0][0] = “SPK”;
• $product[0][1] = “Spark Plugs”; 18
PHP array_search() Function

Example
Search an array for the value "red" and return its key:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Definition and Usage
The array_search() function search an array for a value and returns the key .
Syntax
arrary_search(value, array, strict)
Parameter Description
value Required. Specifies the value to search for
array Required. Specifies the array to search in
strict •Optional. If this parameter is set to TRUE, then
this function will search for identical elements in
the array. Possible values:true
•false - Default
When set to true, the number 5 is not the same 19
PHP array_search() Function

More Examples
Example 1
Search an array for the value 5 and return its key (notice the ""):
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>

20
PHP 5 Global Variables - Superglobals

Several predefined variables in PHP 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.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP $GLOBALS
is used to access global variables from anywhere in the PHP script (also from within
functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.

21
PHP $GLOBALS

Example
<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.

22
PHP $_REQUEST

PHP $_REQUEST is used to collect data after submitting an HTML form.


Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

23
PHP $_POST

PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>
24
PHP $_GET

PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>

<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>

When a user clicks on the link "Test $GET", the parameters "subject" and "web" is
sent to "test_get.php", and you can then acces their values in "test_get.php" with
$_GET.
The example below shows the code in "test_get.php":
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html> 25
PHP 5 Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a
submit button:
Example
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php".
The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
The same result could also be achieved using the HTTP GET method:
Example

<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
PHP 5 Form Validation
• PHP Form Validation Example
• * required field.
• Name: * Name is required

E-mail: * Email is required

Website:

Comment:

Gender: Female Male * Gender is required

submit
The validation rules for the form above are as follows:
Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @ and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one

Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
The Form Element
The HTML code of the form looks like this:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".
What is the $_SERVER["PHP_SELF"] variable?

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.
What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities


PHP - Required Fields
From the validation rules table on the previous page, we see that the "Name", "E-
mail", and "Gender" fields are required. These fields cannot be empty and must
be filled out in the HTML form.
In the following code 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:

<!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"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

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;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?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>
<!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 (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)
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;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
PHP 5 Date and Time

The PHP date() function is used to format a date and/or a time.


The PHP Date() Function
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
PHP 5 Date and Time…
Get a Simple Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
• d - Represents the day of the month (01 to 31)
• m - Represents a month (01 to 12)
• Y - Represents a year (in four digits)
• l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
The example below formats today's date in three different ways:
Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

</body>
</html>
PHP 5 Date and Time…
PHP Tip - Automatic Copyright Year
• Use the date() function to automatically update the copyright year on your
website:
Example
<!DOCTYPE html>
<html>
<body>

© 2010-<?php echo date("Y")?>


</body>
</html>

Get a Simple Time


• Here are some characters that are commonly used for times:
• h - 12-hour format of an hour with leading zeros (01 to 12)
• i - Minutes with leading zeros (00 to 59)
• s - Seconds with leading zeros (00 to 59)
• a - Lowercase Ante meridiem and Post meridiem (am or pm)
• The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
PHP 5 Date and Time…

Get Your Time Zone

If the time you got back from the code is not the right time, it's probably because
your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set a
timezone to use.
The example below sets the timezone to "America/New_York", then outputs the
current time in the specified format:

Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
PHP 5 Date and Time…

Create a Date With PHP mktime()


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 (as
shown in the examples above).
• The mktime() function returns the Unix timestamp for a date. The Unix
timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.
Syntax
mktime(hour,minute,second,month,day,year)
The example below creates a date and time from a number of parameters in
the mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP 5 Date and Time…
Create a Date From a String With PHP strtotime()

The PHP strtotime() function is used to convert a human readable string to a Unix time.
Syntax
strtotime(time,now)
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various values:

Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
PHP 5 Include Files
The include (or require) statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text
on multiple pages of a website.
PHP include and require Statements
• It is possible to insert the content of one PHP file into another PHP file (before the
server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include
file is missing, use the include statement. Otherwise, in case of FrameWork, CMS,
or a complex PHP application coding, always use the require statement to include a
key file to the flow of execution. This will help avoid compromising your application's
security and integrity, just in-case one key file is accidentally missing.

Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header needs to
be updated, you can only update the header include file.
PHP 5 Include Files…
Syntax
include 'filename';
or
require 'filename';
PHP include Examples
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>
PHP 5 Include Files…
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done (we are using a <div> element
so that the menu easily can be styled with CSS later):
Example
<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>
PHP include vs require

The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included
with the include statement and PHP cannot find it, the script will continue to execute:
Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
If we do the same example using the require statement, the echo statement will not be
executed because the script execution dies after the require statement returned a fatal
error:
Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
PHP 5 File Handling
File handling is an important part of any web application. You often need to open
and process a file for different tasks.

PHP Manipulating Files

PHP has several functions for creating, reading, uploading, and editing files.
PHP readfile() Function
The readfile() function reads a file and writes it to the output
buffer.
Assume we have a text file called "webdictionary.txt", stored on
the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
PHP 5 File Handling…

The PHP code to read the file and write it to the output buffer is as follows (the
readfile() function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read
its contents.
PHP 5 File Open/Read/Close

PHP Open File - fopen()


• A better method to open files is with the fopen() function. This function
gives you more options than the readfile() function.
The first parameter of fopen() contains the name of the file to be opened and
the second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable
to open the specified file:
• Example
• <?php
$myfile = fopen(“names.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize("webdictionary.txt"));
fclose($myfile);
?>
The file may be opened in one of the following modes:
Modes Description

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

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

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

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

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

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

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

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to read from
and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize(“names.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.
• The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
• The fgets() function is used to read a single line from a file.
The example below outputs the first line of the “names.txt" file:
Example
<?php
$myfile = fopen(“names.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP File upload
A PHP script can be used with HTML form to upload files to the server. Initially files
are uploaded into the temporary directory and then redirected to the target
destination by the PHP script.
Creating an upload form:
The following HTM code below creates an uploader form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" > <br > <br>
<input type="submit" value=“submit" >
</form>
</body>
</html>
Creating an upload script

There is one global PHP variable called $_FILES. This


variable is an associate double dimension array and keeps
all information related to uploaded file. S o if the value
assigned to the input's name attribute in uploading form
was file, then PHP would create following five variables:
• $_FILES['file']['tmp_name']- the uploaded file in the temporary
directory on the web server.
• $_FILES['file']['name'] - the actual name of the uploaded file.
• $_FILES['file']['size'] - the size in bytes of the uploaded file.
• $_FILES['file']['type'] - the MIME type of the uploaded file.
• $_FILES['file']['error'] - the error code associated with this file
upload.
Creating an upload script…
<?php
$name = $_FILES[‘file’][‘name’];
$tmp_name = $_FILES[‘file’][‘tmp_name’];
If(isset($name)){
if(!empty($name)){
$location = ‘uploads/’;
If(move_uploaded_file($tmp_name, $location.$name)){
echo”uploaded”;
}else{
echo ”please select a file”;
}
}

?>
<?php
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES["file"]['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = "uploads/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo "uploaded";
}
else "please select the file";
}
}
?>
<html>
<body>
<form action ="upload.php" method ="POST" enctype = "multipart/form-data">

<input type = "file" name = "file"><br><br>


<input type = "submit" value = "submit">
</form>
Limit File Size and File Type

The code below only allows users to upload JPG and JPEG files and also it only accept 2mb and less than, if this not true it generate error message “File must be jpg/jpeg and must
be 2mb or less”
<?php
$name = $_FILES[‘file’][‘name’];
$extension = strtolower(substr($name, strpos($name, “ .”) + 1));
$type = $_FILES[‘file’][‘type’];
$size = _FILES[‘file’][‘size’];
$max_size = 2097152;
$tmp_name = $_FILES["file"]['tmp_name'];
if(isset($name)){
if(!empty($name)){
If(($extension == ‘jpg’|| $extension == ‘jpeg’) && $type == ‘image/jpeg’ && $size <= $max_size){

$location = "uploads/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo "uploaded";
}
else “There was an error”;
}
}else { echo “File must be jpg/jppeg and must be 2mb or less”;
}
}
?>
<html>
<body>
<form action ="upload.php" method ="POST" enctype = "multipart/form-data">

<input type = "file" name = "file"><br><br>


<input type = "submit" value = "submit">
</form>
</body>

You might also like