PHP
File Modes

PHP Provides different modes for file handling. these modes are used in open method during file opening.

ModesDescription
‘r’Open file for reading only, place the file pointer at the beginning of the file.
‘r+’Open file for reading and writing, place the file pointer at the beginning of the file.
‘w’Open file for writing, place the file pointer at the beginning of file. If the file does not exist, attempt to create it.
‘w+’Open file for reading and writing, place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘a’Open file for writing only, place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’Open file for reading and writing, place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’Create and open file for writing only, place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’Create and open file for reading and writing, otherwise it has the same behavior as ‘x’.
‘c’Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’Open the file for reading and writing; otherwise it has the same behavior as ‘c’.

PHP File Open/Read

File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP has many functions for file creation, reading, writing, delete and etc.

In File handling before read/write we need to open a file and close the file after performing operations.

Sample Text File

Assume you have the following sample text file at your server directory. and it’s name is file.txt

PHP = PHP Hypertext Preprocessor
HTML = Hyper Text Markup Language
CSS = Cascading Style Sheets
JS = Java Script
SQL = Structured Query Language
XML = EXtensible Markup Language
AJAX = Asynchronous JavaScript and XML

Reading Complete File

PHP have different function for reading but right now we will study a simple function which will take the file name and return the full content of a file.

	<?php
	//Read a entire file with Single Function
	//Return the Total Number of Bytes in return which is read by this function
	echo readfile("file.txt");
	?>

Read file single line Example

Below example will demonstrate the fget function which will read the file line by line.

	<?php
	//Read a single line from file with fgets
	$fh=fopen("file.txt",'r') or die("file not found"); 
	$text=fgets($fh); //Read Single Line
	fclose($fh);
	echo $text;
	?>

Read the file with FEOF & FGET Method

This example will demonstrate how to read the file line by line till the file pointer reach at the end of file.

	<?php
	//Read a entire file with fget and feof functions
	$fh=fopen("file.txt","r") or die("file not found");
	//output one line until end of file
	while(!feof($fh)){
		echo fgets($fh)."
"; } ?>

Read the file with fread

fread function provides the functionality to the read the file till the specific byte.

	<?php
	//Read a file using fread function
	$fh=fopen("file.txt",'r') or die("file not found");
	$text=fread($fh,filesize("file.txt"));
	fclose($fh);
	echo $text;
	?>

Read Entire File with file_get_content

file_get_content provides the ability to read the remote files and return a string.

	<?php
	//Read a file using file_get_content
	$file=file_get_content("https://www.google.com");
	echo $file;
	?>

PHP Form Validation

In any web application server side form validation is very important part. PHP provides very nice built in functions for form validation.

HTML Form with Validation

Below example form contains 4 fields i.e textbox for name, radio button for gender, email box for email address and select box for degree selection. this example both html5 and php validation which will be discussed in below sections.

<!doctype html>
<html>
	<head>
		<title>HTML5 Form With Server Side Validation</title>
	</head>
	<body>
		<?php
			//Variables for error Messages
			$errName=$errEmail=$errDegree="";
			
			//take the form data
			if(isset($_POST['submit'])){
				
				//declare variables for from controls data
				$name=$gender=$email=$degree="";
				
				//Clear the Form data from injections/attacks
				$name=check_input($_POST['txtName']);
				$gender=check_input($_POST['rdGender']);
				$email=check_input($_POST['txtEmail']);
				$degree=check_input($_POST['slDegree']);
				
				//validate the data
				if(empty($name) || !preg_match("/^[a-zA-Z ]*$/",$name)){
					$errName="Please Enter the Name";
				}
				if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)){ //if email is not empty then validate the email
						$errEmail="Please Enter Valid Email";
				}
			
				if($degree=="--select--"){
					
					$errDegree="Please Select the Degree";
				}
			}
			
			function check_input($value){
				$value=trim($value); //remove the unwanted spaces
				$value=stripslashes($value); //remove the slashes
				$value=htmlspecialchars($value); //convert tags into special character format like from  < tag to < 
				return $value;
			}
		?>
		<h1>Student Form</h1>
		<form  action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post" enctype="multipart/form-data">
			Name*:<input type="text" name="txtName" required maxlength="15" />
			<p style="color:red"><?php echo $errName;?></p>
			Gender*:<input type="radio" value="Male" name="rdGender" checked /> Male
				    <input type="radio" value="FeMale" name="rdGender" /> Female
			<br /><br />
			Email:<input type="email" name="txtEmail" />
			<p style="color:red"><?php echo $errEmail;?></p>
			Degree:<select name="slDegree">
						<option value="--select--">----Select----</option>
						<option value="BSIT">BSIT</option>
						<option value="BSCS">BSCS</option>
						<option value="MIT">MIT</option>
						<option value="MS">MS.IT/CS</option>
						<option value="PHD">PHD</option>
					</select>
			<p style="color:red"><?php echo $errDegree;?></p>
			<input type="submit" value="Send" name="submit" />
		</form>
	</body>
