PHP – SAX Parser Example

PHP – SAX Parser Example ”; Previous Next PHP has the XML parser extension enabled by default in the php.ini settings file. This parser implements SAX API, which is an event-based parsing algorithm. An event-based parser doesn’t 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. SAX based parsing mechanism is faster than the tree based parsers. PHP library includes functions to handle the XML events, as explained in this chapter. The first step in parsing a XML document is to have a parser object, with xml_parse_create() function xml_parser_create(?string $encoding = null): XMLParser This function creates a new XML parser and returns an object of XMLParser to be used by the other XML functions. The xml_parse() function starts parsing an XML document xml_parse(XMLParser $parser, string $data, bool $is_final = false): int xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary. The XMLParser extension provides different event handler functions. xml_set_element_handler() This function sets the element handler functions for the XML parser. Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags. xml_set_element_handler(XMLParser $parser, callable $start_handler, callable $end_handler): true The start_handler() function is called when a new XML element is opened. end_handler() function is called when an XML element is closed. xml_set_character_data_handler() This function sets the character data handler function for the XML parser parser. Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. xml_set_character_data_handler(XMLParser $parser, callable $handler): true xml_set_processing_instruction_handler() This function sets the processing instruction (PI) handler function for the XML parser parser. <?php ?> is a processing instruction, where php is called the “PI target”. The handling of these are application-specific. xml_set_processing_instruction_handler(XMLParser $parser, callable $handler): true A processing instruction has the following format − <?target data ?> xml_set_default_handler() This function sets the default handler function for the XML parser parser. What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler. xml_set_default_handler(XMLParser $parser, callable $handler): true Example The following example demonstrates the use of SAX API for parsing the XML document. We shall use the SAX.xml as below − <?xml version = “1.0” encoding = “utf-8″?> <tutors> <course> <name>Android</name> <country>India</country> <email>[email protected]</email> <phone>123456789</phone> </course> <course> <name>Java</name> <country>India</country> <email>[email protected]</email> <phone>123456789</phone> </course> <course> <name>HTML</name> <country>India</country> <email>[email protected]</email> <phone>123456789</phone> </course> </tutors> Example The PHP code to parse the above document is given below. It opens the XML file and calls xml_parse() function till its end of file is reached. The event handlers store the data in tutors array. Then the array is echoed element wise. <?php // Reading XML using the SAX(Simple API for XML) parser $tutors = array(); $elements = null; // Called to this function when tags are opened function startElements($parser, $name, $attrs) { global $tutors, $elements; if(!empty($name)) { if ($name == ”COURSE”) { // creating an array to store information $tutors []= array(); } $elements = $name; } } // Called to this function when tags are closed function endElements($parser, $name) { global $elements; if(!empty($name)) { $elements = null; } } // Called on the text between the start and end of the tags function characterData($parser, $data) { global $tutors, $elements; if(!empty($data)) { if ($elements == ”NAME” || $elements == ”COUNTRY” || $elements == ”EMAIL” || $elements == ”PHONE”) { $tutors[count($tutors)-1][$elements] = trim($data); } } } $parser = xml_parser_create(); xml_set_element_handler($parser, “startElements”, “endElements”); xml_set_character_data_handler($parser, “characterData”); // open xml file if (!($handle = fopen(”sax.xml”, “r”))) { die(“could not open XML input”); } while($data = fread($handle, 4096)) { xml_parse($parser, $data); } xml_parser_free($parser); $i = 1; foreach($tutors as $course) { echo “course No – “.$i. ”<br/>”; echo “course Name – “.$course[”NAME”].”<br/>”; echo “Country – “.$course[”COUNTRY”].”<br/>”; echo “Email – “.$course[”EMAIL”].”<br/>”; echo “Phone – “.$course[”PHONE”].”<hr/>”; $i++; } ?> The above code gives the following output − course No – 1 course Name – Android Country – India Email – [email protected] Phone – 123456789 ________________________________________ course No – 2 course Name – Java Country – India Email – [email protected] Phone – 123456789 ________________________________________ course No – 3 course Name – HTML Country – India Email – [email protected] Phone – 123456789 ________________________________________ Print Page Previous Next Advertisements ”;

PHP – Create Directory

