PHP Error Handling

Error Handling in any programming language is the process to catch the errors in the program and return the appropriate message based on some conditions. And if you will not handle the errors your program will always break and will see some auto generated errors returned by the programming language and in the chapter you will learn PHP Error Handling.

PHP Error Handling

Error Handling in PHP is quite easy. So we will show you error handling with some examples.

Error Handling with die(); function

You can use die(); function for any simple error handling process as you can see in the following example:

Example

In the above example, the program will return a proper message in both the cases and program will not break anywhere.

Custom Error Handling in PHP

We can create a function to handle the errors and we can call that function whenever required.

Syntax

As you can see, we can pass up to five parameters in the function but two parameters are compulsory.

The compulsory parameters are “error_level” and “error_message”.

And the optional parameters are “error_file”, “error_line”, and “error_context”.

The complete description of all the parameters are given below:

Parameters  Description
error_level This is a required parameter which defines the error level and this must be a value number.
error_message This is a required parameter which defines the error message.
error_file This is an optional parameter which defines the file name in which the error occurred.
error_line This is an optional parameter which defines the line number in which the error occurred.
error_context This is an optional parameter which defines an array containing every variable and their values in use when the error occurred.

 

PHP File Open/Read/Close

In this chapter we will see how we can open, read and close a file using PHP functions.

fopen() – Open a file in PHP

fopen() function is used to open a file in PHP. This function accepts two parameters.

  • One parameter will be passed as a filename
  • And the second parameter will be used for the filemode.

Example

fread() – Read a file in PHP

Then fread() function in PHP, is used to read the file. It accepts two parameters:

  • First parameter will be passed as a filename.
  • And the second parameter specify the file size.

fclose() – Close a file in PHP

This function is used to close an opened file. It is a good practice to close all the opened file because it saves the server resources and makes the website fast.

The fclose() function accepts only one parameter which will be just the filename only.

 

 

PHP File Create/Write

In this chapter we will see how we can create a new file and if we want to write something in this file then how we can do that.

fopen() Function in PHP

fopen() function is basically used to open a file but in case file doesn’t exists then it will create a new file with the name defined as filename argument in the fopen() function.

Syntax of fopen() function in PHP

In the filename parameter, we need to specify the filename which we want to open or create.

And in the filemode parameter, we need to specify in which more we want to open that particular file. There are mainly six file modes in PHP which can be used here as parameter.

PHP File Modes
Mode Purpose
r This specify that the file is for read only purpose.

And the file pointer will be placed at the beginning of the file.

r+ This specify that the file is for read and write both purposes.

And the file pointer will be placed at the beginning of the file.

w This specify that the file is for write only purpose. And If files does not exist then it will create a new file.

And the file pointer will be placed at the beginning of the file.

w+ This specify that the file is for read and write both purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the beginning of the file.

a This specify that the file is for write purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the end of the file.

a+ This specify that the file is for read and write both purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the end of the file.

Example of fopen() function in PHP

Now if you will open the file,  then you will find the text in the file which we write using the fwrite() function.

 

PHP File Upload

File uploading a very common thing if you are working on a web application. So in this chapter we will explain everything in details about file uploading but before that we want to tell you about few common functions which will be used in file uploading.

basename() function in PHP

basename() function accepts one parameter and  is used to get the file name from a link or URL. You can understand this with the following example:

pathinfo() function in PHP

This function accepts two parameter and returns a value with the type of the file.

getimagesize() function in PHP

This function accepts one parameter and returns the image dimensions (height/width) along with the type of file.

file_exists() function in PHP

This function accepts one parameter as a file name and will check if any file or directory with the same name exists or not in the same folder. It will returns TRUE if the file exists, else FALSE.

move_uploaded_file() function in PHP

This is is used to move a file to a new location or simply we can say that this file will be used to upload the file on server. This function accepts two parameter (filename, file location) and if the file is not uploaded because of any reason then it will returns FALSE else there will be no action.

As we have already explained all the functions which will be used in file uploading, so now it will be easy for you to understand the complete process.

NOTE: If you are creating an HTML form for the purpose of file uploading then you need to know the three main important points as mentioned below:

  1. Form Method: If you are trying to upload a file then the form method should be “POST” because the “GET” method is not going to work for file uploading because we can send only limited values using GET method. So always use POST method while file uploading.
  2. enctype attribute: You also have to add the enctype attribute in the form tag because only this tag will specify that which content type will be used while uploading the file.
  3. File attribute of input type: The file attribute of the input type should be “file”. Normally, we use input type attribute as “text” but in case of file upload, the input type attribute should be “file” because this will create the option to browse a file.

Step 1: Create an HTML Form

Step 2: Upload file in PHP

Check the file size in PHP

