Category: PHP

  • XML Introduction

    With the help of PHPs built-in functions and libraries, we can handle manipulation of XML data. XML, which stands for eXtensible Markup Language, is a data format for structured document interchange, especially on the Web.

    XML is a popular file format used for serialization of data storing the data, transmitting it to another location, and reconstructing it at the destination.

    In this chapter, we shall learn about the basics of XML processing with PHP.

    Features of XML

    One of the features of XML is that it is both human readable and machine readable. The specifications of XML are defined and standardized by The World Wide Web Consortium. PHP parser can perform read/write operations on XML data.

    XML Tags

    Like HTML, XML document is also composed with the help of tags. However, you can define your own tags, which is unlike HTML where you need to use predefined tags to compose a HTML document.

    The HTML tags essentially apply formatting attributes over text, image, multimedia resources etc. The XML tags define user specified attributes to the data elements.

    XML Document

    An XML document has a hierarchical structure of tags that define the elements and attributes of data within a document. Each XML document consists of a root element that encloses other elements. Elements can have attributes, which provide additional information or properties about the element. The data within elements are enclosed by opening and closing tags.

    Example

    An example of a typical XML document is given below −

    <?xml version = '1.0' encoding = 'UTF-8'?><note><Course>Android</Course><Subject>Android</Subject><Company>TutorialsPoint</Company><Price>$10</Price></note>

    Types of XML Parsers

    In PHP, there are two types of XML parsers available −

    • Tree based parsers
    • Event based parsers

    Tree-based Parsers

    With this type of a parser, PHP loads the entire XML document in the memory and transforms the XML document into a Tree structure. It analyzes the whole document, and provides access to the Tree elements.

    For smaller documents, tree-based parser works well, but for large XML document, it causes major performance issues. SimpleXML parser and DOM XML parser are the examples of tree-based parsers

    Simple XML Parser

    The Simple XML parser also called as tree-based XML parser and it will parse the simple XML file. Simple XML parse will call simplexml_load_file() method to get access to the xml from specific path.

    DOM Parser

    DOM Parser also called as a complex node parser, Which is used to parse highly complex XML file. It is used as interface to modify the XML file. DOM parser has encoded with UTF-8 character encoding.

    Event-based Parsers

    An event-based parser doesnt load the entire XML document in the memory. instead, it reads in one node at a time. The parser allows you to interact with in real time. Once you move onto the next node, the old one is removed from the memory.

    As there is no memory overload involved, this type of parser is suitable for large XML documents, and the document is parsed faster than any tree-based parser. XMLReader and XML Expat Parser are the examples of event-based parsers.

    XML Parser

    XML parsing is based on SAX parse. It is more faster the all above parsers. It will create the XML file and parse the XML. XML parser has encoded by ISO-8859-1, US-ASCII and UTF-8 character encoding.

    XML Reader

    XML Reader parse also called as Pull XML parse. It is used to read the XML file in a faster way. It works with high complex XML document with XML Validation.

  • AJAX RSS Feed Example

    Really Simple Syndication (RSS)

    RSS, which stands for Really Simple Syndication, is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using AJAX and PHP. This code demonstrates how to show RSS feeds in our site.

    Index.html

    The index page should be as follows −

    <html><head><script>
    
      function showRSS(str) {
         if (str.length == 0) { 
            document.getElementById("output").innerHTML = "";
            return;
         }
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("output").innerHTML = xmlhttp.responseText;
            }
         }
         xmlhttp.open("GET","rss.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><p>Please Select an option to get RSS:</p><form><select onchange = "showRSS(this.value)"><option value = "">Select an RSS-feed:</option><option value = "cnn">CNN</option><option value = "bbc">BBC News</option><option value = "pc">PC World</option></select></form><br><div id = "output">RSS-feeds</div></body></html>

    rss.php

    “rss.php” has contained syntax about how to get access to RSS Feeds RSS Feeds and return RSS Feeds to the webpages.

    <?php
       $q = $_GET["q"];
    
       if($q == "cnn") {
    
      $xml = ("http://rss.cnn.com/rss/cnn_topstories.rss");
    } elseif($q == "bbc") {
      $xml = ("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
    } elseif($q = "pcw"){
      $xml = ("http://www.pcworld.com/index.rss");
    } $xmlDoc = new DOMDocument(); $xmlDoc->load($xml); $channel = $xmlDoc->getElementsByTagName('channel')->item(0); $channel_title = $channel->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue; $channel_link = $channel->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue; $channel_desc = $channel->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue; echo("<p><a href = '" . $channel_link . "'>" .
      $channel_title . "&lt;/a&gt;");
    echo("<br>"); echo($channel_desc . "</p>"); $x = $xmlDoc->getElementsByTagName('item'); for ($i = 0; $i<=2; $i++) {
      $item_title = $x-&gt;item($i)-&gt;getElementsByTagName('title')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      $item_link = $x-&gt;item($i)-&gt;getElementsByTagName('link')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      $item_desc = $x-&gt;item($i)-&gt;getElementsByTagName('description')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      echo ("&lt;p&gt;&lt;a href = '" . $item_link . "'&gt;" . $item_title . "&lt;/a&gt;");
      echo ("&lt;br&gt;");
      echo ($item_desc . "&lt;/p&gt;");
    } ?>

    It will produce the following output −

    PHP RSS Feed Example
  • AJAX Auto Complete Search

    Autocomplete feature is a typeahead mechanism to show input suggestion as the user enters data in the search box provided. It is also called live search because it reacts to the users’ input. In this example, we shall use AJAX and XML parser in PHP to demonstrate the use of auto complete text box.

    This application has three main constituents −

    • The XML Document
    • JavaScript Code
    • XML Parser in PHP

    Let us now discuss these three constituents in detail −

    The XML Document

    Save the following XML script as “autocomplete.xml” in the document root folder

    <?xml version = "1.0" encoding = "utf-8"?><pages><link><title>android</title><url>https://www.tutorialspoint.com/android/index.htm</url></link><link><title>Java</title><url>https://www.tutorialspoint.com/java/index.htm</url></link><link><title>CSS </title><url>https://www.tutorialspoint.com/css/index.htm</url></link><link><title>angularjs</title><url>https://www.tutorialspoint.com/angularjs/index.htm </url></link><link><title>hadoop</title><url>https://www.tutorialspoint.com/hadoop/index.htm </url></link><link><title>swift</title><url>https://www.tutorialspoint.com/swift/index.htm </url></link><link><title>ruby</title><url>https://www.tutorialspoint.com/ruby/index.htm </url></link><link><title>nodejs</title><url>https://www.tutorialspoint.com/nodejs/index.htm </url></link></pages>

    JavaScript Code

    The following script renders a text field for the user to enter a course name of his choice. On every keystroke a JavaScript function is called, and the input value is passed to the server-side PHP script with GET method. The servers response is asynchronously rendered.

    Save this code as “index.php“.

    <html><head><script>
    
      function showResult(str) {
         if (str.length == 0) {
            document.getElementById("livesearch").innerHTML = "";
            document.getElementById("livesearch").style.border = "0px";
            return;
         }
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
               document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
            }
         }
         xmlhttp.open("GET","livesearch.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><form><h2>Enter Course Name</h2><input type = "text" size = "30" onkeyup = "showResult(this.value)"><div id = "livesearch"></div><a href = "https://www.tutorialspoint.com">More Details</a></form></body></html>

    XML Parser in PHP

    This the PHP script on the server. It parses the given XML source document, reads the characters entered in the input field, searches for it in the parsed XNL object, and sends back the response.

    Save the following code as “livesearch.php”.

    <?php
       $xml_doc = new DOMDocument();
       $xml_doc->load('autocomplete.xml');
    
       $x=$xml_doc->getElementsByTagName('link');
    
       $q = $_GET['q'];
       $result = '';
       foreach($x as $node) {
    
      if (stripos("{$node-&gt;nodeValue}", $q) !== false) {
         $result .= "{$node-&gt;nodeValue}";
      }
    } // Set $response to "No records found." in case no hint was found // or the values of the matching values if ($result == '')
      $result = 'No records found.';
    // show the results or "No records found." echo $result; ?>

    With the XAMPP server running, visit “http://localhost/index.php” and the browser displays a input text field. For each character typed in it, the relevant suggestions appear below it.

  • AJAX XML Parser

    Using PHP with AJAX, we can parse an XML document from local directory as well as on a server. The following example demonstrates how to parse XML with web browser.

    The client-end script renders a HTML form and defines a JavaScript function for sending a HTTP request to the server with XMLHttpRequest object.

    On the server, a PHP script loads the DOM object from the required XML document, fetches the selected course from $_REQUEST variable, and renders the details of the course chosen as the response back to the client.

    Step 1

    The following XML document is stored on the document root of the XAMPP server.

    <?xml version = "1.0" encoding = "utf-8"?><CATALOG><SUBJECT><COURSE>Android</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$10</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Html</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$15</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Java</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$20</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Microsoft</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$25</PRICE><YEAR>2015</YEAR></SUBJECT></CATALOG>

    Step 2

    The AJAX code below has a HTML form and a JavaScript function to raise HTTP request through XMLHttpRequest object.

    <html><head><script>
    
      function showCD(str) {
         if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
         }
         if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
         } else {  
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
         }
         xmlhttp.open("GET","hello.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><form>
      Select a Course:
      &lt;select name = "cds" onchange = "showCD(this.value)"&gt;&lt;option value = ""&gt;Select a course:&lt;/option&gt;&lt;option value = "Android"&gt;Android &lt;/option&gt;&lt;option value = "Html"&gt;HTML&lt;/option&gt;&lt;option value = "Java"&gt;Java&lt;/option&gt;&lt;option value = "Microsoft"&gt;MS technologies&lt;/option&gt;&lt;/select&gt;&lt;/form&gt;&lt;div id = "txtHint"&gt;&lt;b&gt;Course info will be listed here...&lt;/b&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Step 3

    The server-side PHP script to search within the XML document is as follows −

    <?php
       $q = $_GET["q"];
    
       $xmlDoc = new DOMDocument();
       $xmlDoc->load("test.xml");
    
       $x = $xmlDoc->getElementsByTagName('COURSE');
    
       for ($i = 0; $i<=$x->length-1; $i++) {
    
      if ($x-&gt;item($i)-&gt;nodeType == 1) {
         if ($x-&gt;item($i)-&gt;childNodes-&gt;item(0)-&gt;nodeValue == $q) {
            $y = ($x-&gt;item($i)-&gt;parentNode);
         }
      }
    } $cd = ($y->childNodes); for ($i = 0;$i<$cd->length;$i++) {
      if ($cd-&gt;item($i)-&gt;nodeType == 1) {
         echo("&lt;b&gt;" . $cd-&gt;item($i)-&gt;nodeName . ":&lt;/b&gt; ");
         echo($cd-&gt;item($i)-&gt;childNodes-&gt;item(0)-&gt;nodeValue);
         echo("&lt;br&gt;");
      }
    } ?>

    Visit "http://localhost/example.php" to let the user select a course. Upon selection, the relevant details are fetched from the server and displayed as below −

    PHP AJAX XML Parser
  • AJAX Search

    AJAX is a shortform of the term Asynchronous JavaScript and XML. Ajax is used to build fast and dynamic web pages. Below example demonstrates interaction with the backend PHP script with AJAX functions to provide a search field on the webpage.

    Step 1

    Save the following script as “example.php” −

    <html><head><style>
    
      span {
         color: green;
      }
    </style><script>
      function showHint(str) {
         if (str.length == 0) {
            document.getElementById("txtHint").innerHTML = "";
            return;
         } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
               if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
                  document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
               }
            }
            xmlhttp.open("GET", "hello.php?q=" + str, true);
            xmlhttp.send();
         }
      }
    </script></head><body><p><b>Search your favourite tutorials:</b></p><form><input type = "text" onkeyup = "showHint(this.value)"></form><p>Entered Course name: <span id="txtHint"></span></p></body></html>

    This code is essentially a HTML script that renders a HTML form with a text field. On its onkeyup event, a showHint() JavaScript function is called. The function sends a HTTP GET request to another PHP script on the server.

    Step 2

    Save the following script as “php_ajax.php” −

    <?php
       // Array with names
       $a[] = "Android";
       $a[] = "B programming language";
       $a[] = "C programming language";
       $a[] = "D programming language";
       $a[] = "euphoria";
       $a[] = "F#";
       $a[] = "GWT";
       $a[] = "HTML5";
       $a[] = "ibatis";
       $a[] = "Java";
       $a[] = "K programming language";
       $a[] = "Lisp";
       $a[] = "Microsoft technologies";
       $a[] = "Networking";
       $a[] = "Open Source";
       $a[] = "Prototype";
       $a[] = "QC";
       $a[] = "Restful web services";
       $a[] = "Scrum";
       $a[] = "Testing";
       $a[] = "UML";
       $a[] = "VB Script";
       $a[] = "Web Technologies";
       $a[] = "Xerox Technology";
       $a[] = "YQL";
       $a[] = "ZOPL";
    
       $q = $_REQUEST["q"];
       $hint = "";
    
       if ($q !== "") {
    
      $q = strtolower($q);
      $len = strlen($q);
      foreach($a as $name) {
         if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
               $hint = $name;
            } else {
               $hint .= ", $name";
            }
         }
      }
    } echo $hint === "" ? "Please enter a valid course name" : $hint; ?>

    Step 3

    We will start this application by opening example.php in the browser by entering the URL http://localhost/example.php

    On every keystroke in the search field, a GET request goes to the server. The server script reads the character from $_REQUEST array and searches for the course name that matches. The matched value is displayed below the text field in the browser.

  • AJAX Introduction

    PHP powered web applications often make use of AJAX, together they are useful to create dynamic and interactive web applications. AJAX stands for Asynchronous Javascript and XML. It allows webpages to be updated asynchronously without reloading the entire page.

    In AJAX applications, the exchange of data between a web browser and the server-side PHP script is asynchronous. PHP is a server-side scripting language that can be used to generate dynamic content and process data.

    AJAX creates an additional layer known as AJAX engine in between the web application and web server due to which we can make background server calls using JavaScript and retrieve the required data, can update the requested portion of a web page without casing full reload of the page. It reduces the page refresh timing and provides a fast and responsive experience to the user.

    PHP AJAX Introduction

    What is Required to Run AJAX?

    The technologies that are used by AJAX are already implemented in all the Morden browsers. So the client does not require any extra module to run the AJAX application. The technologies used by AJAX are −

    • Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications.
    • XML − It is used to exchange data between web server and client.
    • The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server.
    • HTML and CSS − It is used to provide markup and style to the webpage text.
    • DOM − It is used to interact with and alter the webpage layout and content dynamically.

    To use AJAX with PHP, you will need to use the XMLHttpRequest object in JavaScript to send requests to the PHP server. The PHP server will then process the request and return a response, typically in the form of JSON or XML. The JavaScript code can then parse the response and update the web page accordingly.

    The XMLHttpRequest object in JavaScript is a browser-based API that allows developers to make HTTP requests to a server without reloading the page. This is the foundation of AJAX programming, which allows for dynamic and interactive web applications.

    The XMLHttpRequest object can be used to −

    • Retrieve data from a server, such as JSON, XML, or HTML.
    • Send data to a server, such as form data or file uploads.
    • Update a web page without reloading it.
    • Create chat applications and other interactive features.

    To use the XMLHttpRequest object, you first need to create a new instance of it. Then, you can use the open() method to specify the HTTP method and request URL. Next, you can set any request headers, if needed. Finally, you can send the request using the send() method.

    Example

    Here is a simple JavaScript code of how to use the XMLHttpRequest object to retrieve data from a server −

    // Create a new XMLHttpRequest objectvar xhr =newXMLHttpRequest();// Set the HTTP method and request URL
    xhr.open("GET","test.php");// Send the request
    xhr.send();// Listen for the onload event to be fired
    xhr.onload =function(){// Check the status code to ensure the request was successfulif(xhr.status ===200){// Get the response data.var users =JSON.parse(xhr.responseText);// Do something with the user data.}else{// Handle the error}};

    The PHP script on the server retrieves the data from AJAX request and sends back the response.

    // Get the request data.$name=$_GET["name"];// Create a response object.$response=newstdClass();$response->message="Hello, $name!";// Send the response back to the client.header("Content-Type: application/json");echojson_encode($response);
  • Flash Messages

    Message flashing in a PHP web application refers to the technique that makes certain messages popup on the browser window for the user to receive applications feedback. To be able to give the user a meaningful feedback to his interactions is an important design principle, that gives a better user experience.

    In a PHP web application, we can use the session data to flash messages regarding success or failure of a certain action, notifications or warnings, etc., from time to time to keep the user informed.

    flash message allows you to create a message on one page and display it once on another page. To transfer a message from one page to another, you use the $_SESSION superglobal variable.

    To start with, you add a variable to the $_SESSION array as follows −

    <?php
       session_start();
       $_SESSION['flash_message'] = "Hello World";
    ?>

    Later, navigate to another page, and retrieve the flashed message from the $_SESSION variable and assign it to a variable. Then, you can display the message and then delete the message from the $_SESSION −

    <?php
       session_start();
       if(isset($_SESSION['flash_message'])) {
    
      $message = $_SESSION['flash_message'];
      unset($_SESSION['flash_message']);
      echo $message;
    } ?>

    To generalize the basic idea of handling the flashed messages, we shall write a function that adds a message to the $_SESSION −

    session_start();functioncreate_flash_message(string$name,string$message):void{// remove existing message with the nameif(isset($_SESSION[FLASH][$name])){unset($_SESSION[FLASH][$name]);}// add the message to the session$_SESSION[FLASH][$name]=['message'=>$message];}

    Let us also have another function that reads back a message, flashes it on the browser, and removes it from the $_SESSION.

    functiondisplay_flash_message(string$name):void{if(!isset($_SESSION[FLASH][$name])){return;}// get message from the session$flash_message=$_SESSION[FLASH][$name];// delete the flash messageunset($_SESSION[FLASH][$name]);// display the flash messageechoformat_flash_message($flash_message);}

    The format_flash_message() function applies desired formatting to the obtained string with appropriate CSS rules.

    If there are more than messages that have been flashed by the application, all of them can be retrieved and flashed with the following example −

    functiondisplay_all_flash_messages():void{if(!isset($_SESSION[FLASH])){return;}// get flash messages$flash_messages=$_SESSION[FLASH];// remove all the flash messagesunset($_SESSION[FLASH]);// show all flash messagesforeach($flash_messagesas$flash_message){echoformat_flash_message($flash_message);}}

    Use the following flash() function to create, format and flash the messages

    functionflash(string$name='',string$message=''):void{if($name!==''&&$message!==''){create_flash_message($name,$message);}elseif($name!==''&&$message===''){display_flash_message($name);// display a flash message}elseif($name===''&&$message===''){display_all_flash_messages();// display all flash message}}

    To implement the above method, call the flash() function on the first page.

    flash('first','Hello World');

    Navigate to another page and call the flash() function to retrieve and display the message −

    flash('first');

    Mechanism of using the flash messages is usually employed on a signup page to redirect users to the login page with a welcome message after they sign up.

  • Post Redirect Get 

    In PHP, PRG stands for “Post/Redirect/Get”. It is a commonly used technique that is designed to prevent the resubmission of a form after it’s been submitted. You can easily implement this technique in PHP to avoid duplicate form submissions.

    Usually a HTML form sends data to the server with the POST method. The server script fetches the data for further processing like adding a new record in a backend database, or running a query to fetch data. If the user accidentally refreshes the browser, there is a possibility of the same form data being resubmitted again, possibly leading to loss of data integrity. The PRG approach in PHP helps you avoid this pitfall.

    Example

    To start with, let us consider the following PHP script that renders a simple HTML form, and submits it back to itself with POST method. When the user fills the data and submits, the backend script fetches the data, renders the result, and comes back to show the blank form again.

    <?php
       if (isset($_POST["submit"])) {
    
      if ($_SERVER["REQUEST_METHOD"] == "POST")
         echo "First name: " . $_REQUEST['first_name'] . " " . "Last Name: " . $_REQUEST['last_name'] . "";
    } ?><html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
      First Name: &lt;input type="text" name="first_name"&gt;&lt;br/&gt;
      Last Name: &lt;input type="text" name="last_name" /&gt;&lt;button type="submit" name="submit"&gt;Submit&lt;/button&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Assuming that the server is running, the above script is placed in the document root folder and visited in the browser.

    Fill the data and submit. The browser echoes the result, and re-renders the form. Now if you try to refresh the browser page, a warning pops up as shown below −

    PHP PRG 1

    If you press Continue, the same data is posted again.

    The problem can be understood with the following figure −

    PHP PRG 2

    Following steps are taken in the PHP script to avoid the problem −

    • The PHP script before the HTML form starts a new session.
    • Check if the form has been submitted with POST method.
    • If so, store the form data in session variables
    • Redirect the browser to a result page. In our case, it is the same page. With the exit command, to terminate this script to make sure no more code gets executed.
    • If PHP finds that the REQUEST method is not POST, it checks if the session variables are set. If so, they are rendered along with the fresh copy of form.
    • Now even if the form is refreshed, you have successfully averted the possibility of resubmission.

    Example

    Here is the PHP code that uses the PRG technique −

    <?php
       session_start();
       if (isset($_POST["submit"])) {
    
      $_SESSION['fname'] = $_POST['first_name'];
      $_SESSION['lname'] = $_POST['last_name']; 
      header("Location: hello.php");
      exit;
    } if (isset($_SESSION["fname"])) {
      echo "First name: " . $_SESSION['fname'] . " " . "Last Name: " . $_SESSION['lname'] . "";
      unset($_SESSION["fname"]); unset($_SESSION["lname"]);
    } ?><html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
      First Name: &lt;input type="text" name="first_name"&gt;&lt;br /&gt;
      Last Name: &lt;input type="text" name="last_name" /&gt;&lt;button type="submit" name="submit"&gt;Submit&lt;/button&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Sanitize Input

    In PHP, it is important to ensure that the input data is sanitized properly by removed any undesired characters before it is processed by the server side code. Usually, the users input their data to a PHP web application through a HTML form. If the form data consists of any undesired characters, it may prove to be harmful, hence an appropriate cleansing operation must be performed.

    Input sanitization can be done with the help of one or more of the following functions in PHP.

    What is Input Sanitization?

    Input sanitization is the process of cleaning up data provided by users before it is used in an application. This prevents other characters or code from being executed. Cleaning input reduces the probability of security issues like SQL injection and cross-site scripting (XSS) attacks.

    Here is why the Input Sanitization important −

    • Security: The main objective of sanitization is to keep your application safe from threats. Malicious users can try to harm your application by transmitting dangerous data.
    • Data Integrity: Sanitizing input makes sure the stored information is correct and consistent. This helps to maintain the quality of information in your application.
    • User Experience: Sanitized input can reduce errors and provide a more consistent user experience.

    The htmlspecialchars() Function

    This function converts special characters to HTML entities.

    htmlspecialchars(string$string,int$flags=ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML401,?string$encoding=null,bool$double_encode=true):string

    In HTML, certain characters have special significance. This htmlspecialchars() function is used to encode special characters in HTML entities. This is useful when you want to display user input as HTML and want to prevent script injection attacks.

    The following special characters are translated as shown −

    CharacterReplaced by
    & (ampersand)&amp;
    ” (double quote)&quot;, unless ENT_NOQUOTES is set
    ‘ (single quote)&#039; (for ENT_HTML401) or &apos; (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
    < (less than)&lt;
    > (greater than)&gt;

    Flag Constants

    The flags parameter is a bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type.

    Sr.NoConstant & Description
    1ENT_COMPATWill convert double-quotes and leave single-quotes alone.
    2ENT_QUOTESWill convert both double and single quotes.
    3ENT_NOQUOTESWill leave both double and single quotes unconverted.
    4ENT_IGNOREdiscard invalid code unit sequences instead of returning an empty string.
    5ENT_SUBSTITUTEReplace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD;
    6ENT_DISALLOWEDReplace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of leaving them as is. This may be useful.
    7ENT_HTML401Handle code as HTML 4.01.
    8ENT_XML1Handle code as XML 1.
    9ENT_XHTMLHandle code as XHTML.
    10ENT_HTML5Handle code as HTML 5.

    Example

    Take a look at the following example −

    <?php
       $str = 'Welcome To "PHP Tutorial" by <b>TutorialsPoint</b>';
       echo htmlspecialchars($str);
    ?>

    It will produce the following output −

    Welcome To "PHP Tutorial" by <b>TutorialsPoint</b>
    

    The strip_tags() Function

    The strip_tags() function removes all the HTML and PHP tags from a given string.

    strip_tags(string$string,array|string|null$allowed_tags=null):string

    This function is very useful when you want ensure that the user input doesn’t contain any potentially malicious tags.

    The allowed_tags parameter is an optional second parameter to specify tags which should not be stripped. These are either given as string, or as an array.

    Example

    Take a look at the following example −

    <?php
       $text = '<p>Hello World</p><!-- Comment --> 
    
      &lt;a href="/test.html"&gt;Click Here&lt;/a&gt;';
    echo strip_tags($text); echo "\n"; // Allow <p> and <a> echo strip_tags($text, '<p><a>'); ?>

    It will produce the following output −

    Hello World 
    
      Click Here
    Hello World
      Click Here

    The addslashes() Function

    The addslashes() function adds backslashes to a string.

    addslashes(string$string):string

    The function returns a string with backslashes added before characters that need to be escaped. These characters are −

    • Single Quote (‘)
    • Double Quote (“)
    • Backslash (\)
    • NUL (The NUL Byte)

    Use this function when you are storing user input in a database and want to prevent SQL injection attacks.

    Example

    Take a look at the following example −

    <?php
       $text = "Newton's Laws";
       $str = addslashes($text);  
    
       // prints the escaped string 
       echo($str);  
    ?>

    It will produce the following output −

    Newton\'s Laws
    

    The filter_var() Function

    With the help of a specific filter flag, you can use filter_var() function to sanitize user input.

    filter_var(mixed$value,int$filter=FILTER_DEFAULT,array|int$options=0):mixed

    The $value parameter is a variable whose value needs to be sanitized. The $filter parameter is any of the predefined filter constants.

    Sr.NoID & Description
    1FILTER_SANITIZE_EMAILRemove all characters except letters, digits and !#$%&’*+-=?^_{|}~@.[].</td></tr><tr><td>2</td><td><strong>FILTER_SANITIZE_ENCODED</strong>URL-encode string, optionally strip or encode special characters.</td></tr><tr><td>3</td><td><strong>FILTER_SANITIZE_ADD_SLASHES</strong>Apply addslashes(). (Available as of PHP 7.3.0).</td></tr><tr><td>4</td><td><strong>FILTER_SANITIZE_NUMBER_FLOAT</strong>Remove all characters except digits, +- and optionally .,eE.</td></tr><tr><td>5</td><td><strong>FILTER_SANITIZE_NUMBER_INT</strong>Remove all characters except digits, plus and minus sign.</td></tr><tr><td>6</td><td><strong>FILTER_SANITIZE_SPECIAL_CHARS</strong>HTML-encode '"&lt;&gt;&amp; and characters with ASCII value less than 32, optionally strip or encode other<br>special characters.</td></tr><tr><td>7</td><td><strong>FILTER_SANITIZE_FULL_SPECIAL_CHARS</strong>Equivalent to calling htmlspecialchars() with&nbsp;<strong>ENT_QUOTES</strong>&nbsp;set. Encoding quotes can be disabled by setting&nbsp;<strong>FILTER_FLAG_NO_ ENCODE_QUOTES</strong>.td&gt;</td></tr><tr><td>8</td><td><strong>FILTER_SANITIZE_URL</strong>Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]<>#%”;/?:@&=.
    9FILTER_UNSAFE_RAW

    Example

    The following code shows how you can sanitize Email data −

    <?php
       $a = 'abc [email protected]';
    
       $sa = filter_var($a, FILTER_SANITIZE_EMAIL);
       echo "$sa";
    ?>

    It will produce the following output −

    [email protected]
    

    Example

    The following code shows how you can sanitize URLs −

    <?php
       $a = "http://example.c o m";
    
       $sa = filter_var($a, FILTER_SANITIZE_URL);
       echo "$sa";
    ?>

    It will produce the following output −

    http://example.com
    

    The mysqli_real_escape_string() Function

    When working with databases, it is important to escape special characters in strings before you use them in SQL queries to prevent SQL injection.

    $conn=newmysqli("localhost","username","password","database");$user_input="O'Reilly";$safe_input=$conn->real_escape_string($user_input);$query="SELECT * FROM users WHERE last_name = '$safe_input'";

  • Sending Emails

    The provision of sending emails is one the commonly required features of a typical PHP powered web application. You would like to send emails containing notifications, updates and other communications to your registered users, through your PHP application itself, instead of a different mail service. You can add this capability to your PHP application by adopting the techniques described in this chapter.

    PHP has a built-in mail() function to send an email. However, you need configure properly the “php.ini” settings to be able to do so. First, you must know the SMTP domain of the web hosting platform that you are using. For example, if your website is being hosted on GoDaddy hosting service, the SMTP domain is “smtp.secureserver.net”, which you should use in the configuration.

    If you use Windows based hosting of GoDaddy, you should ensure that two directives are enabled in php.ini file. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

    Configuration for Windows

    The configuration for Windows should look something like this −

    [mail function];For Win32 only.SMTP= smtp.secureserver.net
    
    ;For win32 only
    sendmail_from = [email protected]
    

    Configuration for Linux

    Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

    The configuration for Linux should look something like this −

    [mail function];For Win32 only.SMTP=;For win32 only
    sendmail_from =;For Unix only
    sendmail_path =/usr/sbin/sendmail -t -i
    

    The mail() Function

    The mail() function in PHP requires three mandatory arguments that specify the recipient’s email address, the subject of the message and the actual message additionally there are other two optional parameters.

    Syntax

    Below is the syntax of the PHP mail() function −

    mail( to, subject, message, headers, parameters );

    Parameters

    Below are the parameters of the mail() function −

    • to − Required. Specifies the receiver / receivers of the email
    • subject − Required. Specifies the subject of the email. This parameter cannot contain any newline characters
    • message − Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
    • headers − Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
    • parameters − Optional. Specifies an additional parameter to the send mail program

    Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

    Sending HTML Email

    When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

    While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

    Example

    The following example shows how to send an HTML email message to “[email protected]” copying it to “[email protected]”. You can code this program in such a way that it should receive all content from the user and then it should send an email.

    It should receive all content from the user and then it should send an email.

    <?php
       $to = "[email protected]";
       $subject = "This is subject";
    
       $message = "<b>This is HTML message.</b>";
       $message .= "<h1>This is headline.</h1>";
    
       $header = "From:[email protected] \r\n";
       $header .= "Cc:[email protected] \r\n";
       $header .= "MIME-Version: 1.0\r\n";
       $header .= "Content-type: text/html\r\n";
    
       $retval = mail ($to,$subject,$message,$header);
    
       if( $retval == true ) {
    
      echo "Message sent successfully...";
    }else {
      echo "Message could not be sent...";
    } ?>

    It will produce the following output −

    Message could not be sent...
    sh: 1: /usr/sbin/sendmail: not found
    

    Sending Email from Localhost

    The above method of calling PHP mail() may not work on your localhost. In that case, there is an alternate solution to sending email. You can use PHPMailer to send email using SMTP from localhost.

    PHPMailer is an open-source library to connect SMTP to send emails. You can download it from PEAR or Composer repositories, or download it from https://github.com/PHPMailer/PHPMailer. Download the ZIP file from here, and copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually.

    Using PHPMailer for Advanced Features

    Use the following PHP script to send email with PHPMailer library −

    Phpmailer.php

    <?php
       use PHPMailer\PHPMailer\PHPMailer;
       use PHPMailer\PHPMailer\SMTP;
       use PHPMailer\PHPMailer\Exception;
    
       require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
       require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
       require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';  
       require 'vendor/autoload.php';
    
       $mail = new PHPMailer;
       if(isset($_POST['send'])){
       
    
      // getting post values
      $fname=$_POST['fname'];		
      $toemail=$_POST['toemail'];	
      $subject=$_POST['subject'];	
      $message=$_POST['message'];
      $mail-&gt;isSMTP();					      // Set mailer to use SMTP
      $mail-&gt;Host = 'smtp.gmail.com';             
      $mail-&gt;SMTPAuth = true;                     
      $mail-&gt;Username = '[email protected]';	// SMTP username
      $mail-&gt;Password = 'mypassword'; 		// SMTP password
      // Enable TLS encryption, 'ssl' also accepted
      $mail-&gt;SMTPSecure = 'tls';
      $mail-&gt;Port = 587;                          
      $mail-&gt;setFrom([email protected]', 'My_Name');
      $mail-&gt;addReplyTo([email protected]', 'My_Name');
      $mail-&gt;addAddress($toemail);   	  // Add a recipient
      $mail-&gt;isHTML(true);                // Set email format to HTML
      $bodyContent=$message;
      $mail-&gt;Subject =$subject;
      $body = 'Dear'.$fname;
      $body .='&lt;p&gt;'.$message.'&lt;/p&gt;';
      $mail-&gt;Body = $body;
      if(!$mail-&gt;send()) {
         echo 'Message could not be sent.';
         echo 'Mailer Error: ' . $mail-&gt;ErrorInfo;
      } else {
         echo 'Message has been sent';
      }
    } ?>

    Use the following HTML form to compose the mail message. The form is submitted to the above phpmail.php script

    Email.html

    <h1>PHP - Sending Email</h1><form action="PHPmailer.php" method="post"><label for="inputName">Name</label><input type="text" id="inputName" name="fname" required><label for="inputEmail">Email</label><input type="email" id="inputEmail" name="toemail" required><label for="inputSubject">Subject</label><input type="text" id="inputSubject" name="subject" required><label for="inputMessage">Message</label><textarea id="inputMessage" name="message" rows="5" required></textarea><button type="submit" name="send">Send</button></form>

    Sending Attachments with Email

    To send an email with mixed content you should set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

    A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

    Example

    Take a look at the following example −

    <?php
    
       // request variables 	
       $from = $_REQUEST["from"];
       $emaila = $_REQUEST["emaila"];
       $filea = $_REQUEST["filea"];
    
       if ($filea) {
    
      function mail_attachment ($from , $to, $subject, $message, $attachment){
         $fileatt = $attachment; 		// Path to the file
         $fileatt_type = "application/octet-stream"; // File Type 
         $start = strrpos($attachment, '/') == -1 ? 
         strrpos($attachment, '//') : strrpos($attachment, '/')+1;
         // Filename that will be used for the file as the attachment
         $fileatt_name = substr($attachment, $start, 
         strlen($attachment));
         $email_from = $from; 		// Who the email is from
         $subject = "New Attachment Message";
         $email_subject =  $subject; // The Subject of the email 
         $email_txt = $message;     // Message that the email has in it 
         $email_to = $to; 	 	   // Who the email is to
         $headers = "From: ".$email_from;
         $file = fopen($fileatt,'rb'); 
         $data = fread($file,filesize($fileatt)); 
         fclose($file); 
         $msg_txt="\n\n You have recieved a new attachment message from $from";
         $semi_rand = md5(time()); 
         $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
         $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
         boundary=\"{$mime_boundary}\"";
         $email_txt .= $msg_txt;
         $email_message .= "This is a multi-part message in MIME format.\n\n" . 
         "--{$mime_boundary}\n" . "Content-Type:text/html; 
         charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . 
         $email_txt . "\n\n";
         $data = chunk_split(base64_encode($data));
         $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
         " name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . 
         //" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: 
         "base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
         $ok = mail($email_to, $email_subject, $email_message, $headers);
         if($ok) {
            echo "File Sent Successfully.";
            // delete a file after attachment sent.
            unlink($attachment);
         } else {
            die("Sorry but the email could not be sent. Please go back and try again!");
         }
      }
      move_uploaded_file($_FILES["filea"]["tmp_name"],
      'temp/'.basename($_FILES['filea']['name']));
      mail_attachment("$from", "[email protected]", 
      "subject", "message", ("temp/".$_FILES["filea"]["name"]));
    } ?><html><head><script language = "javascript" type = "text/javascript">
      function CheckData45() {
         with(document.filepost) {
            if(filea.value ! = "") {
               document.getElementById('one').innerText = "Attaching File ... Please Wait";
            }
         }
      }
    </script></head><body><table width = "100%" height = "100%" border = "0"
      cellpadding = "0" cellspacing = "0"&gt;&lt;tr&gt;&lt;td align = "center"&gt;&lt;form name = "filepost" method = "post" 
               action = "file.php" enctype = "multipart/form-data" id = "file"&gt;&lt;table width = "300" border = "0" cellspacing = "0" 
                  cellpadding = "0"&gt;&lt;tr valign = "bottom"&gt;&lt;td height = "20"&gt;Your Name:&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;input name = "from" type = "text" id = "from" size = "30"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr valign = "bottom"&gt;&lt;td height = "20"&gt;Your Email Address:&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td class = "frmtxt2"&gt;&lt;input name = "emaila" type = "text" id = "emaila" size = "30"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td height = "20" valign = "bottom"&gt;Attach File:&lt;/td&gt;&lt;/tr&gt;&lt;tr valign = "bottom"&gt;&lt;td valign = "bottom"&gt;&lt;input name = "filea" type = "file" id = "filea" size = "16"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td height = "40" valign = "middle"&gt;&lt;input name = "Reset2" type = "reset" id = "Reset2" value = "Reset"&gt;&lt;input name = "Submit2" type = "submit" value = "Submit" onClick = "return CheckData45()"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/form&gt;&lt;center&gt;&lt;table width = "400"&gt;&lt;tr&gt;&lt;td id = "one"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/center&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following output −

    PHP Sending Emails