</html>

HTML5 Validation Features

First thing HTML5 Provide new parameters for input field like email, url, number and etc. and their is required attribute for input tag which will autmatically check whether field is empty or filled by data.

		Name*:<input type="text" name="txtName" required maxlength="15" />
		Email:<input type="email" name="txtEmail" />

PHP_SELF for Forms

Mostly we need to submit our form data to same page by which we are submitting the data. so php provides comprehensive way to submit data to same page. php global variable $_SERVER[‘PHP_SELF’] provides it’s filename.

	<?php 
		//htmlspecialchars functions convert the tags into html special character codes to pervent the attacks/injections.
		echo htmlspecialchars($_SERVER['PHP_SELF'])
	?>

Clearing the $_POST/$_GET Data

Server don’t know either a ordinary user is sending a data or a hacker is trying to hack a site. so there are plenty of functions that is used to clear the $_POST/$_GET Data before processing them. so below user-defined function is a combination of different built-in functions which will take the form component value and clear it from unnecessary things and return a clean value.

	<?php
		function check_input($value){
			$value=trim($value); //remove the unwanted spaces
			$value=stripslashes($value); //remove the slashes
			//convert tags into special character format like from  < tag to 
			
			$value=htmlspecialchars($value); 
			return $value;
		}
	?>

Preg_match Function

preg_match is a PHP built-in function which is used to match a data according to regular expression. in this example we using preg_match to identify the name as name just contains alphabets not numbers or special characters.

<?php
	// "/^[a-zA-Z ]*$/" this reular expression state that only lower and upper case alphabets are allowed.
	preg_match("/^[a-zA-Z ]*$/",$name)
?>

filter_var Function

filter_var contains different attributes to filter different things. but in this example this function is used to verify the email pattern.

	<?php
		//Email Validation by filter_var function with FILTER_VALIDATE_EMAIL attribute
		filter_var($email, FILTER_VALIDATE_EMAIL)
	?>

PHP Form File Upload

File Upload is very important part in any web application. PHP Provides very easy functions for file upload.

File Upload Example

Below example combines the HTML & PHP Code for file upload.

<!doctype html>
<html>
	<head>
		<title>File Upload</title>
	</head>
	<body>
		<form action="" method="post" enctype="multipart/form-data" >
			Picture<input type="file" name="fiPicture" />
			<br />
			<input type="submit" value="Upload" name="Upload" />
		</form>
		
		
		<?php
			if(isset($_POST['Upload'])){
				$name=$_FILES['fiPicture']['name'];
				if(move_uploaded_file($_FILES['fiPicture']['tmp_name'],$name)){
					echo "<p>file has been Uploaded Successfully</p>";
				}else{
					echo "<p>Unable to upload file please try again.</p>";
				}
				
			}
		?>
	</body>
</html>

Get File Attributes Example

$_FILES Array provide other attributes such as file type, file size. below example will demonstrate how to get file size, file type

<!doctype html>
<html>
	<head>
		<title>File Upload</title>
	</head>
	<body>
		<form action="" method="post" enctype="multipart/form-data" >
			Picture<input type="file" name="fiPicture" />
			<br />
			<input type="submit" value="Upload" name="Upload" />
		</form>
		
		
		<?php
			if(isset($_POST['Upload'])){
				$name=$_FILES['fiPicture']['name'];
				$type=$_FILES['fiPicture']['type'];
				$size=$_FILES['fiPicture']['size']; //size will come in bytes
				
				echo "Name=".$name."<br />";
				echo "Type=".$type."<br />";
				echo "Size=".$size."<br />";
			}
		?>
	</body>
</html>

Get File Extension Example

File extension comes with file name. below example will demonstrate how to fetch extension from name with the help of other functions

