Category Archives: Core Php

PHP Upload File


PHP File Upload :– In this tutorial you will see how to upload a file on remote server.You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.

We have given the best suitable example for understanding file uploading approach in detail.


PHP $_FILES:

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

For example $_FILES[‘filename’][‘tmp_name’] returns temporary file’s folder where it will store i.e. c://xampp?temp.

move_uploaded_file() function:

Most oftenly when we upload file ;it will go into temp folder in c://xampp//temp and now move_uploaded_file() function comes into picture and sends file from temp folder to remote server.

In below example one thing to remember is that we have created a folder named “uploads” where our jellyfish.jpg file will be uploaded.

PHP File Upload | Example

Example

Select File:

Example

";
$tempdir=$_FILES['fileToUpload']['tmp_name'];
echo $tempdir;
echo "
"; echo $target_path = $target_path.'/'.basename( $_FILES['fileToUpload']['name']); if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) { echo "File uploaded successfully!"; } else{ echo "Sorry, file not uploaded, please try again!"; } ?>

PHP Creating And Writing File


PHP Creating And Writing File:– One of the most useful features of a server side language is its ability to interface with the file system on the server.
o access a file you first have to establish a connection to that file. This is done by opening the file with the fopen function. To use the fopen function you provide it two parameters. The first is the name of the file you wish to use and the second says how you want to use the file (for reading or writing etc) Using the fopen function establishes a pointer to the file

When we have an existing file then we open it to perform operations and if file does not exists then we create it first.


PHP Creating And Writing File | Example

Below first screenshot shows the initial content of file and second bottom screenshot shows content of file after writing into file.

Example

";
echo "
"; //echo fread($handle,filesize("file.txt")); fwrite($handle,$data); fwrite($handle,$filedata); fwrite($handle,$value); fclose($handle); $myfile = fopen("testfile.txt", "w"); echo "data has been successfully written"; ?>

PHP Filesystem Functions

Example

Functions Description
fread() Reads a string of characters from a file.
fwrite() Writes a string of characters to a file.
rewind() Moves the file pointer to the start of the file.
ftell() Returns the position of the file pointer.
fseek() Moves the file pointer to a specific location within an open file.
readfile() Displays the contents of a file without needing to open it.
fpassthru() Displays the contents of an open file.
file_put_contents() Writes a whole string to a file without needing to open it.
file_get_contents() Reads an entire file into a string without needing to open it.
file() Reads an entire file into an array.
fgetcsv() Reads a line of comma – separated values.
fgets() Reads a single line at a time.
feof() Checks to see if the end of the file has been reached.
fgetc() Reads a single character at a time.

PHP File Handling System


PHP File Handling:– File handling is an important task of any web application. In this tutorial you will learn how to create, access, and manipulate files and directory on your web server using the PHP file system functions.

Firstly open a file using fopen method by passing two parameters(file name,access mode).Based on requirement there are many modes which we can utilise in files.
For example opening a file for reading only, opening a file for reading and writing both etc .These all mode we will discuss later in detail.

  1. fclose()function is used to close a file after performing all operations.
  2. fread()function is used to read a file from first character to entire file .
  3. fread()takes two parameters ; first file name and second is for filesize given for characters length to read from file.

Modes Meaning
r opens the file to read only
r+ Opens the file for reading and writing.
x+ Opens the file for reading and writing. Returns FALSE and an error if file already exists.
x Opens the file for writing only. Returns FALSE and an error if file already exists.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
a Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
w+ Opens the file for reading and writing and clears the contents of file. If files does not exist then it attempts to create a file.
w Opens the file for writing only and clears the contents of file. If files does not exist then it attempts to create a file.

PHP File Handling | Example

Example of PHP File Handling.

";
echo "
"; echo fread($handle,filesize("file.txt")); ?>

PHP Include


PHP Include:– PHP include keyword is used to import a php file into another file.This reduces time and rewriting of code instead of copy and paste strategy.So we recommend to use this include keyword to evaluate a specific php file which you need to include in your file.

If somebody deletes your file then use of include does not make any sense because echo statement will execute.So now we should use require keyword in place of include keyword.
Benefit of using require keyword over include is once require will find no existing file immediately it will kill echo statement.


PHP Include | Example

Below example shows how simplephp.php file’s content are accessed by Simple.php file.

Example of PHP Include//Simple.php


Illustration of simplephp.php file.


PHP Require Vs Include