The following script is used to check the file size:

Check the file format in PHP

Check the file exist or not in PHP

 

 

 

PHP File Handling

If you are web developer, then you may need to deal with files.  Because file handling is an import part in PHP, so you may need to open and process the files using the file functions. So in this chapter, we will explain you how you can read a file using PHP functions.

readfile() Function in PHP

The readfile() function in PHP, reads any file. While using the readfile() function, you have to make sure that the file exists on the same path as mentioned with the readfile() function braces otherwise it will generate an error if file doesn’t exists.

Example of readfile() function

In the example above, we used a file named “thephpguide.txt”. So it will display all content whatever we have written in the file.

But in the real life program, we may need to read a big .xml file and we may need to fetch all data from that file based on some conditions.

So, we will explain all the commonly used file functions in our other chapter and we hope you will be able to do it easily whenever needed in the program.

 

PHP Date and Time

Sometimes we may need to display current date and time in our program and that is why we use the date() and time() functions to display the date and time.

The date() function in PHP

if you want to display date and time in a more readable language then we need to use the date() and time() functions with timestamp.

Syntax of date() function in PHP

Format: The format parameter is required in date() function. So it is must to define this parameter to display the current date.

Timestamp: It is not compulsory to pass the timestamp variable in the date() function in PHP. And the default value of the timestamp will the current date and time. So if we don’t pass this parameter this it will by default display the current date in the format as defined in the date() function.

How to display the current date in PHP

To display the current date, we will use the date() function as shown in the following example:

How to display the current time in PHP

You can display the current time as shown in the following example:

There are so many parameters which can be used to display the current date and time in different format. Here is the list of parameters in PHP:

The list of characters used as parameter in date() function.
character Details Example
Day characters
d displays the day of month leading with zeros 01 to 31
D This will display the textual representation of a day with three letters Mon        to         Sun
j Displays the day of the month without leading zeros 1 to 31
l (lowercase ‘L’) full representation of the week days Sunday

to

Saturday

N numeric representation of the day of the week like 1 (for Monday) 7 (for Sunday)
S suffix for the day of the month st, nd, rd or th. Works well with j
w Its a Numeric representation of the day of the week like 0 (for Sunday) and 6 (for Saturday)
z Its used for the day of the year 0 to 365
Week
W week number of year like 42, the 42nd week of the year
Month
F A full representation of a month January  to December
m Numeric representation of the month with zeros 01 – 12
M A textual representation of a month with three characters only. Jan – Dec
n a numeric representation of the month without zeros 1 – 12
t used to display the number of days in the month 28 – 31
Year
L Check if it’s a leap year 1 if it is a leap year else  0 .
o This is same as Y, except if the ISO week number (W) belongs to the previous or next year Examples: 1999 or 2003
Y displays the current year with 4 digits. Like: 2017
y two digit representation of year Like: 16 or 17
Time
a Lowercase am or pm am or pm
A Uppercase AM or PM AM or PM
B Swatch Internet time 000 – 999
g displays 12-hour time format of an hour without zeros 1 – 12
G displays 24-hour time format of hour without zeros 0 – 23
h displays 12-hour format of hour with leading zeros 01 – 12
H displays a 24-hour format of hour with leading zeros 00 – 23
i Minutes with zeros 00 – 59
s Seconds leading zeros 00 – 59

 

PHP Include Files

If you are developing any application or website, you may always needs to include the external files for several purposes. So “include” function in PHP plays an important role if you want to include any external files. We have already explained all the functions which are being used to include any external files. Mainly there are four functions as mentioned below:

  1. include() – The include statement in PHP
  2. include_once() – The include_once statement in PHP
  3. require() – require statement in PHP
  4. require_once() – The require_once statement in PHP

So you can go through all the four chapters mentioned above for the complete details if you want to include any external file in your program. All the differences are clearly mentioned about all the four methods.

PHP Multidimensional Arrays

An array with two or more arrays are called multi-dimensional arrays in PHP. So in this tutorial we will understand about the multi-dimensional array in PHP.

What is Multi-dimensional array in PHP

It is not necessary that all the arrays have one key values but one key of array  may have other arrays. So a multi-dimensional array could be of 1 level, 2 level, 3 level, 4 level or more. So those arrays are called multi-dimensional arrays in PHP.

Two-dimensional array in PHP

Let us understand two-dimensional array with an example. Suppose you are a teacher and you want to prepare an exam record of class 10 with student name, roll number and marks as shown in the following table:

Student Name Roll Number Marks
Andy 101 50
Ian 102 75
david 103 68

If we need to maintain only the student name then this can be done with one-dimensional array but in our case, we need to keep a complete record of each student. So we need a multi-dimensional array (two dimensional array in our case here) this purpose.

