Category: PHP

  • File Existence

    When working with files in PHP, one important task is to detect whether a specific file exists. This helps make sure that your program does not face errors while trying to access files that may not exist. This chapter will show you how to use basic examples to validate the presence of a file.

    It is often handy to check if the file you are trying to open really exists in the first place before performing any processing on it. Otherwise, the program is likely to raise a runtime exception.

    Why Check for File Existence?

    Before trying to open or read a file, be sure it exists. This allows you to avoid errors that can cause your program to fail. For example, trying to read an image file that does not exist can result in your function failure.

    PHP Functions for File Existence

    PHP’s built-in library provides some utility functions in this regard. Some of the functions we shall discuss in this chapter are −

    • file_exists() − tests if the file exists
    • is_file() − if the handle returned by the fopen() refers to a file or directory.
    • is_readable() − test if the file you have opened allows reading data
    • is_writable() − test if writing data in the file is allowed

    The file_exists() Function

    This function works with a file as well as a directory. It checks whether the given file or directory exists or not.

    file_exists(string$filename):bool

    The only parameter to this function is a string representing the file/directory with full path. The function returns true or false depending upon the file exists or not.

    Example

    The following program checks if the file “hello.txt” exists or not.

    <?php
       $filename = 'hello.txt';
       if (file_exists($filename)) {
    
      $message = "The file $filename exists";
    } else {
      $message = "The file $filename does not exist";
    } echo $message; ?>

    Output

    If the file does exist in the current directory, the message is −

    The file hello.txt exists
    

    If not, the message is −

    The file hello.txt does not exist
    

    Example

    The string pointing to the file may have a relative or absolute path. Assuming that “hello.txt” file is available in a “hello” subdirectory which is inside the current directory.

    <?php
       $filename = 'hello/hello.txt';
    
      if (file_exists($filename)) {
    $message = "The file $filename exists"; } else {
      $message = "The file $filename does not exist";
    } echo $message; ?>

    Output

    It will produce the following output −

    The file hello/hello.txt exists
    

    Example

    Try giving the absolute path as below −

    <?php
       $filename = 'c:/xampp/htdocs/hello.txt';
       if (file_exists($filename)) {
    
      $message = "The file $filename exists";
    } else {
      $message = "The file $filename does not exist";
    } echo $message; ?>

    Output

    It will produce the following result −

    The file c:/xampp/htdocs/hello.txt exists
    

    The is_file() Function

    The file_exists() function returns true for existing file as well as directory. The is_file() function helps you to determine if it’s a file.

    is_file(string$filename):bool

    The following example shows how the is_file() function works −

    <?php
       $filename = 'hello.txt';
    
       if (is_file($filename)) {
    
      $message = "$filename is a file";
    } else {
      $message = "$filename is a not a file";
    } echo $message; ?>

    Output

    The output tells that it is a file −

    hello.txt is a file
    

    Now, change the “$filename” to a directory, and see the result −

    <?php
       $filename = hello;
    
       if (is_file($filename)) {
    
      $message = "$filename is a file";
    } else {
      $message = "$filename is a not a file";
    } echo $message; ?>

    Now you will be told that “hello” is not a file.

    Note that The is_file() function accepts a $filename and returns true only if the $filename is a file and exists.

    The is_readable() Function

    Sometimes, you may want to check before hand if the file can be read from or not. The is_readable() function can ascertain this fact.

    is_readable(string$filename):bool

    Example

    Given below is an example of how the is_readable() function works −

    <?php
       $filename = 'hello.txt';
       if (is_readable($filename)) {
    
      $message = "$filename is readable";
    } else {
      $message = "$filename is not readable";
    } echo $message; ?>

    Output

    It will generate the following output −

    hello.txt is readable
    

    The is_writable() Function

    You can use the is_writable() function to can check if a file exists and if it is possible to perform write operation on the given file.

    is_writable(string$filename):bool

    Example

    The following example shows how the is_writable() function works −

    <?php
       $filename = 'hello.txt';
    
       if (is_writable($filename)) {
    
      $message = "$filename is writable";
    } else {
      $message = "$filename is not writable";
    } echo $message; ?>

    Output

    For a normal archived file, the program tells that it is writable. However, change its property to “read_only” and run the program. You now get −

    hello.txt is writable

  • Write File

    This chapter will show you how to create and write files in PHP. PHP is a popular programming language for creating dynamic web pages and applications. Writing files helps you to store data, log messages and create content on the server.

    What is File Writing?

    In PHP, file writing means either creating a new file or updating an existing one. This can be a text, log or CSV file. We will look at how to create simple text files in PHP.

    Here are the reasons why you should write files in PHP −

    • Data storage: It allows you to save user data, settings and any other information that your program needs.
    • Logging: Save any errors or events in your application for future review.
    • Backup: Exporting important data to a file provides its backup.

    Basic Functions for File Writing in PHP

    PHP’s built-in function library provides two functions to perform write operations on a file stream. These functions are fwrite() and fputs().

    To be able to write data in a file, it must be opened in write mode (w), append mode (a), read/write mode (r+ or w+) or binary write/append mode (rb+, wb+ or wa).

    The fputs() Function

    The fputs() function writes a string into the file opened in a writable mode.

    fputs(resource$stream,string$string,int$length)

    Here, the $stream parameter is a handle to a file opened in a writable mode. The $string parameter is the data to be written, and $length is an optional parameter that specifies the maximum number of bytes to be written.

    The fputs() function returns the number of bytes written, or false if the function is unsuccessful.

    Example: Return the number of Bytes

    The following code opens a new file, writes a string in it, and returns the number of bytes written.

    <?php
       $fp = fopen("hello.txt", "w");
       $bytes = fputs($fp, "Hello World\n");
       echo "bytes written: $bytes";
       fclose($fp);
    ?>

    It will produce the following output −

    bytes written: 12
    

    Example: Add text in Existing File

    If you need to add text in an earlier existing file, it must be opened in append mode (a). Let us add one more string in the same file in previous example.

    <?php
       $fp = fopen("hello.txt", "a");
       $bytes = fputs($fp, "Hello PHP");
       echo "bytes written: $bytes";
       fclose($fp);
    ?>

    If you open the “hello.txt” file in a text editor, you should see both the lines in it.

    Example: Write Content in Another File

    In the following PHP script, an already existing file (hello.txt) is read line by line in a loop, and each line is written to another file (new.txt)

    It is assumed thar “hello.txt” consists of following text −

    Hello World
    TutorialsPoint
    PHP Tutorials
    

    Here is the PHP code to create a copy of an existing file −

    <?php
       $file = fopen("hello.txt", "r");
       $newfile = fopen("new.txt", "w");
       while(! feof($file)) {
    
      $str = fgets($file);
      fputs($newfile, $str);
    } fclose($file); fclose($newfile); ?>

    The newly created “new.txt” file should have exactly the same contents.

    The fwrite() Function

    The frwrite() function is a counterpart of fread() function. It performs binary-safe write operations.

    fwrite(resource$stream,string$data,?int$length=null):int|false

    Here, the $stream parameter is a resource pointing to the file opened in a writable mode. Data to be written to the file is provided in the $data parameter. The optional $length parameter may be provided to specify the number of bytes to be written. It should be int, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

    The fwrite() function returns the number of bytes written, or false on failure along with E_WARNING.

    Example: Return Number of Bytes

    The following program opens a new file, performs write operation and displays the number of bytes written.

    <?php
       $file = fopen("/PhpProject/sample.txt", "w");
       echo fwrite($file, "Hello Tutorialspoint!!!!!");
       fclose($file);
    ?>

    Output

    This will create the below output −

    25
    

    Example: Open File in Binary Read Mode

    In the example code given below, an existing file “welcome.png” in opened in binary read mode. The fread() function is used to read its bytes in “$data” variable, and in turn written to another file “new.png” −

    <?php
       $name = "/PHP/PhpProjects/image2.png";
       $file = fopen($name, "rb");
       $newfile = fopen("/PHP/PhpProjects/new.png", "wb");
       $size = filesize($name);
       $data = fread($file, $size);
       fwrite($newfile, $data, $size);
       echo "File is written successfully.";
       fclose($file);
       fclose($newfile);
    ?>

    Run the above code. The current directory should now have a copy of the existing “welcome.png” file.

    Output

    Following is the output of the above code −

    File is written successfully.
    

  • Read File

    What is File Reading?

    Working with online applications frequently needs reading data from files. PHP makes it easy to read files from your server. File reading is the process of opening a file and extracting its data for usage in your program. For example, you may want to read a text file that contains user information, configuration settings or product specifications.

    How to Read a File in PHP?

    There are a number of options in PHP for reading data from a file that has been opened with the fopen() function. The following built-in functions in PHP’s library can help us perform the read operation −

    • file_get_contents() − reads a file into a string.
    • fgets() − gets a line from the file pointer.
    • fgetc() − returns a string with a single character from the file pointer.
    • fread() − reads a specified number of bytes from the file pointer.
    • fscanf() − reads data from the file and parses it as per the specified format.

    Using file_get_contents() Function

    This function reads the entire file into a string. It is the simplest way to read a file.

    file_get_contents($path,$include_path,$context,$start,$max_length)

    Example

    The following code reads the entire available content from the “myfile.txt” file −

    <?php
       // Specify the path to the file
       $filename = 'myfile.txt';
    
       // Read the content of the file
       $content = file_get_contents($filename);
    
       // Check if the file was read successfully
       if ($content === false) {
    
      echo "Error reading the file.";
    } else {
      echo "File content: " . $content;
    } ?>

    Output

    It will produce the following output −

    File content: Hello this is an example of 
    PHP read file.
    
    This is a new line in the file.
    

    Using fgets() Function

    The fgets() function can return a line from an open file. This function stops returning on a new line at a specified length or EOF, whichever comes first and returns false on failure.

    fgets(resource$stream,?int$length=null):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode, and $length is an optional parameter specifying the number of bytes to be read.

    The read operation ends when “length-1” bytes are read or a newline is encountered, whichever is first.

    Example

    The following code reads the first available line from the “hello.txt” file −

    <?php
       $file = fopen("hello.txt", "r");
       $str = fgets($file);
       echo $str;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    Hello World
    

    Example

    You can put the fgets() function in a loop to read the file until the end of file is reached.

    <?php
       $file = fopen("hello.txt", "r");
       while(! feof($file)) {
    
      echo fgets($file). "&lt;br&gt;";
    } fclose($file); ?>

    Output

    It will produce the following output −

    Hello World
    TutorialsPoint
    PHP Tutorials
    

    Here, we have used the feof() function which returns true if the file pointer is at EOF; otherwise returns false.

    Using fgetc() Function

    The fgetc() function returns a single character read from the current position of the file handle. It returns false when EOF is encountered.

    fgetc(resource$stream):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode.

    Example

    The following code displays the first character read from the “hello.txt” file −

    <?php
       $file = fopen("hello.txt", "r");
       $str = fgets($file);
       echo $str;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    H
    

    Example

    You can also put the fgetc() function inside a loop to read the file character by character until it reaches EOF.

    <?php
       $file = fopen("hello.txt", "r");
       while(! feof($file)) {
    
      $char = fgetc($file);
      if ($char == "\n")
      echo "&lt;br&gt;";
      echo $char;
    } fclose($file); ?>

    Output

    It will produce the following output −

    Hello World
    TutorialsPoint
    PHP Tutorials
    

    Using fread() Function

    The fread() function in PHP is a binary-safe function for reading data from a file. While the fgets() function reads only from a text file, the fread() function can read a file in binary mode.

    fread(resource$stream,int$length):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with binary read or read/write mode (rb or rb+). The $length parameter specifies number of bytes to be read.

    If the $length parameter is not given, PHP tries to read the entire file until EOF is reached, subject to the chunk size specified.

    Example

    The following code reads a text file −

    <?php
       $name = "hello.txt";
       $file = fopen($name, "r");
       $data = fread($file, filesize($name));
       echo $data;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    Hello World TutorialsPoint PHP Tutorials
    

    Example

    You can also read a non-ASCII file such as an image file opened in rb mode.

    <?php
       $name = "welcome.png";
       $file = fopen($name, "rb");
       $data = fread($file, filesize($name));
       var_dump($data);
       fclose($file);
    ?>

    The browser displays the “var_dump” information as the following −

    PHP Read File

    Using fscanf() Function

    The fscanf() function in PHP reads the input from a file stream and parses it according to the specified format, thereby converts it into the variables of respective types. Each call to the function reads one line from the file.

    fscanf(resource$stream,string$format,mixed&...$vars):array|int|false|null

    Here, the $stream parameter is the handle to the file opened with the fopen() function and in read mode. And, $format is a string containing one or more of the following formatting specifiers −

    • %% − Returns a percent
    • %b − Binary number
    • %c − The character according to the ASCII value
    • %f − Floating-point number
    • %F − Floating-point number
    • %o − Octal number
    • %s − String
    • %d − Signed decimal number
    • %e − Scientific notation
    • %u − Unsigned decimal number
    • %x − Hexadecimal number for lowercase letters
    • %X − Hexadecimal number for uppercase letters

    $vars is an optional parameter that specifies variables by reference which will contain the parsed values.

    Assuming that the “employees.txt” file is available in the same directory in which the PHP script given below is present. Each line in the text file has name, email, post and salary of each employee, separated by tab character.

    Example

    The following PHP script reads the file using the format specifiers in fscanf() function −

    <?php
       $fp = fopen("employees.txt", "r");
       while ($employee_info = fscanf($fp, "%s\t%s\t%s\t%d\n")) {
    
      list ($name, $email, $post, $salary) = $employee_info;
      echo "&lt;b&gt;Name&lt;/b&gt;: $name &lt;b&gt;Email&lt;/b&gt;: 
    $email <b>Salary</b>: Rs. $salary <br>"; } fclose($fp); ?>

    Output

    It will produce the following output −

    Name: Ravishankar Email: [email protected] Salary: Rs. 40000
    Name: Kavita Email: [email protected] Salary: Rs. 25000
    Name: Nandkumar Email: [email protected] Salary: Rs. 30000
  • Open File

    When working with PHP, you will need to read and write files. This chapter explains how to open a file in PHP. This is a important skill for any web developer who want to manage data properly.

    PHP’s built-in function library provides fopen() function to open a file or any other stream and returns its “reference pointer”, also called as “handle”.

    The fopen() function in PHP is similar to fopen() in C, except that in C, it cannot open a URL.

    Why Do We Need to Open Files?

    Opening files allows you to −

    • Retrieve data (like user submissions).
    • Save data (like user-generated content).
    • Handle various types of file formats (like JSON, CSV, and XML).

    How to Open a File in PHP

    To open a file with PHP, use the fopen() function. This function needs two parameters −

    • The name of the file.
    • The mode in which you want to open the file.

    Syntax of fopen()

    The fopen() function has the following signature −

    fopen(string$filename,string$mode,bool$use_include_path=false,?resource$context=null):resource|false

    Parameters

    The $filename and $mode parameters are mandatory. Here’s the explanation of the parameters −

    • $filename − This parameter is a string representing the resource to be opened. It may be a file in the local filesystem, or on a remote server with the scheme:// prefix.
    • $mode − A string that represents the type of access given to the file/resource.
    • $use_include_path − A Boolean optional parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.
    • $context − A context stream resource.

    Modes of Opening a File

    PHP allows a file to be opened in the following modes −

    ModesDescription
    rOpen a file for read only.
    wOpen a file for write only. creates a new file even if it exists.
    aOpen a file in append mode
    xCreates a new file for write only.
    r+Open a file for read/write.
    w+Open a file for read/write. creates a new file even if it exists.
    a+Open a file for read/write in append mode.
    x+Creates a new file for read/write.
    cOpen the file for writing, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode).
    c++Open the file for read/write, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode).
    eSet close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

    If the fopen() function is successfully executed, it returns a “file pointer” or “handle” resource bound to the file stream. However, if it fails, it returns false with E_WARNING being emitted.

    $handle=fopen('a.txt, 'r');var_dump($handle);

    If the file exists in the current directory, the success is shown by the output −

    resource(5) of type (stream)
    

    If not, you get the following error message −

    Warning: fopen(a.txt): Failed to open stream: 
    No such file or directory in a.php on line 2
    bool(false)
    

    Examples

    The following examples show different usages of the fopen() function −

    <?php
       // Opening a file for writing   
       $handle = fopen("hello.txt", "w");
    
       $handle = fopen("c:/xampp/htdocs/welcome.png", "rb");
    
       // Opening a file for reading
       $handle = fopen("http://localhost/hello.txt", "r");
    ?>

    Note that this function may also succeed when the filename is a directory. In that case, you may need to use the is_dir() function to check whether it is a file before doing any read/write operations.

    Once a file is opened, you can write data in it with the help of functions such as fwrite() or fputs(), and read data from it with fread() and fgets() functions.

    Closing a File

    It is always recommended to close the open stream referenced by the handle −

    fclose($handle);

    Important Notes

    Here are some important point you need to keep in mind while working with file Handling −

    • Always make sure the file opened successfully. It is a good idea to verify that the file opened successfully. If it did not, you can accept the error carefully.
    • When you are finished reading or writing, always use fclose() to close your file. This releases system resources.
  • File Handling

    In PHP, a file is a resource object, from which data can be read or written to in a linear fashion. The term “file handling” refers to a set of functions in PHP that enable read/write operations on disk files with PHP code.

    A file object is classified as a stream. Any resource on which linear read/write operations are done is a stream. Other stream-like objects are the TCP sockets, standard input stream, i.e., a system keyboard represented by “php://stdin”, the standard output stream represented by “php://stdout”, and the error stream “php://stderr”.

    Note − The constants STDIN, STDOUT, and STDERR stand for the respective standard streams.

    Although PHP is regarded as a server-side scripting language for developing web applications, PHP also has a command-line interface to perform console IO operations.

    What is File Handling?

    File handling refers to the process of managing files on a server. In PHP, this includes −

    • Open a file.
    • Reading data from a file.
    • Writing data into a file.
    • Close the file.

    Why Use File Handling?

    File handling is important since it allows you to −

    • Store user information.
    • Manage logs.
    • Create configuration files.
    • Generate reports.

    Now, let us look at how to manage files in PHP.

    Opening a File

    To open a file in PHP, we use the fopen() function. This function requires two parameters: the path to the file and the mode (what you want to do with the file).

    Here are some common modes you might use −

    • “r”: Read only.
    • “w”: Write only (truncates the file to zero length).
    • “a”: Write only (append).
    • “r+”: Read and write.

    Example: Opening a File

    Here is the example showing how you can open a file using the PHP file handling −

    // Opens the file for reading$file=fopen("/PHP/PhpProjects/myfile.txt","r");if($file){echo"File opened successfully!";}else{echo"Error opening the file.";}

    Output

    Here is the outcome of the following code −

    File opened successfully!
    

    Reading from a File

    When you have opened a file then you can read its contents with the help of ‘fgets() or fread()’.

    • fgets($file): Reads a single line from the file.
    • fread($file, $length): Reads a specified number of bytes.

    Example: Reading a File

    Here is the example showing how you can read a file after opening it in PHP.

    <?php
       $file = fopen("/PHP/PhpProjects/myfile.txt", "r");
    
       while (($line = fgets($file)) !== false) {
    
      // Prints each line
      echo $line . "\n"; 
    } fclose($file); ?>

    Output

    This will create the below output −

    Hello this is an example of 
    
    PHP File Handling.
    

    Writing to a File

    To write data to a file you will have to open it in write mode (“w” or “a”). Then you can use ‘fwrite()’.

    Example: Writing to a File

    Here is the example showing how you can write content in a file −

    <?php
       // Opens the file for appending
       $file = fopen("/PHP/PhpProjects/myfile.txt", "a");
    
       if ($file) {
    
      // Write a line
      fwrite($file, "\nThis is a new line in the file.\n"); 
      
      // Close the file
      fclose($file); 
      echo "Data written to the file successfully!";
    } else {
      echo "Error opening the file.";
    } ?>

    Output

    Here is the output of the above code −

    Data written to the file successfully!
    

    Here is the updated content of the file myfile.txt −

    Hello this is an example of 
    
    PHP File Handling.
    
    This is a new line in the file.
    

    Closing a File

    When you are finished reading or writing to a file, use the fclose() method to properly close it. This helps free up system resources.

    Example: Closing a File

    Below is the example showing how you can use the fclose() function to close the opened file −

    <?php
       $file = fopen("/PHP/PhpProjects/myfile.txt", "r");
       // Do something with the file
       // Close the file
       fclose($file); 
    
       echo "The file has been closed.";
    ?>

    Output

    This will generate the below output −

    The file has been closed.
    

    File Handling Errors

    It is very important to handle errors when you are working with files. Use conditional statements to check if the file was opened successfully.

    Example: Error Handling

    You can follow the below example to handle errors while working with file handling −

    <?php
       $file = fopen("nonexistent.txt", "r");
       if (!$file) {
    
      echo "Error: File does not exist.";
    } else {
      // Read the file
      fclose($file);
    } ?>

    Output

    It will produce the following output −

    Error: File does not exist.
    

    Example: Get List of Stream Wrappers

    PHP supports a variety of stream protocols for stream related functions such as fopen(), file_exists(), etc. Use php_get_wrappers() function to get a list of all the registered wrappers.

    <?php
       print_r(stream_get_wrappers());
    ?>

    Output

    It will generate the following output −

    Array
    (
       [0] => php
       [1] => file
       [2] => glob
       [3] => data
       [4] => http
       [5] => ftp
       [6] => zip
       [7] => compress.zlib
       [8] => compress.bzip2
       [9] => https
       [10] => ftps
       [11] => phar
    )
    

    The streams are referenced as “scheme://target”. For instance, the file stream is “file://xyz.txt”.

    The input data from the console is stored in the computer’s main memory (RAM) until the application is running. Thereafter, the memory contents from RAM are erased.

    We would like to store it in such a way that it can be retrieved whenever required in a persistent medium such as a disk file. Hence, instead of the standard streams (keyboard for input and the display device for output), we will use the disk files for reading the data, and destination for storing the data.

    In addition to the read and write modes as used in the above example (IO operations with standard streams), the file stream can be opened in various other modes like “r+” and “w+” for simultaneous read/write, “b” for binary mode, etc.

    To open a disk file for reading and obtain its reference pointer, use the fopen() function.

    $handle=fopen('file://'.__DIR__.'/data.txt','r');

    The “file://” scheme is the default. Hence, it can be easily dropped, especially when dealing with local files.

    Note − It is always recommended to close the stream that was opened. Use the fclose() function for this purpose.

    fclose($handle);

    PHP has several built-in functions for performing read/write operations on the file stream. In the subsequent chapters, we shall explore the filesystem functions.

  • $_SESSION

    One of the superglobal variables in PHP, $_SESSION is an associative array of session variables available in the current script. $HTTP_SESSION_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated.

    What is a Session?

    A Session is an alternative way to make data accessible across the pages of an entire website. It is the time duration between the time a user establishes a connection with a server and the time the connection is terminated. During this interval, the user may navigate to different pages. Many times, it is desired that some data is persistently available across the pages. This is facilitated by session variables.

    A session creates a file in a temporary directory on the server where the registered session variables and their values are stored. This data will be available to all the pages on the site during that visit.

    The server assigns a unique SESSION_ID to each session. Since HTTP is a stateless protocol, data in session variables is automatically deleted when the session is terminated.

    How Sessions Work?

    Here is the way how sessions work −

    • The server assigns a unique SESSION_ID to each user.
    • This ID is stored in a temporary file on the server.
    • The session data is accessible from all pages until the session is terminated.

    Starting a Session

    In order to enable access to session data, the session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

    session_start(array$options=[]):bool

    This function returns true if a session was successfully started, else it returns false.

    Creating and Using Session Variables

    To create a new session variable, add a key-value pair in the $_SESSION array −

    $_SESSION["var"]=value;

    To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions.

    echo$_SESSION["var"];

    To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION −

    foreach($_SESSIONas$key=>$val)echo$key."=>".$val;

    Deleting Session Variables

    To manually clear all the session data, there is session_destroy() function. A specific session variable may also be released by calling the unset() function.

    unset($_SESSION["var"]);

    List of Session Functions

    In PHP, there are many built-in functions for managing the session data.

    Session FunctionsDescription
    session_abortDiscard session array changes and finish session
    session_cache_expireReturn current cache expire
    session_cache_limiterGet and/or set the current cache limiter
    session_commitAlias of session_write_close
    session_create_idCreate new session id
    session_decodeDecodes session data from a session encoded string
    session_destroyDestroys all data registered to a session
    session_encodeEncodes the current session data as a session encoded string
    session_gcPerform session data garbage collection
    session_get_cookie_paramsGet the session cookie parameters
    session_idGet and/or set the current session id
    session_is_registeredFind out whether a global variable is registered in a session
    session_module_nameGet and/or set the current session module
    session_nameGet and/or set the current session name
    session_regenerate_idUpdate the current session id with a newly generated one
    session_register_shutdownSession shutdown function
    session_registerRegister one or more global variables with the current session
    session_resetRe-initialize session array with original values
    session_save_pathGet and/or set the current session save path
    session_set_cookie_paramsSet the session cookie parameters
    session_set_save_handlerSets user-level session storage functions
    session_startStart new or resume existing session
    session_statusReturns the current session status
    session_unregisterUnregister a global variable from the current session
    session_unsetFree all session variables
    session_write_closeWrite session data and end session

    Example: Managing User Data with PHP Sessions

    The following PHP script renders an HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables.

    Save this code as “test.php” in the document root folder, and open it in a client browser. Enter the data and press the Submit button.

    <html><head><title>PHP Sessions: How to Use $_SESSION to Manage User Data</title><meta name="keywords" content="PHP Sessions, PHP $_SESSION, Manage User Data in PHP, PHP session_start, session variables, PHP session tutorial"></head><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><h3>User's ID: <input type="text" name="ID"/></h3><h3>Your Name: <input type="text" name="name"/></h3><h3>Enter Age: <input type="text" name="age"/></h3><input type="submit" value="Submit"/></form><?php
    
      session_start();
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $_SESSION['UserID'] = $_POST['ID'];
         $_SESSION['Name'] = $_POST['name'];
         $_SESSION['age'] = $_POST['age'];
      }
      echo "Following Session Variables Created: \n";
      foreach ($_SESSION as $key=&gt;$val)
      echo "&lt;h3&gt;" . $key . "=&gt;" . $val . "&lt;/h3&gt;";
      echo "&lt;br/&gt;" . '&lt;a href="hello.php"&gt;Click Here&lt;/a&gt;';
    ?></body></html>

    When you click the “Submit” button, it will show a list of all the session variables created −

    PHP $ SESSION 1

    Next, have the following script in the “hello.php” file and save it.

    <?php
    session_start();
       echo "<h2>Following Session variables Read:</h2>";
       foreach ($_SESSION as $key=>$val)
       echo "<h3>" . $key . "=>" . $val . "</h3>";
    ?>

    Now, follow the link on the “test.php” page to navigate to “hello.php”. It will show the session variables that are read −

    PHP $ SESSION 2

  • $_COOKIE

    The PHP superglobal $_COOKIE stores the variables passed to the current PHP script along with the HTTP request in the form of cookies. $HTTP_COOKIE_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated.

    What is a Cookie?

    Cookies are text files stored by a server on the client computer and they are kept for tracking purpose. PHP transparently supports HTTP cookies. Cookies are usually set in an HTTP header. JavaScript can also sets a cookie directly on a browser.

    The server script sends a set of cookies to the browser. It stores this information on the local machine for future use. Next time, when the browser sends any request to the web server, it sends those cookies information to the server and the server uses that information to identify the user.

    The setcookie() Function

    PHP provides the setcookie function to create a cookie object to be sent to the client along with the HTTP response.

    setcookie(name, value, expire, path, domain, security);

    Parameters

    Here are the parameters of setcookie() function −

    • Name − Name of the cookie stored.
    • Value − This sets the value of the named variable.
    • Expiry − This specifies a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
    • Path − Directories for which the cookie is valid.
    • Domain − Specifies the domain name in very large domains.
    • Security − 1 for HTTPS. Default 0 for regular HTTP.

    How to Set Cookies

    Take a look at the following example. This script sets a cookie named username if it is not already set.

    Example

    <?php
       if (isset($_COOKIE['username'])) {
    
      echo "&lt;h2&gt;Cookie username already set: " . $_COOKIE['username'] . "&lt;/h2&gt;";
    } else {
      setcookie("username", "Mohan Kumar");
      echo "&lt;h2&gt;Cookie username is now set.&lt;/h2&gt;";
    } ?>

    Run this script from the document root of the Apache server. You should see this message as the output −

    Cookie username is now set
    

    If this script is re-executed, the cookie is now already set.

    Cookie username already set: Mohan Kumar
    

    Example

    To retrieve cookies on subsequent visit of client −

    <?php
       $arr=$_COOKIE;
       foreach ($arr as $key=>$val);
       echo "<h2>$key => $val </h2>";
    ?>

    The browser will display the following output −

    Username => Mohan Kumar
    

    How to Read a Cookie

    We can use the $_COOKIE variable to read a cookie. The isset() function is used to check if the cookie exists. And the $_COOKIE[“username”] retrieves the cookie value.

    <?php
       if(isset($_COOKIE["username"])) {
    
      echo "Welcome " . $_COOKIE["username"];
    } else {
      echo "Cookie is not set.";
    } ?>

    How to Remove Cookies

    To delete a cookie, set the cookie with a date that has already expired, so that the browser triggers the cookie removal mechanism.

    <?php
       setcookie("username", "", time() - 3600);
       echo "<h2>Cookie username is now removed</h2>";
    ?>

    The browser will now show the following output −

    Cookie username is now removed
    

    Setting Cookies Using the Array Notation

    You may also set the array cookies by using the array notation in the cookie name.

    setcookie("user[three]","Guest");setcookie("user[two]","user");setcookie("user[one]","admin");

    If the cookie name contains dots (.), then PHP replaces them with underscores (_).

    When to Use Cookies in PHP

    You can use cookies in PHP to save small amounts of data on the user’s browser for later use! Let’s discuss some common situations −

    • User Authentication (Login Systems)
    • Remember User Preferences
    • Tracking User Activity
    • Shopping Carts
    • Session Management
    • Personalized Greetings or Messages
  • $_ENV

    $_ENV is a superglobal variable in PHP. It is an associative array that stores all the environment variables available in the current script. $HTTP_ENV_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated.

    The environment variables are imported into the global namespace. Most of these variables are provided by the shell under which the PHP parser is running. Hence, the list of environment variables may be different on different platforms.

    This array ($_ENV) also includes CGI variables in case PHP is running as a server module or a CGI processor.

    We can use the foreach loop to display all the environment variables available −

    <?php
       foreach ($_ENV as $k=>$v)
       echo $k . " => " . $v . "<br>";
    ?>

    List of Environment Variables

    On a Windows OS and with XAMPP server, you may get the list of environment variables as follows −

    VariableValue
    ALLUSERSPROFILEC:\ProgramData
    APPDATAC:\Users\user\AppData\Roaming
    CommonProgramFilesC:\Program Files\Common Files
    CommonProgramFiles(x86)C:\Program Files (x86)\Common Files
    CommonProgramW6432C:\Program Files\Common Files
    COMPUTERNAMEGNVBGL3
    ComSpecC:\WINDOWS\system32\cmd.exe
    DriverDataC:\Windows\System32\Drivers\DriverData
    HOMEDRIVEC −
    HOMEPATH\Users\user
    LOCALAPPDATAC:\Users\user\AppData\Local
    LOGONSERVER\\GNVBGL3
    MOZ_PLUGIN_PATHC:\Program Files (x86)\ Foxit Software\ Foxit PDF Reader\plugins\
    NUMBER_OF_PROCESSORS8
    OneDriveC:\Users\user\OneDrive
    OneDriveConsumerC:\Users\user\OneDrive
    OSWindows_NT
    PathC:\Python311\Scripts\;C:\Python311\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\ v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\xampp\php;C:\Users\user\AppData\Local\Microsoft\ WindowsApps;C:\VSCode\Microsoft VS Code\bin
    PATHEXT.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE; .WSF;.WSH;.MSC;.PY;.PYW
    PROCESSOR_ARCHITECTUREAMD64
    PROCESSOR_IDENTIFIERIntel64 Family 6 Model 140 Stepping 1, GenuineIntel
    PROCESSOR_LEVEL6
    PROCESSOR_REVISION8c01
    ProgramDataC:\ProgramData
    ProgramFilesC:\Program Files
    ProgramFiles(x86)C:\Program Files (x86)
    ProgramW6432C:\Program Files
    PSModulePathC:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\ Modules
    PUBLICC:\Users\Public
    SystemDriveC −
    SystemRootC:\WINDOWS
    TEMPC:\Users\user\AppData\Local\Temp
    TMPC:\Users\user\AppData\Local\Temp
    USERDOMAINGNVBGL3
    USERDOMAIN_ROAMINGPROFILEGNVBGL3
    USERNAMEuser
    USERPROFILEC:\Users\user
    windirC:\WINDOWS
    ZES_ENABLE_SYSMAN1
    __COMPAT_LAYERRunAsAdmin Installer
    AP_PARENT_PID10608

    You can access the value of individual environment variable too. This code fetches the PATH environment variable −

    <?php
       echo "Path: " . $_ENV['Path'];
    ?>

    It will produce the following output −

    Path:
    C:\Python311\Scripts\;C:\Python311\;C:\WINDOWS\system32;
    C:\WINDOWS;C:\WINDOWS\System32\Wbem;
    C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
    C:\WINDOWS\System32\OpenSSH\;C:\xampp\php;
    C:\Users\mlath\AppData\Local\Microsoft\WindowsApps;
    C:\VSCode\Microsoft VS Code\bin
    

    Note − The $_ENV array may yield empty result, depending on “php.ini” setting “variables_order”. You may have to edit the “php.ini” file and set variables_order=”EGPCS” instead of variables_order=”GPCS” value.

    The getenv() Function

    The PHP library provides the getenv() function to retrieve the list of all the environment variables or the value of a specific environment variable.

    The following script displays the values of all the available environment variables −

    <?php
       $arr=getenv();
       foreach ($arr as $key=>$val)
       echo "$key=>$val";
    ?>

    To obtain the value of a specific variable, use its name as the argument for the getenv() function −

    <?php
       echo "Path: " . getenv("PATH");
    ?>

    The putenv() Function

    PHP also provides the putenv() function to create a new environment variable. The environment variable will only exist for the duration of the current request.

    Changing the value of certain environment variables should be avoided. By default, users will only be able to set the environment variables that begin with “PHP_” (e.g. PHP_FOO=BAR).

    The “safe_mode_protected_env_vars” directive in “php.ini” contains a comma-delimited list of environment variables that the end user won’t be able to change using putenv().

    <?php
       putenv("PHP_TEMPUSER=GUEST");
       echo "Temp user: " . getenv("PHP_TEMPUSER");
    ?>

    The browser will display the following output −

    Temp user: GUEST

  • $_FILES

    $_FILES is one of the ‘superglobal’, or automatic global, variables in PHP. It is available in all scopes throughout a script. The variable $_FILES is an associative array containing items uploaded via HTTP POST method.

    A file is uploaded when a HTML form contains an input element with a file type, its enctype attribute set to multipart/form-data, and the method attribute set to HTTP POST method.

    $HTTP_POST_FILES also contains the same information, but it is not a superglobal, and it has now been deprecated.

    HTML File Input Element for File Upload

    The following HTML script contains a form with input element of file type −

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

    This “input type” renders a button captioned as file. When clicked, a file dialogbox pops up. You can choose a file to be uploaded.

    The PHP script on the server can access the file data in $_FILES variable.

    Properties of $_FILES

    The $_FILES array contains the following properties −

    • $_FILES[‘file’][‘name’] − The original name of the file that the user has chosen to be uploaded.
    • $_FILES[‘file’][‘type’] − The mime type of the file. An example would be “image/gif”. This mime type is however not checked on the PHP side.
    • $_FILES[‘file’][‘size’] − The size, in bytes, of the uploaded file.
    • $_FILES[‘file’][‘tmp_name’] − The temporary filename of the file in which the uploaded file was stored on the server.
    • $_FILES[‘file’][‘full_path’] − The full path as submitted by the browser. Available as of PHP 8.1.0.
    • $_FILES[‘file’][‘error’] − The error code associated with this file upload.

    PHP File Upload Error Codes

    The error codes are enumerated as below −

    Error CodesDescription
    UPLOAD_ERR_OK (Value=0)There is no error, the file uploaded with success.
    UPLOAD_ERR_INI_SIZE (Value=1)The uploaded file exceeds the upload_max_filesize directive in php.ini.
    UPLOAD_ERR_FORM_SIZE (Value=2)The uploaded file exceeds the MAX_FILE_SIZE.
    UPLOAD_ERR_PARTIAL (Value=3)The uploaded file was only partially uploaded.
    UPLOAD_ERR_NO_FILE (Value=4)No file was uploaded.
    UPLOAD_ERR_NO_TMP_DIR (Value=6)Missing a temporary folder.
    UPLOAD_ERR_CANT_WRITE (Value=7)Failed to write file to disk.
    UPLOAD_ERR_EXTENSION (Value=8)A PHP extension stopped the file upload.

    Single File Upload Form

    The following “test.html” contains a HTML form whose enctype is set to multiform/form-data. It also has an input file element which presents a button on the form for the user to select file to be uploaded. Save this file in the document root folder of your Apache server.

    <html><body><form action="hello.php" method="POST" enctype="multipart/form-data"><p><input type="file" name="file"></p><p><input type ="submit" value="submit"></p></form></body></html>

    The above HTML renders a button named “Choose File” in the browser window. To open a file dialog box, click the “Choose File” button. As the name of selected file appears, click the submit button.

    PHP $ Files 1

    Server-Side Script to Handle Single File Upload

    The server-side PHP script (upload.php) in the document root folder reads the variables $_FILES array as follows −

    <?php
       echo "Filename: " . $_FILES['file']['name']."<br>";
       echo "Type : " . $_FILES['file']['type'] ."<br>";
       echo "Size : " . $_FILES['file']['size'] ."<br>";
       echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
       echo "Error : " . $_FILES['file']['error'] . "<br>";
    ?>

    It will produce the following output −

    Filename: abc.txt
    Type : text/plain
    Size : 556762
    Temp name: C:\xampp\tmp\phpD833.tmp
    Error : 0
    

    Multiple File Upload Form

    In PHP, you can upload multiple files using the HTML array feature −

    <html><body><form action="hello.php" method="POST" enctype="multipart/form-data"><input type="file" name="files[]"/><input type="file" name="files[]"/><input type ="submit" value="submit"/></form></body></html>

    Now, change the PHP script (hello.php) to −

    <?php
       foreach ($_FILES["files"]["name"] as $key => $val) {       
    
      echo "File uploaded: $val &lt;br&gt;";
    } ?>

    The browser will show multiple “Choose File” buttons. After you upload the selected files by clicking the “Submit” button, the browser will show the names of files in response to the URL http://localhost/hello.html as shown below −

    PHP $ Files 2

  • $_GET

    $_GET is one of the superglobals in PHP. It is an associative array of variables passed to the current script via the query string appended to the URL of HTTP request. Note that the array is populated by all requests with a query string in addition to GET requests.

    $HTTP_GET_VARS contains the same initial information, but that has now been deprecated.

    By default, the client browser sends a request for the URL on the server by using the HTTP GET method. A query string attached to the URL may contain key value pairs concatenated by the “&” symbol. The $_GET associative array stores these key value pairs.

    How Does $_GET Work?

    When someone visits a URL like this −

    http://localhost/hello.php?name=Amit&age=22
    

    PHP can access the values using $_GET.

    <?php
       echo "Hello, " . $_GET['name'] . "!";
       echo " You are " . $_GET['age'] . " years old.";
    ?>

    Output

    Here is the outcome of the following code −

    Hello, Amit! You are 22 years old.
    

    Example

    Save the following script in the document folder of Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder.

    <?php
       echo "<h3>First Name: " . $_REQUEST['first_name'] . "<br />" . 
       "Last Name: " . $_REQUEST['last_name'] . "</h3>";
    ?>

    Start the XAMPP server, and enter “http://localhost/hello.php?first_name=Mukesh&last_name=Sinha” as the URL in a browser window. You should get the following output −

    PHP $ GET 1

    The $_GET array is also populated when a HTML form data is submitted to a URL with GET action.

    Under the document root, save the following script as “hello.html” −

    <html><body><form action="hello.php" method="get"><p>First Name: <input type="text" name="first_name"/></p><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form></body></html>

    In your browser, enter the URL “http://localhost/hello.html” −

    PHP $ GET 2

    You should get a similar output in the browser window −

    PHP $ GET 3

    HTML Special Characters

    In the following example, htmlspecialchars() is used to convert characters in HTML entities −

    CharacterReplacement
    & (ampersand)&amp;
    ” (double quote)&quot;
    ‘ (single quote)&#039; or &apos;
    < (less than)&lt;
    > (greater than)&gt;

    Assuming that the URL in the browser is “http://localhost/hello.php?name=Suraj&age=20” −

    <?php
       echo  "Name: " . htmlspecialchars($_GET["name"]) . "";
       echo  "Age: " . htmlspecialchars($_GET["age"]) . "<br/>";
    ?>

    It will produce the following output −

    Name: Suraj
    Age: 20