PHP – Create Directory ”; Previous Next Computer files are stored in the local storage device (called drive) in a hierarchical order, where a directory contains one or more files as well as subdirectories. Respective DOS commands defined in operating systems Windows, Linux etc. are used to create and manage directories. PHP provides directory management functions to create a directory, change the current directory and remove a certain directory. This chapter discusses the usage of the following directory functions in PHP − The mkdir() Function The mkdir() function creates a new directory whose path is given as one of the parameters to the function mkdir( string $directory, int $permissions = 0777, bool $recursive = false, ?resource $context = null ): bool Parameters $directory − The first parameter $directory is mandatory. It is a string with either absolute or relative path of the new directory to be created. $permissions − The second parameter $permissions is an octal number with four octal digits. The first digit is always zero, second specifies permissions for the owner, third for the owner”s user group and fourth for everybody else. Each digit is the sum of values for each type of permission − 1 = execute permission 2 = write permission 4 = read permission The default value of $permissions parameters is 0777, which means the directory is created with execute, write and read permissions enabled. Note that the $permissions parameter is ignored when working on Windows OS. $recursive − If true, then any parent directories to the directory specified will also be created, with the same permissions. $context − This optional parameter is the stream resource. The mkdir() function returns either true or false, indicating if the function has been successfully executed or not. Examples Here are some examples of mkdir() function. The following call to mkdir() creates a subdirectory inside the current working directory. The dot indicates that the path is relative. $dir = “./mydir/”; mkdir($dir); We can give the string parameter that contains the absolute path of the directory to be created. $dir = “c:/newdir/”; mkdir($dir); The following call to mkdir() contains nested directory structure inside the current directory, as the $recursive parameter is set to true. $dirs = “./dir1/dir2/dir3/”; mkdir($dirs, 0777, true); The Windows explorer will show the nested directory structure as follows − The chdir() Function The chdir() function in PHP corresponds to the chdir or cd command in Linux/Windows. It causes the current directory to be changed as required. chdir(string $directory): bool The string parameter to this function is either an absolute or relative path of a directory to which the current directory needs to be changed to. It returns true or false. The getcwd() Function The getcwd() function works similar to pwd command in Ubuntu Linux, and returns the path to the current working directory. Example With the following code snippet, PHP displays the current working directory before and after changing the current working directory. A couple of files are created inside the new current directory. With the scandir() function, the files are listed. <?php echo “current directory: “. getcwd() . PHP_EOL; $dir = “./mydir”; chdir($dir); echo “current directory changed to: “. getcwd() .PHP_EOL; $fp = fopen(“a.txt”, “w”); fwrite($fp, “Hello World”); fclose($fp); copy(“a.txt”, “b.txt”); $dir = getcwd(); foreach(scandir($dir) as $file) echo $file . PHP_EOL; ?> It will produce the following output − current directory: C:xamppphp current directory changed to: C:xamppphpmydir . .. a.txt b.txt The rmdir() Function The rmdir() function removes a certain directory whose path is given as parameter. The directory to be removed must be empty. $dir = “c:/newdir/”; rmdir($dir) or die(“The directory is not present or not empty”); Print Page Previous Next Advertisements ”;

PHP – Sanitize Input

PHP – Sanitize Input ”; Previous Next 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. 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 − Character Replaced 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.No Constant & Description 1 ENT_COMPAT Will convert double-quotes and leave single-quotes alone. 2 ENT_QUOTES Will convert both double and single quotes. 3 ENT_NOQUOTES Will leave both double and single quotes unconverted. 4 ENT_IGNORE discard invalid code unit sequences instead of returning an empty string. 5 ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; 6 ENT_DISALLOWED Replace 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. 7 ENT_HTML401 Handle code as HTML 4.01. 8 ENT_XML1 Handle code as XML 1. 9 ENT_XHTML Handle code as XHTML. 10 ENT_HTML5 Handle 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 –> <a href=”/test.html”>Click Here</a>”; 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.No ID & Description 1 FILTER_SANITIZE_EMAIL Remove all characters except letters, digits and !#$%&”*+-=?^_`{|}~@.[]. 2 FILTER_SANITIZE_ENCODED URL-encode string, optionally strip or encode special characters. 3 FILTER_SANITIZE_ADD_SLASHES Apply addslashes(). (Available as of PHP 7.3.0). 4 FILTER_SANITIZE_NUMBER_FLOAT Remove all characters except digits, +- and optionally .,eE. 5 FILTER_SANITIZE_NUMBER_INT Remove all characters except digits, plus and minus sign. 6 FILTER_SANITIZE_SPECIAL_CHARS HTML-encode ””<>& and characters with ASCII value less than 32, optionally strip or encode other special characters. 7 FILTER_SANITIZE_FULL_SPECIAL_CHARS Equivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ ENCODE_QUOTES. td> 8 FILTER_SANITIZE_URL Remove all characters except letters, digits and $-_.+!*”(),{}|\^~[]`<>#%”;/?:@&=. 9 FILTER_UNSAFE_RAW Example The following code shows how you can sanitize Email data − <?php $a = ”abc [email protected]”; $sa = filter_var($a,