So a two-dimensional array is a combination of multiple arrays. you can understand this with the following example:

We hope you understand the concept behind the multi-dimensional arrays.

 

PHP Cookies

Cookies are basically text files which are stored on client computer to track the user activities.

What is Cookies in PHP

Cookies are basically text files which are stored on client computer to track the user activities. PHP transparently supports HTTP cookies. So a cookie is a small file with the maximum size of 4KB that is storedon the client computer.

How to create cookie in PHP

In PHP, you can set a cookie using the functions setcookie() or setrawcookie(). As cookies are the part of HTTP header so setcookie() should be called before any output is sent to the browser.

Syntax of creating a cookie in PHP

All parameters details are given below:
  • Name − The name parameter is compulsory for creating a cookie and only this variable name will be used while accessing any cookies.
  • Value − This parameter will be used to set the value of the cookie variable name.
  • Expiry − Using this parameter, we can also set time of expiry of any cookie. And after the specified time period the cookie will be automatically be deleted from the client computer. And if the expiry parameter is not defined then the cookie will be automatically expired when the browser is closed.
  • Path − In this parameter we will specify the directories for which the cookie is valid. If we add “/”, it means the cookie is valid for the whole website.
  • Domain − In this parameter, just pass the domain name for which you want the cookies to be used for example www.google.com
  • Security − Just set this to 1 if the cookie is only sent by a secure transmission using HTTPS otherwise keep it to 0.
NOTE: WHILE CREATE A COOKIE IN PHP, THEN ONLY THE “NAME” PARAMETER IS COMPULSORY. SO REST OF THE PARAMETERS COULD BE BLANK.
Example of creating a cookie in PHP

How to delete a cookie in PHP

If you want to delete a cookie then you have to define the “expire” parameter with the expiry date.

EXAMPLE OF DELETING A COOKIE IN PHP

What is the difference between Session and Cookie in PHP

As we may have some confusion in sessions and cookies because we may think that both are working for the same purposes. But its not true, there are differences in sessions and cookies. Here are the main differences:

  1. Sessions store data on server side instead cookies stores the values in browser only.
  2. Sessions are used to store more sensitive and important information because sessions are more secure instead cookies are not secure because all cookies values are stored in the user’s browser only and anyone can check these values.
  3.  Sessions needs extra space on server because it creates a file when session is created and that file keeps all the sessions ids. Most commonly /temp folder is used for this purpose. instead cookies don’t needs any extra space because it just created in the browser only.
  4. If we want to maintain sessions on all the pages then we have to use the functions session_start() otherwise we will not get the session value on all the pages instead we don’t need to use any extra function to maintain its values on all pages, we can just use the global variable $_COOKIE to access the cookies values.

We hope we explained sessions and cookies both very well and you understand the differences.

PHP Sessions

In PHP, session is a method which can be used to store information which can be accessed on any page whenever needed on the website.

What is a session in PHP

Basically, sessions are used to identify the use identity and the server sends the same information related to that user only which is stored in session variable. For example, when you logged into your gmail or yahoomail account then how the server knows what information to be sent to the user who is currently logging into the account. This makes possible because of sessions. So whenever a user logged into their account, browser immediately sends a request with the session ID and server displays all the information related to that particular user only.

How the session work in PHP

  1. Whenever a session start, PHP creates generate a unique identifier of 32 bit hexadecimal numbers which could be any random number.
  2. A cookie will also be created autometically with the name of PHPSESSID in the users computer. The  PHPSESSID stores a unique value for each session ID.
  3. The session value is also stored either in the database or in the predefined folder name for which we do the settings in PHP.INI file and set a session path in session.save_path.

So when a request is sent from the browser, then first it looks for the cookie names  PHPSESSID created with the unique sessions ID and then match the session value which is stored either in the database or in the predefined folder. And based on this, the data will retrieved from the server and sent to the browser for that particular user.

How to Start a PHP Session

we need to use a PHP function named session_start() on the top of the page to start a session. This is the first and most important step if you trying to create a session using PHP.

And then the session value will be stored using a PHP global variable named $_SESSION. 

You can understand this using the following example:

PHP Session Example

In this example, we created a session named “username” using the PHP global variable $_SESSION. So now, if we want to retrieve the value of this session on any page then, first thing would be to add the function session_start() on the top of every page and only then you will be able to retrieve the value of session.

How to retrieve the PHP session Value

You can also display the session value using the following method also

How to destroy a session in PHP

If you want to destroy all the PHP sessions then just use the function session_destroy(). Once you call this function, it will automatically destroy all the PHP sessions.

But in case, if you want to destroy any particular session then you need to use the “unset()” function.

You can see both the methods in the following example:

We hope this chapter clears all the basics about the sessions in PHP.