PHP Require Vs Include:– When we want to import a file content into another php file then simply we can use include keyword but have you ever think that will will happen if file does not exists which we want to access ; it will execute echo statement excluding the file content.Now we use require keyword to eleminate execution of echo statement which will execute unnecessary strings.


PHP Require Vs Include | Example

In below example we use simplephp2.php file name instead of simplephp.php mistakenly so will can see outputs displaying “Name of Alex ” extra string used in echo statement using include; but this undesired echo statement will not be executed when we use require .

Example of PHP Require Vs Include.

";
echo "Age of Alex is ".$age;
?>
";
echo "Age of Alex is ".$age;
?>

PHP Form Validation And Required Field


PHP Form Validation And Required Field :– Web application are more vulnerable if you do not validate your form inputs.So form validation is used to prevent cross site scripting attacks from hackers.

There are two types of validations in php.

  1. Client Side Validation
  2. Server Side Validation

PHP Form Validation | Example

Server side validation is done on php enabled server whereas client side validation usually happens on client side i.e browser.Following below examples describes how does script checks and validate user inputs in form validation process.

When user leaves Name field blank in first example below ; user gets one warning message .Similarily in below example you can easily see if user gives an invalid email address immediately a message displays saying “Please enter valid email id “.

These example contains complete validation script for form data with name ,email , URL fields and radio button.

If you run below script you will find output same as looking in below screenshots.

.

Example.

Name:

Only letters and white space allowed";
}
}
if (empty($_POST["email"])){
$emailerror = "email is required";
}

	else
 {
$email = test_input($_POST["email"]); // check name only contains letters and whitespace
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailerror = "  
please enter correct email id"; } } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; }else { $gender = test_input($_POST["gender"]); } if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } function test_input($value) { $value = trim($value); $value = stripslashes($value); $value = htmlspecialchars($value); return $value; } ?>
"> Name:

Email:

Gender: Female Male

"; echo "
"; echo $email; echo "
"; echo $website; echo "
"; echo $gender; echo $nameError; echo $emailerror; ?>

PHP Form Handling


PHP Form Handling:– When a form is submitted to a php script.the information from that form is automatically made available to the script. There are few ways to access this information which are described in below example.


PHP Form Handling | Example

Now we are going to explain below example how does a html form data is processed by a php script.Here you can see getform.php file is defined on form action tag which simply means that when user clicks on submit button then form input field values will be processed by php script using post method. Here you can also use get method instead of post method but for security reasons we never recommend to use it .

.

Example of PHP Form Handling.

Your name:

Your age:


Description of getform.php.



OR

.
You are  years old.
?>


PHP Sorting Array


PHP Array Sorting:– Array sorting means reordering of array element either in ascending or descending order.


PHP Indexed Array Sorting | Example

To sort indexed array we use sort() function whereas rsort() function is used to sort in descending order.

Example of Indexed Array Sorting in ascending order.


PHP Associative Array Sorting| Example

we use asort() function To sort associative array in ascending order according to value whereas ksort() function is used to sort according to key value.

arsort() and krsort() functions are used to sort associative array in desdending order according to value and key respectively.

Example of Associative Array Sorting in ascending order by value and key respectively in below example.

Example of Associative Array Sorting

10,"Mohan"=>8,"Rohan"=>11,"Kamal"=>22,"Paras"=>21);
ksort($numbers);
print_r($numbers);
?>

PHP Array


PHP Array:– In programming array is a collection of similar data having same size and types.Each value in an array is called array element.

For example you could have array of integers ,strings,characters,objects etc depending on need for programming perspective .
There are three types of php array which are discussed below one by one in detail.

  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array

PHP Array | Example

An Indexed Array stores values on indexes starting fron 0 to length of array.

Example of Indexed Array


PHP Associative Array | Example

We can also store values in key value pair by using associative array

Example of Associative Array

"Peacock","National_Game"=>"Football","National_Currency"=>"Rupee");
echo "National Bird is ==>".$direction_name['National_Bird'];
?>

PHP Multidimensional Array | Example

Multidimentional array stores multiple arrays inside an array.

Example of Multidimensional Array

"Java",
"Harish"=>"Android",
),
array(
"Web Technology"=>"PHP",
"Android Technology"=>"Java",
),
);
echo "Retreiving values from nested array "  .$employee[0]["Harish"];
echo "
"; echo $employee[1]["Android Technology"] ?>