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. 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 − 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 − 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 − The PHP script on the server retrieves the data from AJAX request and sends back the 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 application’s 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. A 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 − 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 − To generalize the basic idea of handling the flashed messages, we shall write a function that adds a message to the $_SESSION − Let us also have another function that reads back a message, flashes it on the browser, and removes it from the $_SESSION. 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 − Use the following flash() function to create, format and flash the messages To implement the above method, call the flash() function on the first page. Navigate to another page and call the flash() function to retrieve and display the message − 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 (PRG)
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. 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 − If you press Continue, the same data is posted again. The problem can be understood with the following figure − Following steps are taken in the PHP script to avoid the problem − Example Here is the PHP code that uses the PRG technique − Open Compiler
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. The htmlspecialchars() Function This function converts special characters to HTML entities. 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 − Character Replaced by & (ampersand) & ” (double quote) ", unless ENT_NOQUOTES is set ‘ (single quote) ' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set < (less than) < > (greater than) > 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.No Constant & Description 1 ENT_COMPATWill convert double-quotes and leave single-quotes alone. 2 ENT_QUOTESWill convert both double and single quotes. 3 ENT_NOQUOTESWill leave both double and single quotes unconverted. 4 ENT_IGNOREdiscard invalid code unit sequences instead of returning an empty string. 5 ENT_SUBSTITUTEReplace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or � 6 ENT_DISALLOWEDReplace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or � (otherwise) instead of leaving them as is. This may be useful. 7 ENT_HTML401Handle code as HTML 4.01. 8 ENT_XML1Handle code as XML 1. 9 ENT_XHTMLHandle code as XHTML. 10 ENT_HTML5Handle code as HTML 5. Example Take a look at the following example − Open Compiler It will produce the following output − The strip_tags() Function The strip_tags() function removes all the HTML and PHP tags from a given 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 − Open Compiler It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The addslashes() Function The addslashes() function adds backslashes to a string. The function returns a string with backslashes added before characters that need to be escaped. These characters are − 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 − Open Compiler It will produce the following output − The filter_var() Function With the help of a specific filter flag, you can use filter_var() function to sanitize user input. The $value parameter is a variable whose value needs to be sanitized. The $filter parameter is any of the predefined filter constants. Sr.No ID & Description 1 FILTER_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 ‘”<>& 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 <strong>ENT_QUOTES</strong> set. Encoding quotes can be disabled by setting <strong>FILTER_FLAG_NO_ ENCODE_QUOTES</strong>.</td></tr><tr><td>8</td><td><strong>FILTER_SANITIZE_URL</strong>Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]<>#%”;/?:@&=. 9 FILTER_UNSAFE_RAW Example The following code shows how you can sanitize Email data − Open Compiler It will produce the following output − [email protected] Example The following code shows how you can sanitize URLs − Open Compiler It will produce the following output −
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. The configuration for Windows should look something like this − 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 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. Parameters 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. Open Compiler It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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. Example Use the following PHP script to send email with PHPMailer library − Phpmailer.php Use the following HTML form to compose the mail message. The form is submitted to the above phpmail.php script Email.html 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 − Open Compiler It will produce the following output −
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. Example 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’ => ‘private’, ‘read_and_close’ => 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.save_handler It defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. session.auto_start It specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled). 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. 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. 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. session.upload_progress.enabled It enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled. 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.
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 superglobal 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. 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. 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 − Open Compiler The browser will show a random string as the output − A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string. 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 − 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 − 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. Open Compiler Refresh the browser multiple times to simulate repeated visits. The browser displays the counter − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − Here is the call which will destroy all the session variables − 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. Save this code as “hello.php” in the document root folder, and open it in a client browser. Press the Submit button. The browser will show the session variables created − The browser navigates to another page by following the link shown. It reads back the session variables.
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. 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 − 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 − 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. Parameters Here is the detail of all the arguments − 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. Run this script from the document root of the Apache server. You should see this message − If this script is re-executed, the cookie is now already set. 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. A foreach loop as below retrieves all the cookies − 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 − SetCookie.php reads the form data and sets the cookies. With another getcookie.php code, we can retrieve the cookies set. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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. You can use isset() function to check if a cookie is set or not. 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 − The browser shows the following response − You may also set array cookies by using array notation in the cookie name. 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. The process of uploading a file follows these steps − 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 − 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. Open Compiler 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. 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) − Click the File button, browse to the desired file to be uploaded, and click the Upload button. The server responds with the following message −
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 Try out following example by putting the source code in test.php script. It will produce the following result − 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. Try out following example by putting the source code in test.php script. It will produce the following result − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 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” − 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 − 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” − Open Compiler In your browser, enter the URL “http://localhost/hello.html” − 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 − 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 − 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.