<!doctype html>
<html>
	<head>
		<title>File Upload</title>
	</head>
	<body>
		<form action="" method="post" enctype="multipart/form-data" >
			Picture<input type="file" name="fiPicture" />
			<br />
			<input type="submit" value="Upload" name="Upload" />
		</form>
		
		
		<?php
			if(isset($_POST['Upload'])){
				$name=$_FILES['fiPicture']['name'];
				$fileParts=explode(".",$name);
				echo "File Extension is=".$fileParts[1]."<br>";
			}
		?>
	</body>
</html>

File Validation Example

Some times we require only image file or doc files with size limits. below example will demonstrate how to accomplish file validation with file type and size.

<!doctype html>
<html>
	<head>
		<title>File Upload</title>
	</head>
	<body>
		<form action="" method="post" enctype="multipart/form-data" >
			Picture<input type="file" name="fiPicture" />
			<br />
			<input type="submit" value="Upload" name="Upload" />
		</form>
		
		
		<?php
			if(isset($_POST['Upload'])){
				$name=$_FILES['fiPicture']['name'];
				$type=$_FILES['fiPicture']['type'];
				$size=$_FILES['fiPicture']['size'];
				$fileParts=explode('.',$name); //divide the name into two parts
				$ext=strtolower($fileParts[1]); //extract the extension of file and convert it to lower case
				if($ext=="jpeg" || $ext=="jpg" || $ext=="png" || $ext=="gif" || $ext=="bmp"){
					if($size/1024<=200){ //size limit to 200KB
						if(move_uploaded_file($_FILES['fiPicture']['tmp_name'],$name)){
							echo "&ltp>file has been Uploaded Successfully</p>";
						}else{
							echo "<p>Unable to upload file please try again.</p>";
						}
					}else{
						echo "<p>Please upload less then 200KB image file</p>";
					}
				}else{
					echo "<p>Only Image Files are allowed such as jpg, png, gif & bmp</p>";
				}
			}
		?>
	</body>
</html>


PHP Form Handling

$_GET & $_POST are global variables which are used to obtain form data.

Simple HTML Form

Below form will consist of single text box which contains the name and send the data to welcome.php by get Method

<!doctype html>
<html>
	<head>
		<title>Simple Form</title>
	</head>
	<body>
		<form action="welcome.php" method="get">
			Name:<input type="text" name="txtName" />
			<br />
			<input type="submit" Value="Send" name="btnsend" />
			<input type="reset" />
		</form>
		</form>
	</body>
</html>

Welcome.php File for Form

$_GET store all the request’s data which are sent by Get Method.

<?php
	if(isset($_GET['btnsend'])){
			echo 'Welcome Mr.'.$_GET['txtName'].' to PHPdocs.com';
		}
?>

Simple HTML Login Form

Below is the Login form which will send it’s data to login.php file via post Method.

<!doctype html>
<html>
	<head>
		<title>Simple Form</title>
	</head>
	<body>
		<form action="login.php" method="POST">
			User Name:<input type="text" name="txtUserName" />
			<br />
			Password:<input type="password" name="txtPassword" />
			<br />
			<input type="submit" Value="Login" name="btnlogin" />
			<input type="reset" />
		</form>
	</body>
</html>

login.php file for Login Form

	<?php
		if(isset($_POST['btnlogin'])){
			$username=$_POST['txtUserName'];
			$password=$_POST['txtPassword'];
			
			if($username=="abc@gmail.com" && $password=="123@pk"){
				echo "Welcome to Page";
			}else{
				echo "Username/Password is Invalid. try again!";
			}
		}
	?>

PHP Include/Require Function

The include/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.

Both Include/Require Statements are identical except errors.

  • Require will produce fatal error and stop the script.
  • Include will produce warning message and continue the execution of script.

require_once & include_once is another identical versions of both functions with the feater of one time file include. both are recommend method’s during high end application development.

Division of page

Majority of web applications consist of same headers, menus, footer. so in the below example we will identifiy the gerneric parts of web page and divide into header, menu and footer files and include them in a web pages.

<!doctype html>
<html>
	<!--Head Starts Here-->
	<head>
		<title>Include/Require Functions</title>
	</head>
		<!--Head Ends Here-->
	<body>
		<!--Menus Start Here-->
		<a href="#">Home</a>
		<a href="#">HTML</a>
		<a href="#">CSS</a>
		<a href="#">Java Script</a>
		<!-- Menus End Here-->
		<br />
		<h1>Welcome to PHP Docs</h1>
		<p>This example will divide header, menus, footer into separate files</p>
		<!--Footer Starts Here-->
		<?php echo "<p>Copyright © 2017-" . date("Y") . " PHPdocs.com</p>"; ?>
		<!--Footer Ends Here-->
	</body>