PHP – File Inclusion

PHP – File Inclusion ”; Previous Next 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. The include() Function The require() 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. 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> It will produce the following result − 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. 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> 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. Print Page Previous Next Advertisements ”;

PHP – Do…While Loop

PHP – Do…While Loop ”; Previous Next The “do…while” loop is another looping construct available in PHP. This type of loop is similar to the while loop, except that the test condition is checked at the end of each iteration rather than at the beginning of a new iteration. The while loop verifies the truth condition before entering the loop, whereas in “do…while” loop, the truth condition is verified before re entering the loop. As a result, the “do…while” loop is guaranteed to have at least one iteration irrespective of the truth condition. The following figure shows the difference in “while” loop and “do…while” loop by using a comparative flowchart representation of the two. The syntax for constituting a “do…while” loop is similar to its counterpart in C language. do { statements; } while (expression); Example Here is a simple example of “do…while” loop that prints iteration numbers 1 to 5. <?php $i=1; do{ echo “Iteration No: $i n”; $i++; } while ($i<=5); ?> It will produce the following output − Iteration No: 1 Iteration No: 2 Iteration No: 3 Iteration No: 4 Iteration No: 5 Example The following code uses a while loop and also generates the same output − <?php $i=1; while ($i<=5){ echo “<h3>Iteration No: $i</h3>”; $i++; } ?> Hence, it can be said that the “do…while” and “while” loops behave similarly. However, the difference will be evident when the initial value of the counter variable (in this case $i) is set to any value more than the one used in the test expression in the parenthesis in front of the while keyword. Example In the following code, both the loops – while and “do…while” – are used. The counter variable for the while loop is $i and for “do…while” loop, it is $j. Both are initialized to 10 (any value greater than 5). <?php echo “while Loop n”; $i=10; while ($i<=5){ echo “Iteration No: $i n”; $i++; } echo “do-while Loop n”; $j=10; do{ echo “Iteration No: $j n”; $j++; } while ($j<=5); ?> It will produce the following output − while Loop do – while Loop Iteration No: 10 The result shows that the while loop doesn’t perform any iterations as the condition is false at the beginning itself ($i is initialized to 10, which is greater than the test condition $i<=5). On the other hand, the “do…while” loop does undergo the first iteration even though the counter variable $j is initialized to a value greater than the test condition. We can thus infer that the “do…while” loop guarantees at least one iteration because the test condition is verified at the end of looping block. The while loop may not do any iteration as the test condition is verified before entering the looping block. Another syntactical difference is that the while statement in “do…while” terminates with semicolon. In case of while loop, the parenthesis is followed by a curly bracketed looping block. Apart from these, there are no differences. One can use both these types of loops interchangeably. Decrementing a “do…while” Loop To design a “do…while” with decrementing count, initialize the counter variable to a higher value, use decrement operator (–) inside the loop to reduce the value of the counter on each iteration, and set the test condition in the while parenthesis to run the loop till the counter is greater than the desired last value. Example In the example below, the counter decrements from 5 to 1. <?php $j=5; do{ echo “Iteration No: $j n”; $j–; } while ($j>=1); ?> It will produce the following output − Iteration No: 5 Iteration No: 4 Iteration No: 3 Iteration No: 2 Iteration No: 1 Traverse a String in Reverse Order In PHP, a string can be treated as an indexed array of characters. We can extract and display one character at a time from end to beginning by running a decrementing “do…while” loop as follows − <?php $string = “TutorialsPoint”; $j = strlen($string); do{ $j–; echo “Character at index $j : $string[$j] n”; } while ($j>=1); ?> It will produce the following output − Character at index 13 : t Character at index 12 : n Character at index 11 : i Character at index 10 : o Character at index 9 : P Character at index 8 : s Character at index 7 : l Character at index 6 : a Character at index 5 : i Character at index 4 : r Character at index 3 : o Character at index 2 : t Character at index 1 : u Character at index 0 : T Nested “do…while” Loops Like the for loop or while loop, you can also write nested “do…while” loops. In the following example, the upper “do…while” loop counts the iteration with $i, the inner “do…while” loop increments $j and each time prints the product of $i*j, thereby printing the tables from 1 to 10. <?php $i=1; $j=1; do{ print “n”; do{ $k = sprintf(“%4u”,$i*$j); print “$k”; $j++; } while ($j<=10); $j=1; $i++; } while ($i<=10); ?> It will produce the following output − 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54

PHP – Sending Emails

