Author: Saim Khalid

  • Session Options

    From PHP version 7 onwards, the session_start() function accepts an array of options to override the session configuration directives set in “php.ini”. The [session] session in “php.ini” defines the default values of various options.

    The options, if provided, are in the form of an associative array of options that will override the currently set session configuration directives. The keys should not include the “session.” prefix.

    Start an HTTP session

    For example, you may start the HTTP session with the two session options defined as the parameters of session_start() function −

    <?php
       session_start([
    
      'cache_limiter' =&gt; 'private',
      'read_and_close' =&gt; true,
    ]); ?>

    Configurable Options of an HTTP Session

    Some of the configurable options of an HTTP session in PHP are as follows −

    session_name

    It specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID.

    session_name('MY_SESSION');session_start();

    session.save_handler

    It defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files.

    ini_set('session.save_handler','files');session_start();

    session.auto_start

    It specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).

    ini_set('session.auto_start',1);

    session.cookie_lifetime

    It specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means “until the browser is closed.” Defaults to 0.

    // 1 hourini_set('session.cookie_lifetime',3600);session_start();

    session.cache_limiter

    It specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache.

    ini_set('session.cache_limiter','private');session_start();

    session.sid_length

    It allows you to specify the length of session ID string. Session ID length can be between 22 to 256. The default is 32.

    ini_set('session.sid_length',64);session_start();echosession_id();

    session.upload_progress.enabled

    It enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.

    ini_set('session.upload_progress.enabled',1);session_start();

    session.lazy_write

    When it is set to 1, it means that the session data is only rewritten if it changes. Defaults to 1, enabled.

    ini_set('session.lazy_write',1);session_start();$_SESSION['key']='value';

    PHP session options provide extensive control over user sessions. Understanding and using these options allows you to design more secure and versatile web apps. To secure user information, always start your session with session_start() and handle session data properly.

  • Sessions

    A web session is the time duration between the time a user establishes connection with a server and the time the connection is terminated. Along with the cookies, the session variables make the data accessible across the various pages of an entire website.

    During a session, the website maintains information about the user’s actions and preferences. The session data is populated in a super-global associative array $_SESSION.

    To start a new session in PHP, you need to call the session_start() function.

    Starting a Session

    In order to enable access to session data, 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, otherwise false.

    PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers.

    The session_id() function sets or retrieves a unique session ID.

    session_id(?string$id=null):string|false

    PHP will generate a random session ID, if the $id parameter is not given. You may specify your own ID instead. The function returns the session id for the current session or the empty string if there is no current session. On failure, it returns false.

    Example

    Take a look at the following example −

    <?php  
       // Starting the session
       session_start();
       $id = session_id();
       echo "Session Id: ".$id ;
    ?>

    The browser will show a random string as the output −

    Session Id: mi3976f8ssethe9f04vq1ag6it
    

    A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.

    PHP Sessions 1

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

    The location of the temporary file is determined by a setting in the “php.ini” file called “session.save_path”.

    Handling Session Variables

    Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.

    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;

    Example

    The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.

    Use the isset() function to check if a session variable is already set or not.

    The following PHP script starts a session when it runs for the first time, and sets a session variable named counter. When the client revisits the same URL again, since the session variable is already set, the counter is incremented.

    <?php
       session_start();
       if( isset( $_SESSION['counter'] ) ) {
    
      $_SESSION['counter'] += 1;
    } else {
      $_SESSION['counter'] = 1;
    } $msg = "Number of visits in this session: ". $_SESSION['counter']; ?><?php echo "$msg"; ?>

    Refresh the browser multiple times to simulate repeated visits. The browser displays the counter −

    Number of visits in this session: 5
    

    Destroying a PHP Session

    A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

    Here is an example to unset a single variable −

    <?php
       unset($_SESSION['counter']);
    ?>

    Here is the call which will destroy all the session variables −

    <?php
       session_destroy();
    ?>

    You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

    Example

    The following PHP script renders a 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.

    <html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><h3>User's ID: <input type="text" name="ID"/></h3><h3>User's Name: <input type="text" name="name"/></h3><h3>User Type: <input type="text" name="type"/></h3><input type="submit" value="Submit" /></form><?php
    
      session_start();
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $_SESSION['ID'] = $_POST['ID'];
         $_SESSION['Name'] = $_POST['name'];
         $_SESSION['type'] = $_POST['type'];
         echo "&lt;h2&gt;Following Session variables Created&lt;/h2&gt;";
         foreach ($_SESSION as $key=&gt;$val) {
            echo "&lt;h3&gt;" . $key . "=&gt;" . $val . "&lt;/h3&gt;";
         }
         echo "&lt;a href='test.php'&gt;&lt;b&gt;Click Here&lt;/b&gt;&lt;/a&gt;";
      }
    ?></body></html>

    Save this code as “hello.php” in the document root folder, and open it in a client browser.

    PHP Sessions 2

    Press the Submit button. The browser will show the session variables created −

    PHP Sessions 3

    The browser navigates to another page by following the link shown. It reads back the session variables.

    PHP Sessions 3
  • Cookies

    The worldwide web is powered by HTTP protocol, which is a stateless protocol. The mechanism of Cookies helps the server maintain the information of previous requests. PHP transparently supports HTTP cookies.

    Understanding Cookies in PHP

    • When a client first sends its request, the server includes a small piece of data along with its response as cookies. PHP provides the setcookie() method to inject cookies in the response.
    • This cookie data is stored in the client’s machine as text files. On subsequent visits of the same client, these cookies are included as a part of the request header.
    • The server populates the PHP superglobal variable “$_COOKIE” with all the cookies present in the client request.

    This chapter will teach you how to set cookies, how to access them and how to delete them.

    The Anatomy of a Cookie

    Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −

    HTTP/1.1 200 OK
    Date: Fri, 04 Feb 2000 21:03:38 GMT
    Server: Apache/1.3.9 (UNIX) PHP/4.0b3
    Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
    
                 path=/; domain=tutorialspoint.com
    Connection: close Content-Type: text/html

    As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date.

    If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser’s headers might look something like this −

    GET / HTTP/1.0
    Connection: Keep-Alive
    User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
    Host: zink.demon.co.uk:1126
    Accept: image/gif, */*
    Accept-Encoding: gzip
    Accept-Language: en
    Accept-Charset: iso-8859-1,*,utf-8
    Cookie: name=xyz
    

    A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].

    How to Set a Cookie in PHP?

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

    Syntax

    Here is the syntax for cookie in PHP −

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

    Parameters

    Here is the detail of all the arguments −

    • Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
    • Value − This sets the value of the named variable and is the content that you actually want to store.
    • Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
    • Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
    • Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
    • Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

    Example

    The PHP script give below checks if the cookie named username is already set, and retrieves its value, if so. If not, a new cookie username is set.

    <?php
       if (isset($_COOKIE['username'])) {
    
      echo "&lt;h2&gt;Cookie username already set:" . $_COOKIE['username'] . "&lt;/h2&gt;";
    } else {
      setcookie("username", "MohanKumar");
      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 −

    Cookie username is now set
    

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

    Cookie username already set: MohanKumar
    

    Your browser’s developer tool is a very useful facility. You can set, retrieve and delete cookies with its help. The cookie set by the above program can be viewed under the Application tab of the browser’s developer tools.

    PHP Cookies

    foreach loop as below retrieves all the cookies −

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

    The following script contains an HTML form. It sends the form data to setcookie.php script, that sets the cookies with the use of data retrieved from the $_POST array.

    The HTML form is rendered by the following code −

    <form action="setcookie.php" method="POST"><input type="text" name="name"><input type="text" name="age"><input type="submit" name="Submit"></form>

    SetCookie.php reads the form data and sets the cookies.

    if(isset($_POST["submit"]){setcookie("name",$_POST["name"]);setcookie("age",$_POST["age"]);}

    With another getcookie.php code, we can retrieve the cookies set.

    if(isset($_COOKIE["name"])echo"Cookie: name => ".$_COOKIE["name"]."<br>";if(isset($_COOKIE["age"])echo"Cookie: age => ".$_COOKIE["age"]."<br>";

    Accessing Cookies with PHP

    PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

    <?php
       echo $_COOKIE["name"]. "<br />";
    
       /* is equivalent to */
       echo $HTTP_COOKIE_VARS["name"]. "<br />";
    
       echo $_COOKIE["age"] . "<br />";
    
       /* is equivalent to */
       echo $HTTP_COOKIE_VARS["age"] . "<br />";
    ?>

    You can use isset() function to check if a cookie is set or not.

    <?php
       if( isset($_COOKIE["name"]))
    
      echo "Welcome " . $_COOKIE["name"] . "&lt;br /&gt;";
    else
      echo "Sorry... Not recognized" . "&lt;br /&gt;";
    ?>

    Deleting the Cookies

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

    Example

    Take a look at the following example −

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

    The browser shows the following response −

    Cookie username is now removed
    

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

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

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

    Although the main purpose behind the concept of cookies is to help web developers provide a more personalized and convenient user experience, it may pose a risk to your privacy and personal information.

    In some cases, the application may deny you full access you don’t accept their cookies. In such cases, periodically clearing the cookie related data from your browser’s cache is advised.

  • File Uploading

    One of the common features required in a typical PHP web application is the provision of letting the user upload files. Uploading files from a client is very easy in PHP. In this chapter, we shall learn how to use PHP script for the file upload process.

    How to Upload a File?

    The process of uploading a file follows these steps −

    • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
    • The user clicks the browse button and selects a file to upload from the local PC.
    • The full path to the selected file appears in the text filed then the user clicks the submit button.
    • The selected file is sent to the temporary directory on the server.
    • The PHP script that was specified as the form handler in the form’s action attribute checks that the file has arrived and then copies the file into an intended directory.
    • The PHP script confirms the success to the user.

    Configuring File Upload Settings in PHP

    In order to perform this activity, we must first ensure that configuration settings related to file upload are enabled in “php.ini”.

    Open the “php.ini” file and ensure that the following settings are enabled by removing the leading semicolon (;) symbol in file_uploads, upload_tmp_dir, upload_max_filesize and max_file_uploads parameters −

    ;;;;;;;;;;;;;;;;; File Uploads ;;;;;;;;;;;;;;;;;; Whether to allow HTTP file uploads.; http://php.net/file-uploads
    file_uploads=On
    
    ; Temporary directory forHTTP uploaded files(will usesystem;defaultif not specified).; http://php.net/upload-tmp-dir
    upload_tmp_dir="C:\xampp\tmp"; Maximum allowed size for uploaded files.; http://php.net/upload-max-filesize
    upload_max_filesize=40M
    
    ; Maximum number of files that can be uploaded via a single request
    max_file_uploads=20

    It is necessary that the folders for both temporary and final locations have permissions set that enable file writing. If either is set to be read-only then process will fail.

    Creating a File Upload Form

    Next, we need to design a HTML form for file upload. The form’s method attribute must be POST and enctype must be multipart/form-data. Use the input type as file to let the user browse and select the file to be uploaded.

    <h2>File Upload Form</h2><form method = "POST" action = "uploadfile.php" enctype="multipart/form-data"><label for="file">File name:</label><input type="file" name="uploadfile" /><input type="submit" name="submit" value="Upload" /></form>

    Creating an Upload Script

    The uploadfile.php script receives the uploaded file. The file data is collected in a suparglobal variable $_FILES. Fetch the name, file type, size and the tmp_name attributes of the uploaded file.

    The move_uploaded_file() function copies the selected file to the document folder.

    <?php
       echo "<b>File to be uploaded: </b>" . $_FILES["uploadfile"]["name"] . "<br>";
       echo "<b>Type: </b>" . $_FILES["uploadfile"]["type"] . "<br>";
       echo "<b>File Size: </b>" . $_FILES["uploadfile"]["size"]/1024 . "<br>";
       echo "<b>Store in: </b>" . $_FILES["uploadfile"]["tmp_name"] . "<br>";
    
       if (file_exists($_FILES["uploadfile"]["name"])){
    
      echo "&lt;h3&gt;The file already exists&lt;/h3&gt;";
    } else {
      move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $_FILES["uploadfile"]["name"]);
      echo "&lt;h3&gt;File Successfully Uploaded&lt;/h3&gt;";
    } ?>

    Assuming that both the files myform.php and uploadfile.php are stored in the document folder.

    Open “myform.php” in the browser (http://localhost/myform.php) −

    PHP File Uploading 1

    Click the File button, browse to the desired file to be uploaded, and click the Upload button.

    The server responds with the following message −

    PHP File Uploading 2

    Error Handling

    Handling upload errors is important when giving feedback to users. PHP returns an error code for each file upload, which you can check using $_FILES[‘uploadfile’].[‘error’].

    if($_FILES["uploadfile"]["error"]>0){switch($_FILES["uploadfile"]["error"]){caseUPLOAD_ERR_INI_SIZE:echo"<h3>The uploaded file exceeds the upload_max_filesize directive in php.ini.</h3>";break;caseUPLOAD_ERR_FORM_SIZE:echo"<h3>The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form.</h3>";break;caseUPLOAD_ERR_PARTIAL:echo"<h3>The file was only partially uploaded.</h3>";break;caseUPLOAD_ERR_NO_FILE:echo"<h3>No file was uploaded.</h3>";break;caseUPLOAD_ERR_NO_TMP_DIR:echo"<h3>Missing a temporary folder.</h3>";break;caseUPLOAD_ERR_CANT_WRITE:echo"<h3>Failed to write file to disk.</h3>";break;caseUPLOAD_ERR_EXTENSION:echo"<h3>File upload stopped by extension.</h3>";break;default:echo"<h3>Unknown upload error.</h3>";}}else{move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$target_file);echo"<h3>File Successfully Uploaded</h3>";}

    Output

    Here is the output of the above error handling −

    No file was uploaded.

  • GET & POST

    Since PHP is mostly used for web application development, the data sent by the browser client is mainly with the GET and POST types of HTTP request methods. The HTTP protocol also defines other methods for sending the request to the server. They are PUT, DELETE, HEAD and OPTIONS (in addition to GET and POST methods). In this chapter, we shall concentrate on how PHP handles the GET and POST methods.

    The GET Method

    The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

    http://www.test.com/index.htm?name1=value1&name2=value2
    
    • The GET method produces a long string that appears in your server logs, in the browser’s Location: box.
    • The GET method is restricted to send upto 1024 characters only.
    • Never use GET method if you have password or other sensitive information to be sent to the server.
    • GET can’t be used to send binary data, like images or word documents, to the server.
    • The data sent by GET method can be accessed using QUERY_STRING environment variable.
    • The PHP provides $_GET associative array to access all the sent information using GET method.

    Try out following example by putting the source code in test.php script.

    <?php
       if( $_GET["name"] || $_GET["age"] ) {
    
      echo "Welcome ". $_GET['name']. "&lt;br /&gt;";
      echo "You are ". $_GET['age']. " years old.";
      
      exit();
    } ?><form action = "<?php <b>$_PHP_SELF</b> ?>" method = "GET"> Name: <input type = "text" name = "name" /> Age: <input type = "text" name = "age" /><input type = "submit" /></form>

    Output

    It will produce the following result −

    Forms

    The POST Method

    The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

    • The POST method does not have any restriction on data size to be sent.
    • The POST method can be used to send ASCII as well as binary data.
    • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
    • The PHP provides $_POST associative array to access all the sent information using POST method.

    Try out following example by putting the source code in test.php script.

    <?php
       if( $_POST["name"] || $_POST["age"] ) {
    
      if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
         die ("invalid name and name should be alpha");
      }
      echo "Welcome ". $_POST['name']. "&lt;br /&gt;";
      echo "You are ". $_POST['age']. " years old.";
      
      exit();
    } ?><form action = "<?php <b>$_PHP_SELF</b> ?>" method = "POST"> Name: <input type = "text" name = "name" /> Age: <input type = "text" name = "age" /><input type = "submit" /></form>

    Output

    It will produce the following result −

    Forms

    File Uploads using POST

    To handle file uploads in PHP using POST requests, create an HTML form for the file input and a PHP script to process the submitted file.

    Example

    You will need an HTML form where users can upload files. To properly enable file uploads, the form must have the enctype=”multipart/form-data” tag.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>File Upload</title></head><body><h2>Upload a File</h2><form action="upload.php" method="POST" enctype="multipart/form-data"><input type="file" name="fileToUpload" required><input type="submit" value="Upload File"></form></body></html>

    Create an upload.php file to manage file uploads. When you submit the form, this code will handle the data.

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Directory where files will be uploaded
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size (e.g., limit to 500KB)
    if ($_FILES["fileToUpload"]["size"] &gt; 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats (e.g., jpg, png, gif)
    if (!in_array($fileType, ['jpg', 'png', 'jpeg', 'gif'])) {
        echo "Sorry, only JPG, JPEG, PNG &amp; GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // Attempt to upload the file
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    } else {
    echo "Invalid request method.";
    } ?>

    Make sure you set up an uploads directory on your server to store uploaded content. Make sure this directory is readable.

    mkdir uploads
    chmod 775 uploads
    

    Difference between GET and POST

    The main difference between the GET and POST methods is that while the request parameters appended to the URL are exposed in the browser’s URL, the POST data is included in the message body, and not revealed in the URL. Hence, the GET method shouldn’t be used to send sensitive data to the server.

    Secondly, the request data in GET method cannot exceed 2048 characters and can consist of ASCII characters only, while with POST method, there is no limit to the request data which can be in binary also (the default maximum size of POST data is determined by post_max_size setting in php.ini file)

    PHP provides the following three superglobals to retrieve and process the request parameters −

    • $_GET − an associative array to access all the sent information using GET method.
    • $_POST − an associative array to access all the sent information using POST method.
    • $_REQUEST − an associative array that can be used to get the result from form data sent with both the GET and POST methods.

    $_GET Array

    You can pass the request parameters in the form of query string directly appended to the URL.

    Save the following PHP script in the document root folder (htdocs) as “hello.php” −

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

    Enter “http://localhost/hello.php?first_name=Amar&last_name=Sharma” as the URL in a browser window (ensure that the PHP server is running).

    The $_GET array is populated from the request and the output is displayed as below −

    First name: Amar Last Name: Sharma
    

    You can also populate the $_GET array with the HTML form data if its method attribute is GET.

    Use the following HTML form to collect the data and send it to “hello.php”. Under the document root, save the following script as “hello.html” −

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

    Output

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

    PHP Get Post

    You should get the similar output in the browser window.

    $_POST Array

    The easiest way to send data to a server with the POST request is specifying the method attribute of HTML form as POST. Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as in the earlier example −

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

    The “hello.php” script (in document root folder) retrieves the form data in the $_POST array and renders it as the HTTP response back to the browser −

    <?php
       echo "First name: " . $_POST['first_name'] . " " . 
    
      "Last Name: " . $_POST['last_name'] . "";
    ?>

    Open “http://localhost/hello.html” in your browser. The data entered is retrieved by the server, and rendered back to the client, as in the earlier example.

  • File Inclusion

    When developing websites, we generally have to reuse the same information or code in many places. For example, we might want the same header, footer or menu across all pages. PHP allows us to use file inclusion instead of writing the same code many times!

    File inclusion saves time, organizes our code and allows us to make simple changes. When we make a change to one file, that changes all other files that contain that file.

    Types File Inclusion in PHP

    You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

    • Include() Function
    • Require() Function
    • Include_once() and Require_once() Function

    This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

    The include() Function

    The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

    Syntax

    Below is the syntax of the includefunction −

    include'filename.php';

    Here, filename.php is the file you want to include. It can be a relative or absolute path.

    Example

    Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

    <a href="http://www.tutorialspoint.com/index.htm">Home</a><a href="http://www.tutorialspoint.com/ebxml">ebXML</a><a href="http://www.tutorialspoint.com/ajax">AJAX</a><a href="http://www.tutorialspoint.com/perl">PERL</a>

    Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

    <?php <b>include("menu.php");</b> ?><p>This is an example to show how to include PHP file!</p>

    Output

    It will produce the following result −

    Include

    Advantages of include() Method

    Using the include() method in PHP has several advantages −

    • Adding a file allows you to reuse the same content on other pages without having to change any code.
    • You can add basic website elements like headers, footers, and menus to various pages.
    • If the included file has an error, include() will only display a warning message and the script will continue to run.
    • If you need to change the included file (for example, to update the header or footer), do so only once, and the changes will be reflected on all pages that use it.

    The require() Function

    The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

    So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

    Syntax

    Below is the syntax of the requirefunction −

    require'filename.php';

    Here, filename.php is a file you want to require. It can be a relative or absolute path.

    Example

    You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

    <?php include("xxmenu.php"); ?><p>This is an example to show how to include wrong PHP file!</p>

    Output

    This will produce the following result −

    This is an example to show how to include wrong PHP file!
    

    Now lets try same example with require() function.

    <?php <b>require("xxmenu.php");</b> ?><p>This is an example to show how to include wrong PHP file!</p>

    This time file execution halts and nothing is displayed.

    NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

    Advantages of require() Method

    Using the require() method in PHP has many advantages −

    • If the required file is important for the page (for example, a database connection file), require() makes sure the script stops and displays an error if it is not found, preventing the page from loading with limited functionality.
    • The function makes sure all necessary files are always available for proper execution. This is useful for files that the website need to work properly.
    • Like include(), require() allows you to reuse code across multiple pages.
    • With require(), you only need to include the required code once, which reduces duplication.

    Difference between include() and require() Methods

    The require statement is also used to include a file within PHP code. However, there is one important difference between include and require: if a file is included using the include line but PHP cannot find it, the script will continue to run.

    • The include() function shows a warning and continues execution if the file is missing. While the require() method shows a fatal error and stops execution if the file is missing.
    • The include() function is basically used for non-critical files for example- header, footer. While require() is used for important files like database connection, configuration.
    • The include() method can include a file multiple times unless include_once() is used. And the require() includes a file multiple times unless require_once() is used.
    • The include() continues execution even if the file is not present of missing. And require() stops script execution if the file is missing.

    The include_once() and require_once() Function

    These functions are useful when you have to make sure a file is only included once.

    // config.php
    <?php
       $database_host = 'localhost';
    ?>
    
    // settings.php
    <?php
       // Includes config.php only once   
       include_once 'config.php'; 
    
       // It will not include again if called multiple times
       require_once 'config.php'; 
       echo "Database host is: $database_host";
    ?>

    Security Risks of File Inclusion

    While file inclusion can make your code easier to work with, it may also create security risks, particularly if users have control over which files are included. This is known as Local File Inclusion (LFI) and can be used by attackers.

    Example of a Vulnerable Code

    In this scenario, a malicious user may gain access to any file on the server by changing the page query parameter, which could result in data breaches or other vulnerabilities. Here is an example code which you should avoid in your PHP applications −

    <?php
       // User can set the page parameter
       $page = $_GET['page']; 
    
       // This can lead to dangerous inclusions
       include($page); 
    ?>

    Prevent File Inclusion Vulnerabilities

    Always check and sanitize any user input before using it in an include statement.

    <?php
       $allowed_pages = ['home.php', 'about.php', 'contact.php'];
       if (in_array($page, $allowed_pages)) {
    
      include($page);
    } else {
      echo "Page not found.";
    } ?>

    Instead of including files with user-generated content you can consider using predefined paths. If you don’t need remote file inclusion so you can disable it in your php.ini file.

    allow_url_include = Off

  • Compound Types

    Data types in PHP can be of “scalar type” or “compound type”. Integer, float, Boolean and string types are scalar types, whereas array and object types are classified as compound types. Values of more than one types can be stored together in a single variable of a compound type.

    In PHP, objects and arrays are the two compound data types.

    • An array is an ordered collection of elements of other data types, not necessarily of the same type.
    • An object is an instance of either a built-in or a user defined class, consisting of properties and methods.

    Arrays in PHP

    An array is a data structure that stores one or more data values in a single variable. An array in PHP is an ordered map that associates the values to their keys.

    • There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to put the array elements inside square brackets.
    • An array which is a collection of only values is called an indexed array. Each value is identified by a positional index staring from 0.
    • If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type.

    The array() Function in PHP

    The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.

    array(mixed...$values):array

    Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol.

    Example

    Take a look at this following example −

    $arr1=array(10,"asd",1.55,true);$arr2=array("one"=>1,"two"=>2,"three"=>3);$arr3=array(array(10,20,30),array("Ten","Twenty","Thirty"),array("physics"=>70,"chemistry"=>80,"maths"=>90));

    Using Square Brackets [ ]

    Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.

    $arr1=[10,"asd",1.55,true];$arr2=["one"=>1,"two"=>2,"three"=>3];$arr3=[[10,20,30],["Ten","Twenty","Thirty"],["physics"=>70,"chemistry"=>80,"maths"=>90]];

    Accessing Array Elements

    To access any element from a given array, you can use the array[key] syntax. For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.

    <?php
       $arr1 = [10, 20, 30];
       $arr2 = array("one"=>1, "two"=>2, "three"=>3);
    
       var_dump($arr1[1]);
       var_dump($arr2["two"]);
    ?>

    It will produce the following output −

    int(20)
    int(2)
    

    Array Traversal in PHP

    You can also use the foreach loop to iterate through an indexed array.

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $val){
    
      echo "$val\n";
    } ?>

    It will produce the following output −

    10
    20
    30
    40
    50
    

    Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.

    We can unpack each element of the indexed array in the key and value variables with the foreach syntax −

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $key => $val){
    
      echo "arr1[$key] = $val" . "\n";
    } ?>

    It will produce the following output −

    arr1[0] = 10
    arr1[1] = 20
    arr1[2] = 30
    arr1[3] = 40
    arr1[4] = 50
    

    The foreach loop is also used for iterating through an associative array, although any other type of loop can also be used with some maneuver.

    Let us look at the foreach loop implementation, with each k-v pair unpacked in two variables.

    <?php
       $capitals = array(
    
      "Maharashtra"=&gt;"Mumbai", 
      "Telangana"=&gt;"Hyderabad", 
      "UP"=&gt;"Lucknow", 
      "Tamilnadu"=&gt;"Chennai"
    ); foreach ($capitals as $k=>$v) {
      echo "Capital of $k is $v" . "\n";
    } ?>

    It will produce the following output −

    Capital of Maharashtra is Mumbai
    Capital of Telangana is Hyderabad
    Capital of UP is Lucknow
    Capital of Tamilnadu is Chennai
    

    Objects in PHP

    In PHP, an object is a compound data type. It is an instance of either a built in or user defined class. Given below is a simple PHP class −

    classSayHello{functionhello(){echo"Hello World";}}

    To declare an object of a class, we need to use the new operator.

    $obj=newSayHello;

    We can now call its method −

    <?php
       class SayHello {
    
      function hello() {
         echo "Hello World". PHP_EOL;
      }
    } $obj=new SayHello; var_dump(gettype($obj)); $obj->hello(); ?>

    It will produce the following output −

    string(6) "object"
    Hello World
    

    The stdClass

    PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. An object of stdClass is null to begin with. We can add properties to it dynamically.

    <?php
       $obj=new stdClass;
       $obj->name="Deepak";
       $obj->age=21;
       $obj->marks=75;
    
       print_r($obj);
    ?>

    It will produce the following output −

    stdClass Object (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Array to Object Conversion in PHP

    An array in PHP can be typecast to an object as follows −

    <?php
       $arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
       $obj=(object)$arr;
    
       print_r($obj);
    ?>

    It will produce the following output −

    stdClass Object (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Object to Array Conversion in PHP

    Conversely, an object can be cast to an array. Take a look at the following example −

    <?php
       $obj=new stdClass;
       $obj->name="Deepak";
       $obj->age=21;
       $obj->marks=75;
    
       $arr=(array)$obj;
       print_r($arr);
    ?>

    It will produce the following output −

    Array
    (
       [name] => Deepak
       [age] => 21
       [marks] => 75
    )
    

    Scalar Type to Object Type Conversion in PHP

    A variable of any scalar type can also be converted to an object by type casting. The value of the scalar variable becomes the value of the object’s scalar property.

    <?php
       $name="Deepak";
       $age=21;
       $percent=75.50;
    
       $obj1=(object)$name;
       print_r($obj1);
    
       $obj2=(object)$age;
       print_r($obj2);
    
       $obj3=(object)$percent;
       print_r($obj3);
    ?>

    It will produce the following output −

    stdClass Object
    (
       [scalar] => Deepak
    )
    stdClass Object
    (
       [scalar] => 21
    )
    stdClass Object
    (
       [scalar] => 75.5
    )

  • Heredoc & Nowdoc

    Heredoc and Nowdoc are PHP methods that allow you to write long strings without using too many quotes or escape characters. They allow you to write multi-line strings in a neat and readable manner.

    PHP provides two alternatives for declaring single or double quoted strings in the form of heredoc and newdoc syntax.

    Heredoc is useful for including variables, but Nowdoc is useful to get raw text without variable change.

    • The single quoted string doesn’t interpret the escape characters and doesn’t expand the variables.
    • On the other hand, if you declare a double quoted string that contains a double quote character itself, you need to escape it by the “\” symbol. The heredoc syntax provides a convenient method.

    Heredoc Strings in PHP

    The heredoc strings in PHP are much like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables.

    Heredoc Syntax

    $str=<<<IDENTIFIER
    place a string here
    it can span multiple lines
    and include single quote ' and double quotes "
    IDENTIFIER;

    First, start with the “<<<” operator. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The string can span multiple lines and includes single quotes () or double quotes (“).

    The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string.

    Example

    The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. The closing identifier should not contain any other characters except a semicolon (;). Furthermore, the character before and after the closing identifier must be a newline character only.

    Take a look at the following example −

    <?php  
       $str1 = <<<STRING
       Hello World
    
      PHP Tutorial
         by TutorialsPoint
    STRING; echo $str1; ?>

    It will produce the following output −

    Hello World
    
    PHP Tutorial
        by TutorialsPoint

    Example

    The closing identifier may or may not contain indentation after the first column in the editor. Indentation, if any, will be stripped off. However, the closing identifier must not be indented further than any lines of the body. Otherwise, a ParseError will be raised. Take a look at the following example and its output −

    <?php  
       $str1 = <<<STRING
       Hello World
    
      PHP Tutorial
    by TutorialsPoint STRING;
         
    echo $str1; ?>

    It will produce the following output −

    PHP Parse error:  Invalid body indentation level 
    (expecting an indentation level of at least 16) in hello.php on line 3
    

    Example

    The quotes in a heredoc do not need to be escaped, but the PHP escape sequences can still be used. Heredoc syntax also expands the variables.

    <?php  
       $lang="PHP";
       echo <<<EOS
       Heredoc strings in $lang expand vriables.
       The escape sequences are also interpreted.
       Here, the hexdecimal ASCII characters produce \x50\x48\x50
       EOS;
    ?>

    It will produce the following output −

    Heredoc strings in PHP expand vriables.
    The escape sequences are also interpreted.
    Here, the hexdecimal ASCII characters produce PHP
    

    Nowdoc Strings in PHP

    A nowdoc string in PHP is similar to a heredoc string except that it doesn’t expand the variables, neither does it interpret the escape sequences.

    <?php  
       $lang="PHP";
    
       $str = <<<'IDENTIFIER'
       This is an example of Nowdoc string.
       it can span multiple lines
       and include single quote ' and double quotes "
       IT doesn't expand the value of $lang variable
       IDENTIFIER;
    
       echo $str;
    ?>

    It will produce the following output −

    This is an example of Nowdoc string.
    it can span multiple lines
    and include single quote ' and double quotes "
    IT doesn't expand the value of $lang variable
    

    The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the “<<<” operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the heredoc identifier.

    Heredoc strings are like double-quoted strings without escaping. Nowdoc strings are like single-quoted strings without escaping.

  • Maths Functions

    Mathematical operations are important parts of programming. PHP has several built-in math functions that make calculations easy. These functions can be used to round numbers, find maximum and minimum values, work with exponents and logarithms and so on.

    In this chapter, we will look at different PHP math functions and mathematical (arithmetic) operators and how they can be used with the help of some examples. If you need to calculate absolute values, round numbers or perform complex mathematical operations, PHP’s math functions make it easy and efficient.

    List of Math Functions

    Here is the list of functions available in PHP −

    FunctionDescription
    abs($num)Returns the absolute (positive) value of a number.
    ceil($num)Rounds a float number up to the next highest integer.
    exp($num)Returns Euler’s number (e) raised to the power of the given number.
    floor($num)Rounds a float number down to the next lowest integer.
    intdiv($x, $y)Returns the integer quotient of two integers (ignoring remainder).
    log10($num)Returns the base-10 logarithm of a number.
    max($values)Returns the highest value from an array or multiple values.
    min($values)Returns the lowest value from an array or multiple values.
    pow($base, $exp)Returns the result of raising a number to a given power.
    round($num, $precision)Rounds a number to the nearest integer or specified decimal places.
    sqrt($num)Returns the square root of a number.

    PHP abs() Function

    The abs() function is an in-built function in PHP iterpreter. This function accepts any number as argument and returns a positive value, disregarding its sign. Absolute value of any number is always positive.

    abs(mixed$num)

    PHP abs() function returns the absolute value of num. If the data type of num is float, its return type will also be float. For integer parameter, the return type is integer.

    Example

    Take a look at this following example −

    <?php
       $num=-9.99;
       echo "negative float number: " . $num . "\n";
       echo "absolute value : " . abs($num) . "\n"; 
    
       $num=25.55;
       echo "positive float number: " . $num . "\n";
       echo "absolute value : " . abs($num). "\n";
    
       $num=-45;
       echo "negative integer number: " . $num . "\n";
       echo "absolute value : " . abs($num) . "\n"; 
    
       $num=25;
       echo "positive integer number: " . $num . "\n";
       echo "absolute value : " . abs($num);
    ?>

    It will produce the following output −

    negative float number: -9.99
    absolute value : 9.99
    positive float number: 25.55
    absolute value : 25.55
    negative integer number: -45
    absolute value : 45
    positive integer number: 25
    absolute value : 25
    

    PHP ceil() Function

    The ceil() function is an in-built function in PHP iterpreter. This function accepts any float number as argument and rounds it up to the next highest integer. This function always returns a float number as the range of float is bigger than that of integer.

    ceil(float$num):float

    PHP ceil() function returns the smallest integer value that is bigger than or equal to given parameter.

    Example 1

    The following code rounds 5.78 to its next highest integer which is 6

    <?php
       $arg=5.78; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(5.78) = 6
    

    Example 2

    The following example shows how you can find the next highest integer of 15.05.

    <?php
       $arg=15.05; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(15.05) = 16
    

    Example 3

    For negative number, it is rounded towards 0.

    <?php
       $arg=-3.95; 
       $val=ceil($arg);
       echo "ceil(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    ceil(-3.95) = -3
    

    PHP exp() Function

    The exp() function calculates exponent of e that is Euler Number. PHP has a predefined constant M_E that represents Euler Number and is equal to 2.7182818284590452354. Hence, exp(x) returns 2.7182818284590452354x

    This function always returns a float.

    exp(float$arg):float

    PHP exp() function returns the Euler Number e raised to given arg. Note that e is the base of natural algorithm. The exp() function is the inverse of natural logarithm.

    Example 1

    One of the predefined constants in PHP is M_LN2 which stands for loge2 and is equal to 0.69314718055994530942. So, the exp() of this value will return 2.

    <?php
       echo "exp(" . M_LN2 . ") = " . exp(M_LN2);
    ?>

    It will produce the following output −

    exp(0.69314718055995) = 2
    

    Example 2

    M_LN10 is another predefined constant representing loge10. This program calculates exp(M_LN10) and returns 10.

    <?php
       echo "exp(" . M_LN10 . ") = " . exp(M_LN10);
    ?>

    It will produce the following output −

    exp(2.302585092994) = 10
    

    PHP floor() Function

    The floor() function is another in-built function in PHP interpreter. This function accepts any float number as argument and rounds it down to the next lowest integer. This function always returns a float number as the range of float is bigger than that of integer.

    floor(float$num):float

    PHP floor() function returns the largest integer less than or equal to the given parameter.

    Example 1

    The following example shows how to round 15.05 to its next highest integer which is 15

    <?php
       $arg=15.05; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(15.05) = 15
    

    Example 2

    The following example shows how to find the next lowest integer of 5.78.

    <?php
       $arg=5.78; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(5.78) = 5
    

    Example 3

    Negative numbers are rounded away from 0.

    <?php
       $arg=-3.95; 
       $val=floor($arg);
       echo "floor(" . $arg .  ") = " . $val;
    ?>

    It will produce the following output −

    floor(-3.95) = -4
    

    PHP intdiv() Function

    The intdiv() function returns the integer quotient of two integer parameters. If x/y results in “i” as division and “r” as remainder, then −

    x = y*i+r
    

    In this case, intdiv(x,y) returns “i”

    intdiv(int$x,int$y):int

    The “x” parameter forms numerator part of the division expression, while the “y” parameter forms the denominator part of the division expression.

    PHP intdiv() function returns the integer quotient of division of “x” by “y”. The return value is positive if both the parameters are positive or both the parameters are negative.

    Example 1

    The following example shows that if the numerator is less than the denominator, then intdiv() function returns 0.

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
       $r=intdiv($y, $x);
       echo "intdiv(" . $y . "," . $x . ") = " . $r;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(3,10) = 0
    

    Example 2

    In the following example, intdiv() function returns a negative integer because either the numerator or the denominator is negative.

    <?php
       $x=10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=-10;
       $y=3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    
       $x=-10;
       $y=-3; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r ;
    ?>

    It will produce the following output −

    intdiv(10,3) = 3
    intdiv(10,-3) = -3
    intdiv(-10,3) = -3
    intdiv(-10,-3) = 3
    

    Example 3

    Denominator is 0 in the following example. It results in DivisionByZeroError exception.

    <?php
       $x=10;
       $y=0; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
    ?>

    It will produce the following output −

    PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero
    

    Example 4

    The fractional parts in both the parameters are ignored. PHP intdiv() function is applied only to the integer parts.

    <?php
       $x=2.90;
       $y=1.90; 
       $r=intdiv($x, $y);
       echo "intdiv(" . $x . "," . $y . ") = " . $r . "";
    ?>

    It will produce the following output −

    intdiv(2.9,1.9) = 2
    

    PHP log10() Function

    The log10 () function calculates the base-10 logarithm of a number. Base-10 logarithm is also called common or standard algorithm. The log10(x) function calculates log10x. It is related to natural algorithm by the following equation −

    log10x=logex/loge10 ; So that
    log10100=loge100/loge10 =2

    In PHP, log10 is represented by log10() function

    log10(float$arg):float

    PHP log10() function returns the base-10 logarithm of arg.

    Example 1

    The following code calculates the base-10 logarithm of 100

    <?php
       $arg=100;
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(100)=2
    

    Example 2

    The following code calculates the base-10 logarithm of Euler Number M_E. The result is equal to a predefined constant M_LOG10E

    <?php
       $arg=M_E;
       echo "log10(" . $arg. ")=" . log10($arg) . "\n";
       echo "predefined constant M_LOG10E=" . M_LOG10E;
    ?>

    It will produce the following output −

    log10(2.718281828459)=0.43429448190325
    predefined constant M_LOG10E=0.43429448190325
    

    Example 3

    The following code calculates log100 and returns -.

    <?php
       $arg=0;
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(0)=-INF
    

    Example 4

    Similarly sqrt(-1) results in NAN. Hence, its log10() also returns NAN.

    <?php
       $arg=sqrt(-1);
       echo "log10(" . $arg. ")=" . log10($arg) . "";
    ?>

    It will produce the following output −

    log10(NAN)=NAN
    

    PHP max() Function

    The max () function returns the highest element in an array, or the highest amongst two or more comma separated parameters.

    max(array$values):mixed

    Or,

    max(mixed$value1[,mixed $...]):mixed
    • If only one parameter is given, it should be an array of values which may be of same or different types.
    • If two or more parameters are given, they should be any comparable values of same or different types.

    PHP max() function returns the highest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned.

    Example 1

    The following code returns the highest value from a numeric array.

    <?php
       $arg=array(23, 5.55, 142, 56, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=23,5.55,142,56,99,
    max = 142
    

    Example 2

    The following code returns max() from an array of strings.

    <?php
       $arg=array("Java", "Angular", "PHP", "C", "Kotlin");
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=Java,Angular,PHP,C,Kotlin,
    max = PHP
    

    Example 3

    In the following example, a series of string values is provided to the max() function. Let’s see how it behaves −

    <?php
       $val1="Java";
       $val2="Angular";
       $val3="PHP";
       $val4="C";
       $val5="Kotlin";
       echo "values=" . $val1 . "," . $val2 . "," . $val3 . "," . 	$val4 . "," . $val5 . "\n";
       echo "max = " . max($val1, $val2, $val3,$val4,$val5);
    ?>

    It will produce the following output −

    values=Java,Angular,PHP,C,Kotlin
    max = PHP
    

    Example 4

    In this example, the given array is a collection of mixed data types.

    <?php
       $arg=array(23, "Java", 142, 1e2, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "max = " . max($arg);
    ?>

    It will produce the following output −

    array=23,Java,142,100,99,
    max = 142
    

    PHP min() Function

    The min () function returns the lowest element in an array, or the lowest amongst two or more comma separated parameters.

    min(array$values):mixed

    Or,

    min(mixed$value1[,mixed $...]):mixed
    • If only one parameter is given, it should be an array of values which may be of same or different types
    • If two or more parameters are given, they should be any comparable values of same or different types

    PHP min() function returns the lowest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned

    Example 1

    The following code returns the smallest value from numeric array.

    <?php
       $arg=array(23, 5.55, 142, 56, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=23,5.55,142,56,99,
    min = 5.55
    

    Example 2

    The following code returns min() from an array of strings.

    <?php
       $arg=array("Java", "Angular", "PHP", "C", "Kotlin");
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=Java,Angular,PHP,C,Kotlin,
    min = Angular
    

    Example 3

    In this example, a series of string values is provided to the min() function.

    <?php
       $val1="Java";
       $val2="Angular";
       $val3="PHP";
       $val4="C";
       $val5="Kotlin";
       echo "values=" . $val1 . "," . $val2 . "," . $val3 . "," . 	$val4 . "," . $val5 . "\n";
       echo "min = " . min($val1, $val2, $val3,$val4,$val5);
    ?>

    It will produce the following output −

    values=Java,Angular,PHP,C,Kotlin
    min = Angular
    

    Example 4

    In this example, the given array is a collection of mixed data types.

    <?php
       $arg=array(23, "Java", 142, 1e2, 99);
       echo "array=";
       foreach ($arg as $i) echo $i . ",";
       echo "\n"; 
       echo "min = " . min($arg);
    ?>

    It will produce the following output −

    array=23,Java,142,100,99,
    min = 23
    

    PHP pow() Function

    The pow () function is used to compute the power of a certain number. It returns xy calculation, also termed as x raised to y. PHP also provides “**” as exponentiation operator.

    So, pow(x,y) returns xy which is same as x**y.

    pow(number$base,number$exp):number

    The first parameter is the base to be raised. The second parameter is the power to which base needs to be raised.

    PHP pow() function returns the base raised to the power of exp. If both arguments are non-negative integers, the result is returned as integer, otherwise it is returned as a float.

    Example 1

    The following example calculates 102 using pow() function −

    <?php
       echo "pow(10,2) = " . pow(10,2);
       echo " using ** operator " . 10**2;
    ?>

    It will produce the following output −

    pow(10,2) = 100 using ** operator 100
    

    Example 2

    Any number raised to 0 results in 1. This is verified in the following example −

    <?php
       $x=10;
       $y=0;
       echo "pow(" . $x, "," . $y . ")=". pow($x,$y);
    ?>

    It will produce the following output −

    pow(10,0)=1
    

    Example 3

    The following example shows how you can compute the square root of 100 using the pow() function −

    <?php
       $x=100;
       $y=0.5;
       echo "pow(" . $x, "," . $y . ")=". pow($x,$y) . "\n";
       echo "using sqrt() function : ". sqrt(100);
    ?>

    It will produce the following output −

    pow(100,0.5)=10
    using sqrt() function : 10
    

    Example 4

    This example shows how you can use the pow() function to calculate the area of a circle.

    <?php
       $radius=5;
       echo "radius = " . $radius . " area = " . M_PI*pow(5,2);
    ?>

    It will produce the following output −

    radius = 5 area = 78.539816339745
    

    PHP round() Function

    The round() function proves useful in rounding any floating point number upto a desired precision level. Positive precision parameter causes the number to be rounded after the decimal point; whereas with negative precision, rounding occurs before the decimal point. Precision is “0” by default.

    For example, round(10.6) returns 11, round(10.2) returns 10. The function always returns a floating point number.

    This function also has another optional parameter called mode that takes one of the redefined constants described later.

    round(float$value,int$precision,int$mode):float

    Parameters

    • Value − A float number to be rounded.
    • Precision − Number of decimal digits to round to. Default is 0. Positive precision rounds given number after decimal point. Negative precision rounds the given number before decimal point.
    • Mode − One of the following predefined constants.
    Sr.NoConstant & Description
    1PHP_ROUND_HALF_UPRounds number away from 0 when it is half way there. Hence, 1.5 becomes 2 and -1.5 to -2
    2PHP_ROUND_HALF_DOWNRounds number towards 0 when it is half way there. Hence 1.5 becomes 1 and -1.5 to -1
    3PHP_ROUND_HALF_EVENRounds the number to nearest even value
    4PHP_ROUND_HALF_ODDRounds the number to nearest odd value

    PHP round() function returns a float number that by rounding the value to a desired precision.

    Example 1

    The following code rounds the given number to positive precision values −

    <?php
       $arg=1234.567;
       echo "round(" . $arg . ") = " . round($arg) . "\n";
       echo "round(" . $arg . ",1) = " . round($arg,1) . "\n";
       echo "round(" . $arg . ",2) = " . round($arg,2) . "";
    ?>

    It will produce the following output −

    round(1234.567) = 1235
    round(1234.567,1) = 1234.6
    round(1234.567,2) = 1234.57
    

    Example 2

    The following code rounds the number to negative precision values −

    <?php
       $arg=1234.567;
       echo "round(" . $arg . ") = " . round($arg) . "\n";
       echo "round(" . $arg . ",-1) = " . round($arg,-1) . "\n";
       echo "round(" . $arg . ",-2) = " . round($arg,-2) . "";
    ?>

    It will produce the following output −

    round(1234.567) = 1235
    round(1234.567,-1) = 1230
    round(1234.567,-2) = 1200
    

    Example 3

    The following code uses UP and DOWN mode constants for rounding −

    <?php
       echo "round(3.45,HALF_UP) = " . round(3.45,0, PHP_ROUND_HALF_UP) . "\n";
       echo "round(3.75 HALF_UP) = " . round(3.75, 1, PHP_ROUND_HALF_DOWN) . "";
    ?>

    It will produce the following output −

    round(3.45,HALF_UP) = 3
    round(3.75 HALF_UP) = 3.7
    

    Example 4

    The following code uses ODD and EVEN modes for rounding −

    <?php
       echo "round( 3.45,HALF_ODD) = " . round(3.45,0, PHP_ROUND_HALF_ODD) . "\n";
       echo "round(3.78 HALF_EVEN) = " . round(3.78, 0, PHP_ROUND_HALF_EVEN) . "";
    ?>

    It will produce the following output −

    round(3.45,HALF_ODD) = 3
    round(3.78, HALF_EVEN) = 4
    

    PHP sqrt() Function

    The sqrt() function returns the square root of a positive float number. Since square root for a negative number is not defined, it returns NAN. This is one of the most commonly used functions. This function always returns a floating point number.

    sqrt(float$arg):float

    PHP sqrt() function returns the square root of the given arg number. For negative numbers, the function returns NAN.

    Example 1

    The following code calculates the square root of 100 −

    <?php
       $arg = 100;
       echo "Square root of " . $arg . "=" . sqrt($arg) . "";
    ?>

    It will produce the following output −

    Square root of 100=10
    

    Example 2

    For sqrt(2), 1/sqrt(2) and sqrt(3), PHP has special predefined constants M_SQRT2, M_SQRT1_2 and M_SQRT3, respectively.

    <?php
       echo "sqrt(2) = " . sqrt(2) . "\n";
       echo "M_SQRT2 = " . M_SQRT2. "\n";
       echo "sqrt(3) = " . sqrt(3) . "\n";
       echo "M_SQRT3 = " . M_SQRT3 . "\n";
       echo "1/sqrt(2)) = " . 1/sqrt(2) . "\n";
       echo "M_SQRT1_2 = " . M_SQRT1_2 . "";
    ?>

    It will produce the following output −

    sqrt(2) = 1.4142135623731
    M_SQRT2 = 1.4142135623731
    sqrt(3) = 1.7320508075689
    M_SQRT3 = 1.7320508075689
    1/sqrt(2)) = 0.70710678118655
    M_SQRT1_2 = 0.70710678118655
    

    Example 3

    The mathematical constants M_SQRTPI and M_2_SQRTPI represent values of sqrt() and 2/sqrt().

    <?php
       echo "sqrt(pi) = " . sqrt(M_PI) . "\n";
       echo "M_SQRTPI = " . M_SQRTPI. "\n";
       echo "2/sqrt(pi) = " . 2/sqrt(M_PI) . "\n";
       echo "M_2_SQRTPI = " . M_2_SQRTPI . "";
    ?>

    It will produce the following output −

    sqrt(pi) = 1.7724538509055
    M_SQRTPI = 1.7724538509055
    2/sqrt(pi) = 1.1283791670955
    M_2_SQRTPI = 1.1283791670955
    

    Example 4

    sqrt(-1) is undefined, hence it returns NAN.

    <?php
       echo "sqrt(-1) = " . sqrt(-1) . "";
    ?>

    It will produce the following output −

    sqrt(-1) = NAN
    

    Predefined Mathematical Constants

    In addition to the above mathematical functions, PHP also has the following list of predefined mathematical constants −

    ConstantValueDescription
    M_PI3.14159265358979323846Pi
    M_E2.7182818284590452354Euler Number e
    M_LOG2E1.4426950408889634074log2 e
    M_LOG10E0.43429448190325182765log10 e
    M_LN20.69314718055994530942loge 2
    M_LN10M_LN10 2.30258509299404568402 loge 10loge 10
    M_PI_21.57079632679489661923pi/2
    M_PI_40.78539816339744830962pi/4
    M_1_PI0.318309886183790671541/pi
    M_2_PI0.636619772367581343082/pi
    M_SQRTPI1.77245385090551602729sqrt(pi)
    M_2_SQRTPI1.128379167095512573902/sqrt(pi)
    M_SQRT21.41421356237309504880sqrt(2)
    M_SQRT31.73205080756887729352sqrt(3)
    M_SQRT1_20.707106781186547524401/sqrt(2)
    M_LNPI1.14472988584940017414loge(pi)
    M_EULER0.57721566490153286061Euler constant
    PHP_ROUND_HALF_UP1Round halves up
    PHP_ROUND_HALF_DOWN2Round halves down
    PHP_ROUND_HALF_EVEN3Round halves to even numbers
    PHP_ROUND_HALF_ODD4Round halves to odd numbers
    NANNANNot A Number
    INFINFInfinity

  • Files & I/O

    PHP Files and I/O is the process of reading, writing, creating and deleting files. PHP has various functions for easy file management. We can open a file and write to or read from it. Functions like fopen(), fread() and fwrite() are very useful.

    Files allow you to store data for later use. Getting data from files is as simple. File management is important in web applications. It allows for the secure storage and management of data.

    This chapter will explain following functions related to files −

    • Opening a File
    • Reading a File
    • Writing a File
    • Closing a File

    Opening and Closing Files

    The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.

    Files modes can be specified as one of the six options in this table.

    Sr.NoMode & Purpose
    1rOpens the file for reading only.Places the file pointer at the beginning of the file.
    2r+Opens the file for reading and writing.Places the file pointer at the beginning of the file.
    3wOpens the file for writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
    4w+Opens the file for reading and writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
    5aOpens the file for writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
    6a+Opens the file for reading and writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.

    If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.

    After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

    Reading a File

    Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.

    The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

    So here are the steps required to read a file with PHP.

    • Open a file using fopen() function.
    • Get the file’s length using filesize() function.
    • Read the file’s content using fread() function.
    • Close the file with fclose() function.

    Example

    The following example assigns the content of a text file to a variable then displays those contents on the web page.

    <html><head><title>Reading a file using PHP</title></head><body><?php
    
      $filename = "tmp.txt";
      $file = fopen( $filename, "r" );
      if( $file == false ) {
         echo ( "Error in opening file" );
         exit();
      }
      $filesize = filesize( $filename );
      $filetext = fread( $file, $filesize );
      fclose( $file );
      echo ( "File size : $filesize bytes" );
      echo ( "&lt;pre&gt;$filetext&lt;/pre&gt;" );
    ?></body></html>

    It will produce the following result −

    Reading File

    Writing a File

    A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.

    Example

    The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

    <?php
       $filename = "/home/user/guest/newfile.txt";
       $file = fopen( $filename, "w" );
       
       if( $file == false ) {
    
      echo ( "Error in opening new file" );
      exit();
    } fwrite( $file, "This is a simple test\n" ); fclose( $file ); ?><html><head><title>Writing a file using PHP</title></head><body><?php
      $filename = "newfile.txt";
      $file = fopen( $filename, "r" );
      if( $file == false ) {
         echo ( "Error in opening file" );
         exit();
      }
      $filesize = filesize( $filename );
      $filetext = fread( $file, $filesize );
      fclose( $file );
      echo ( "File size : $filesize bytes" );
      echo ( "$filetext" );
      echo("file name: $filename");
    ?></body></html>

    It will produce the following result −

    Writing File

    We have covered all the function related to file input and out in PHP File System Function chapter.