</html>

Above Web Page common parts are marked with comments. below we will create the separate files for each part and include them in final page

Header Part

Copy the Header part and save in header.php file.

		<!--Head Starts Here-->
	<head>
		<title>Include/Require Functions</title>
	</head>
		<!--Head Ends Here-->

Menu Part

Copy the Menu Part and save in menu.php file.

		<!--Menus Start Here-->
		<a href="#">Home</a>
		<a href="#">HTML</a>
		<a href="#">CSS</a>
		<a href="#">Java Script</a>
		<!-- Menus End Here-->

Footer Part

Copy the Footer Part and save in footer.php file.

		<!--Footer Starts Here-->
		<?php echo "<p>Copyright © 2017-" . date("Y") . " PHPdocs.com</p>"; ?>
		<!--Footer Ends Here-->

Join the Pages with include_once/require_once

Now combine the all divide files in a web-page to get the final output.

<!doctype html>
<html>
		<!--Including using require_once header.php-->
		<?php require_once 'header.php'; ?>
	<body>
		
		<!--Including using require_once menu.php-->
		<?php require_once 'menu.php'; ?>
		
		<br />
		<h1>Welcome to PHP Docs</h1>
		<p>This example will divide header, menus, footer into separate files</p>
		
		<!--Including footer.php-->
		<?php include_once 'footer.php'; ?>
	</body>
</html>

Benefit of this method is to make things generic. for example your website have 50 pages with more then 50+ links. if you want to change any link then what ? if you are using this generic method only need to change the menu from one place instead of modifying 50 pages.

PHP String Functions

PHP Provides wide range of functions to perform operations on string.

String Length Function Example

String Length Function will return the total characters in string.

	<?php
	//String Length
	echo strlen("Hello World"); //Output 11
	?>

Reverse String Function Example

	<?php
	//Reverse String
	echo strrev("elppA"); //Output Apple
	?>

String Search Example

Want to find any specific word from sentence. it will return the starting point of word.

	<?php
	//Search For a Specific Text Within a String
	echo strpos("I Love My Country","My"); //Output 7
	?>

Replace Text Function Example

Many time we require to replace the word in variable at runtime for this php provide str_replace() function.

	<?php
	//Replace Text Within a String
	echo str_replace("Friend","Brother","Hello Friend");//Output Hello Brother
	?>

Repeat String Function Example

	<?php
	
	//Repeat the string
	echo str_repeat("ha",4);//output hahahaha
	
	?>

Uppercase Function Example

Converts the string characters to upper case.

	<?php
	//String to UpperCase
	echo strtoupper("Pakistan"); //Output PAKISTAN
	?>

Lowercase Function Example

Converts the string characters to lower case.

	<?php
	//string to LowerCase
	echo strtolower("pHp"); //Output php
	?>

Introduction to Functions

Real power of PHP Comes from it’s bult-in functions, which are more then 1000.

PHP User-defined Functions

  • A function is a block of statements which can be used many times in a program.
  • A function will not execute until you will call.
  • A function will not execute on page load until you will call.

User Defined Function Syntax

<?php

function functionname(){
	//code goes here.
	//.
	//.
	//.
}
?>

Function Example

<?php

function Welcome(){
	echo 'Welcome to PHPDocs.com';
}
Welcome(); //calling the function

?>

Function with Parameters Example

<?php

function Sum($value1,$value2){
	echo $value1+$value2;
	echo "<br />";
}

Sum(20,30); //it will show 50
Sum(30,50); //it will show 80
Sum(40,60); //it will show 100
?>

Function with Return Example

<?php

function Multiply($value1,$value2){
	return $value1*$value2;
}

echo Multiply(2,5)."<br />; //it will show 10
echo Multiply(3,6)."<br />; //it will show 18
echo Multiply(4,8)."<br />; //it will show 32
?>

Function Parameters By Reference Example

To allow a function to modify its arguments, they must be passed by reference

place the & sign in the start of paraemeter to get Parameter by Ref

<?php

function Increment(&$value){
	++$Value
}

$counter=0;

Increment($counter); //it will show 1
Increment($counter); //it will show 2
Increment($counter); //it will show 3
Increment($counter); //it will show 4