PHP – Sending Emails ”; Previous Next 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 − [mail function] ; For Win32 only. SMTP = smtp.secureserver.net ; For win32 only sendmail_from = [email protected] 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 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. mail( to, subject, message, headers, parameters ); Parameters 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 (rn) 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] rn”; $header .= “Cc:[email protected] rn”; $header .= “MIME-Version: 1.0rn”; $header .= “Content-type: text/htmlrn”; $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. Example Use the following PHP script to send email with PHPMailer library − Phpmailer.php <?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerSMTP; use PHPMailerPHPMailerException; 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->isSMTP(); // Set mailer to use SMTP $mail->Host = ”smtp.gmail.com”; $mail->SMTPAuth = true; $mail->Username = ”[email protected]”; // SMTP username $mail->Password = ”mypassword”; // SMTP password // Enable TLS encryption, ”ssl” also accepted $mail->SMTPSecure = ”tls”; $mail->Port = 587; $mail->setFrom([email protected]”, ”My_Name”); $mail->addReplyTo([email protected]”, ”My_Name”); $mail->addAddress($toemail); // Add a recipient $mail->isHTML(true); // Set email format to HTML $bodyContent=$message; $mail->Subject =$subject; $body = ”Dear”.$fname; $body .=”<p>”.$message.”</p>”; $mail->Body = $body; if(!$mail->send()) { echo ”Message could not be sent.”; echo ”Mailer Error: ” . $mail->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

PHP – Download File

PHP – Download File ”; Previous Next Most modern browsers allow files of certain types to be downloaded automatically, without any server-side code such as a PHP script. For example, a zip file, or an EXE file. If an HTML hyperlink points to a ZIP or EXE file, the browser downloads it and pops up a save dialog. However, text files, image files, etc., are not downloaded but opened in the browser, which you can save to your local filesystem. The readfile() Function To download such files (instead of the browser automatically opening them), we can use the readfile() function in PHP’s built-in function library. readfile(string $filename, bool $use_include_path = false, ?resource $context = null) : int|false This function reads a file and writes it to the output buffer. The second parameter $use_include_path is false by default, hence the file in the current directory will be downloaded. If set to true, the directories added to the include_path setting of php.ini configuration will be searched to locate the file to be downloaded. The readfile() function returns the number of bytes read or false even it is successfully completed or not. Example The following PHP script shows the usage of readfile() function. To download a file, the Content-Type response header should be set to application/octect-stream. This MIME type is the default for binary files. Browsers usually don”t execute it, or even ask if it should be executed. Additionally, setting the Content-Disposition header to attachment prompts the “Save As” dialog to pop up. <?php $filePath = ”welcome.png”; // Set the Content-Type header to application/octet-stream header(”Content-Type: application/octet-stream”); // Set the Content-Disposition header to the filename of the downloaded file header(”Content-Disposition: attachment; filename=””. basename($filePath).”””); // Read the contents of the file and output it to the browser. readfile($filePath); ?> Save the above script as “download.php” in the document root folder. Make sure that the file to be downloaded is present in the same folder. Start the server and visit http://localhost/download.php in the browser. You will get a “Save As” dialog as below − You can select a name and download the file. For a large file, you can read it from the file stream in the chunk of a certain predefined size. The browser offers to save it in the local filesystem, if the Content-Disposition head is set to “attachment”, as in the previous example. <?php $filename = ”welcome.png”; header(”Content-Type: application/octet-stream”); header(”Content-Disposition: attachment; filename=”” . basename($filename) . ”””); $handle = fopen($filename, ”rb”); $buffer = ””; $chunkSize = 1024 * 1024; ob_start(); while (!feof($handle)) { $buffer = fread($handle, $chunkSize); echo $buffer; ob_flush(); flush(); } fclose($handle); ?> Print Page Previous Next Advertisements ”;

PHP – Post-Redirect-Get (PRG)

PHP – Post-Redirect-Get (PRG) ”; Previous Next 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: <input type=”text” name=”first_name”> <br/> Last Name: <input type=”text” name=”last_name” /> <button type=”submit” name=”submit”>Submit</button> </form> </body> </html> 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 − 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: <input type=”text” name=”first_name”> <br /> Last Name: <input type=”text” name=”last_name” /> <button type=”submit” name=”submit”>Submit</button> </form> </body> </html> Print Page Previous Next Advertisements ”;

PHP – Sessions

PHP – Sessions ”; Previous Next 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. 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. 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 ($_SESSION as $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 “<h2>Following Session variables Created</h2>”; foreach ($_SESSION as $key=>$val) { echo “<h3>” . $key . “=>” . $val . “</h3>”; } echo “<a href=”test.php”><b>Click Here</b></a>”; } ?> </body> </html> 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. Print Page Previous Next Advertisements ”;

PHP – AJAX Search

PHP – AJAX Search ”; Previous Next 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 && 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. Print Page Previous Next Advertisements ”;