?>

PHP Array Functions

PHP Provides wide range of functions to perform operations on array.

is Array Function Example

During Runtime if you want to check with a variable is a variable or an array then php is_array() function help out from this trouble.

	<?php
	//Getting the Length of an Array
	$fruit[]="Apple";
	$fruit[]="Orange";
	$fruit[]="Mango";
	echo is_array($fruit)?"It's an array":"it's a variable";
	?>

Array Length Function Example

In Programming tasks many time we require to know the length of an unknown array.

	<?php
	//Getting the Length of an Array
	$fruit[]="Apple";
	$fruit[]="Orange";
	$fruit[]="Mango";
	echo count($fruit);
	?>

Print an Array Example

PHP provide print_r() function to print whole array with single line.

	<?php
	$colors=array("white","green","black");
	print_r($colors);
	?>

Array Sort Function Example

Sorting is very important task during retrieval/display the data from database. PHP Provides different sort functions, but currently we will discuss sort() & rsort() functions.

	<?php
	$colors=array("white","green","black");
	sort($colors); //Sort an array in ascending order
	print_r($colors);
	
	$rcolors=array("black","white","green");
	rsort($rcolors); //Sort an array in reverse order
	print_r($rcolors);
	
	
	?>

Array Shuffle Function Example

There are many times when you need to put an array an random order. so don’t worry PHP Have shuffle() function to perform this operation.

	<?php
	
	//Shuffle
	$colors=array("red","green","yellow","blue");
	shuffle($colors);
	print_r($colors); // every time you will see the different color at different index
	
	?>

Array Reset Function Example

Reset() function moves the array index pointer to the first index of an array.

	<?php
	//Reset
	$colors=array("red","green","yellow","blue");
	echo reset($colors);
	?>

Array End Function Example

End() function moves the array index pointer to the last index of an array.

	<?php
	$colors=array("red","green","yellow","blue");
	echo end($colors); //Move the array Index Pointer to Last Index of an array and return the value of last index
	?>

Explode Function Example

Some time we have long string with same pattern and want to divide this long string into array. explode() function will convert a string to an array.

	<?php
	//Explode
	$URL="phpdocs.com/php/variables";
	$URL_array=explode('/',$URL); //divide the string into different parts on the base of forward slash (/)
	print_r($URL_array);
	}
	?>


PHP Array

Array is used to store a collection of values at one place instead of creating different variables.

PHP Have 2 types of arrays.

  • Indexed Arrays
  • Associative Arrays

Define Indexed Array

In PHP arrays are defined by array() method or by square brackets

	<?php
	//Numeric Index Array
	$colors=array("black","white","green");
	
	//another way of defining array
	$fruit[]="Apple";
	$fruit[]="Orange";
	$fruit[]="Mango";
	?>

Indexed Array Example

	<?php
	//Numeric Index Array
	$colors=array("black","white","green");
	
	echo "i like ".$colors[0]." color and my country flag contains ".$colors[1]." & ".$colors[2]." Colors";
	?>

Manually Assigned Indexed Array Example

PHP allow manually assigned Index to an array

	<?php
	//Manually assign Array Index
	$colors[1]="Black";
	$colors[2]="White";
	$colors[3]="Green";
	echo "i like ".$colors[1]." color and my country flag contains ".$colors[2]." & ".$colors[3]." Colors";
	?>

Loop Through Indexed Array Example

	<?php
	//loop through Indexed Array
	$Cities=array("Lahore","Dubai","Jinan");
	for($a=0;$a<3;$a++){
		echo $Cities[$a]."<br>";
	}
	?>

Associative Array Example

Associative Arrays contains Alphanumeric Index instead of Numeric Index.

	<?php
	//Associative Array
	$height=array("Qasim"=>5.7,"Fasial"=>5.5,"Kamran"=>6);
	echo "Qasim height is ".$height['Qasim']." Feet 
"; echo "Fasial height is ".$height['Fasial']." Feet
"; echo "Kamran height is ".$height['Kamran']." Feet
"; ?>

Associative Array with Foreach Loop Example

Foreach loop is designed for Arrays and it work very fine with Associative Arrays.

	<?php
	//Associative Array via ForeachLoop
	$height=array("Qasim"=>5.7,"Fasial"=>5.5,"Kamran"=>6);
	foreach($height as $name=>$value){
		echo $name." height is ".$value." Feet 
"; } ?>