PHP – Type Hints ”; Previous Next PHP supports using “type hints” at the time of declaring variables in the function definition and properties or instance variables in a class. PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a variable before assigning it any value. The PHP parser tries to cast the variables into compatible type as far as possible. Hence, if one of values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation. Example Take a look at the following example − <?php function addition($x, $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } $x=”10″; $y=20; addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 However, if $x in the above example is a string that doesn’t hold a valid numeric representation, then you would encounter an error. <?php function addition($x, $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } $x=”Hello”; $y=20; addition($x, $y); ?> It will produce the following output − PHP Fatal error: Uncaught TypeError: Unsupported operand types: string + int in hello.php:5 Type-hinting is supported from PHP 5.6 version onwards. It means you can explicitly state the expected type of a variable declared in your code. PHP allows you to type-hint function arguments, return values, and class properties. With this, it is possible to write more robust code. Let us incorporate type-hinting in the addition function in the above program − function addition($x, $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } The type-hinting feature is mostly used by IDEs (Integrated Development Environment) to prompt the user about the expected types of the parameters used in function declaration. The following figure shows the VS Code editor popping up the function prototype as you type − If the cursor hovers on the name of the function, the type declarations for the parameters and the return value are displayed − Note that by merely using the data types in the variable declarations doesn’t prevent the unmatched type exception raised, as PHP is a dynamically typed language. In other words, $x=”10″ and $y=20 will still result in the addition as 30, where as $x=”Hello” makes the parser raise the error. strict_types PHP can be made to impose stricter rules for type conversion, so that “10” is not implicitly converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement. The declare() statement must be the first statement in the PHP code, just after the “<?php” tag. Example <?php declare (strict_types=1); function addition(int $x, int $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } $x=10; $y=20; addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 Now, if $x is set to “10”, the implicit conversion wont take place, resulting in the following error − PHP Fatal error: Uncaught TypeError: addition(): Argument #1 ($x) must be of type int, string given The VS Code IDE too indicates the error of the same effect − From PHP 7 onwards with type-hinting support has been extended for function returns to prevent unexpected return values. You can type-hint return values by adding the intended type after the parameter list prefixed with a colon (:) symbol. Example Let us add a type hint to the return value of the addition function above − <?php declare (strict_types=1); function addition(int $x, int $y) : int { return $x+$y; } $x=10; $y=20; $result = addition($x, $y); echo “First number: $x Second number: $y Addition: ” . $result; ?> Here too, if the function is found to return anything other than an integer, the IDE indicates the reason even before you run. Union Types The PHP introduced union types with its version 8.0. You can now specify more than one type for a single declaration. The data types are separated by the “|” symbol. Example In the definition of addition() function below, the $x and $y arguments can be of int or float type. <?php declare (strict_types=1); function addition(int|float $x, int|float $y) : float { return $x+$y; } $x=10.55; $y=20; $result = addition($x, $y); echo “First number: $x Second number: $y Addition: ” . $result; ?> Type-hinting in Class In PHP, from version 7.4 onwards, you can use the type hints in declaration of class properties and methods. Example In the following example, the class constructor uses type hints − <?php declare (strict_types=1); class Student { public $name; public $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } public function dispStudent() { echo “Name: $this->name Age: $this->age”; } } $s1 = new Student(“Amar”, 21); $s1->dispStudent(); ?> It is also possible to use type hints in the declaration of class properties. class Student { public string $name; public int $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function dispStudent() { echo “Name: $this->name Age: $this->age”; } } The most commonly encountered errors during program development are type errors. The type-hinting feature helps in reducing them. Print Page Previous Next Advertisements ”;
Category: php
PHP – Array Destructuring
PHP – Array Destructuring ”; Previous Next In PHP, the term Array destructuring refers to the mechanism of extracting the array elements into individual variables. It can also be called unpacking of array. PHP’s list() construct is used to destrucrure the given array assign its items to a list of variables in one statement. list($var1, $var2, $var3, . . . ) = array(val1, val2, val3, . . .); As a result, val1 is assigned to $var1, val2 to $var2 and so on. Even though because of the parentheses, you may think list() is a function, but it’s not as it doesn’t have return value. PHP treats a string as an array, however it cannot be unpacked with list(). Moreover, the parenthesis in list() cannot be empty. Instead of list(), you can also use the square brackets [] as a shortcut for destructuring the array. [$var1, $var2, $var3, . . . ] = array(val1, val2, val3, . . .); Example Take a look at the following example − <?php $marks = array(50, 56, 70); list($p, $c, $m) = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; # shortcut notation [$p, $c, $m] = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; ?> It will produce the following output − Physics: 50 Chemistry: 56 Maths: 70 Physics: 50 Chemistry: 56 Maths: 70 Destructuring an Associative Array Before PHP 7.1.0, list() only worked on numerical arrays with numerical indices start at 0. PHP 7.1, array destructuring works with associative arrays as well. Let us try to destructure (or unpack) the following associative array, an array with non-numeric indices. $marks = array(”p”=>50, ”c”=>56, ”m”=>70); To destructure this array the list() statement associates each array key with a independent variable. list(”p”=>$p, ”c”=>$c, ”m”=>$m) = $marks; Instead, you can also use the [] alternative destructuring notation. [”p”=>$p, ”c”=>$c, ”m”=>$m] = $marks; Try and execute the following PHP script − <?php $marks = array(”p”=>50, ”c”=>56, ”m”=>70); list(”p”=>$p, ”c”=>$c, ”m”=>$m) = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; # shortcut notation [”p”=>$p, ”c”=>$c, ”m”=>$m] = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; ?> Skipping Array Elements In case of an indexed array, you can skip some of its elements in assign only others to the required variables <?php $marks = array(50, 56, 70); list($p, , $m) = $marks; echo “Physics: $p Maths: $m” . PHP_EOL; # shortcut notation [$p, , $m] = $marks; echo “Physics: $p Maths: $m” . PHP_EOL; ?> In case of an associative array, since the indices are not incremental starting from 0, it is not necessary to follow the order of elements while assigning. <?php $marks = array(”p”=>50, ”c”=>56, ”m”=>70); list(”c”=>$c, ”p”=>$p, ”m”=>$m) = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; [”c”=>$c, ”m”=>$m, ”p”=>$p] = $marks; # shortcut notation echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; ?> Destructuring a Nested Array You can extend the concept of array destructuring to nested arrays as well. In the following example, the subarray nested inside is an indexed array. <?php $marks = [”marks” => [50, 60, 70]]; [”marks” => [$p, $c, $m]] = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; ?> Destructuring works well even if the nested array is also an associative array. <?php $marks = [”marks” => [”p”=>50, ”c”=>60, ”m”=>70]]; [”marks” => [”p”=>$p, ”c”=>$c, ”m”=>$m]] = $marks; echo “Physics: $p Chemistry: $c Maths: $m” . PHP_EOL; ?> Print Page Previous Next Advertisements ”;
PHP.INI File Configuration
PHP.INI File Configuration ”; Previous Next On installing PHP software on your machine, php.ini is created in the installation directory. In case of XAMPP, php.ini is found in c:xammphp folder. It is an important configuration file that controls the performance and sets all the PHP related parameters. The phpinfo() function displays a list of different parameters and their current values of PHP, Aache, MySQL and other parts of the web server installation. Run the following code to display the settings, one of which shows the path to the “php.ini” file: <?php echo phpinfo(); ?> Loaded Configuration File Locate the Loaded Configuration File setting that displays the location of php.ini file C:xamppphpphp.ini Different aspects of PHP’s behaviour are configured by a large number of parameters (called directives). The “php.ini” file comes with most of the lines starting with semicolon (;) symbol – indicating that the line is commented. The uncommented line is actually the effective directive and its value. In other words, to activate and assign a value to a particular directive, remove the leading semicolon. directive = value Directive names are *case sensitive. Directives are variables used to configure PHP or PHP extensions. Note that there is no name validation, so if an expected directive is not found a default value will be used, which can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one of the INI constants (On, Off, True, False, Yes, No and None). Actually, the C:XAMPPPHP folder contains two INI files, one to be used in production environment and other in development environment. The php.ini-development.ini is very similar to its production variant, except it is much more verbose when it comes to errors. In development stage, copy this as php.ini to be able to trace the bugs in the code. Once the code is ready for deployment, use php.ini-production.ini file as the effective php.ini file, which essentially supress the error messages to a large extent. The directives in php.ini are divided in different categories, like Error handling, data handling, path and directories, file uploads, PHP extensions and module settings. Here is a list of some of the important directives in “php.ini” file: short_open_tag = Off Short open tags look like this: <? ?>. This option must be set to Off if you want to use XML functions. safe_mode = Off If this is set to On, you probably compiled PHP with the –enable-safe-mode flag. Safe mode is most relevant to CGI use. See the explanation in the section “CGI compile-time options”. earlier in this chapter. safe_mode_exec_dir = [DIR] This option is relevant only if safe mode is on; it can also be set with the –with-exec-dir flag during the Unix build process. PHP in safe mode only executes external binaries out of this directory. The default is /usr/local/bin. This has nothing to do with serving up a normal PHP/HTML Web page. safe_mode_allowed_env_vars = [PHP_] This option sets which environment variables users can change in safe mode. The default is only those variables prepended with “PHP_”. If this directive is empty, most variables are alterable. safe_mode_protected_env_vars = [LD_LIBRARY_PATH] This option sets which environment variables users can”t change in safe mode, even if safe_mode_allowed_env_vars is set permissively disable_functions = [function1, function2…] A welcome addition to PHP4 configuration and one perpetuated in PHP5 is the ability to disable selected functions for security reasons. Previously, this necessitated hand-editing the C code from which PHP was made. Filesystem, system, and network functions should probably be the first to go because allowing the capability to write files and alter the system over HTTP is never such a safe idea. max_execution_time = 30 The function set_time_limit() won.t work in safe mode, so this is the main way to make a script time out in safe mode. In Windows, you have to abort based on maximum memory consumed rather than time. You can also use the Apache timeout setting to timeout if you use Apache, but that will apply to non-PHP files on the site too. error_reporting = E_ALL & ~E_NOTICE The default value is E_ALL & ~E_NOTICE, all errors except notices. Development servers should be set to at least the default; only production servers should even consider a lesser value error_prepend_string = [“”] With its bookend, error_append_string, this setting allows you to make error messages a different color than other text, or what have you. warn_plus_overloading = Off This setting issues a warning if the + operator is used with strings, as in a form value. variables_order = EGPCS This configuration setting supersedes gpc_order. Both are now deprecated along with register_globals. It sets the order of the different variables: Environment, GET, POST, COOKIE, and SERVER (aka Built-in). You can change this order around. Variables will be overwritten successively in left-to-right order, with the rightmost one winning the hand every time. This means if you left the default setting and happened to use the same name for an environment variable, a POST variable, and a COOKIE variable, the COOKIE variable would own that name at the end of the process. In real life, this doesn”t happen much. register_globals = Off This setting allows you to decide whether you wish to register EGPCS variables as global. This is now deprecated, and as of PHP4.2, this flag is set to Off by default. Use superglobal arrays instead. All the major code listings in this book use superglobal arrays. magic_quotes_gpc = On This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of forms which possibly submit to themselves or other forms and display form values, you may need to set this directive to On or prepare to use addslashes() on string-type data. magic_quotes_runtime = Off This setting
PHP – MySQL Login
PHP – MySQL Login ”; Previous Next MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password. You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed. Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data use mydb; CREATE TABLE `admin` ( `username` varchar(10) NOT NULL, `passcode` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; INSERT INTO `admin` (`username`, `passcode`) VALUES (”guest”, ”abc123”), (”manager”, ”secret”), (”user”, ”test”); ALTER TABLE `admin` ADD PRIMARY KEY (`username`); COMMIT; The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php” Config.php <?php define(”DB_SERVER”, ”localhost”); define(”DB_USERNAME”, ”root”); define(”DB_PASSWORD”, ””); define(”DB_DATABASE”, ”mydb”); $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); ?> This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs. $myusername = mysqli_real_escape_string($db,$_POST[”username”]); $mypassword = mysqli_real_escape_string($db,$_POST[”password”]); $sql = “SELECT * FROM admin WHERE username = ”$myusername” and passcode = ”$mypassword””; $result = mysqli_query($db,$sql); $row = mysqli_num_rows($result); If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script. Login.php Save the following code as “login.php” − <?php include(“config.php”); session_start(); $error=””; if($_SERVER[“REQUEST_METHOD”] == “POST”) { // username and password sent from form $myusername = mysqli_real_escape_string($db,$_POST[”username”]); $mypassword = mysqli_real_escape_string($db,$_POST[”password”]); $sql = “SELECT * FROM admin WHERE username = ”$myusername” and passcode = ”$mypassword””; $result = mysqli_query($db,$sql); $row = mysqli_num_rows($result); $count = mysqli_num_rows($result); if($count == 1) { // session_register(“myusername”); $_SESSION[”login_user”] = $myusername; header(“location: welcome.php”); } else { $error = “Your Login Name or Password is invalid”; } } ?> <html> <head> <title>Login Page</title> <style type = “text/css”> body { font-family:Arial, Helvetica, sans-serif; font-size:14px; } label { font-weight:bold; width:100px; font-size:14px; } .box { border:#666666 solid 1px; } </style> </head> <body bgcolor = “#FFFFFF”> <div align = “center”> <div style = “width:300px; border: solid 1px #333333; ” align = “left”> <div style = “background-color:#333333; color:#FFFFFF; padding:3px;”><b>Login</b></div> <div style = “margin:30px”> <form action = “” method = “post”> <label>UserName :</label><input type = “text” name = “username” class = “box”/><br /><br /> <label>Password :</label><input type = “password” name = “password” class = “box” /><br/><br /> <input type = “submit” value = ” Submit “/><br /> </form> <div style = “font-size:11px; color:#cc0000; margin-top:10px”><?php echo $error; ?></div> </div> </div> </div> </body> </html> Session.php The following is the session.php code file. It checks if the session variable is set; then the user credentials will be assigned to the $login_session variable. If not, the user is redirected back to the login.php file. <?php // Start the session session_start(); if(!isset($_SESSION[”login_user”])){ header(“location: login.php”); die(); } $login_session = $_SESSION[”login_user”]; ?> Welcome.php The “welcome.php” script gets invoked when the user is authenticated. It reads the session variable to display a welcome message. <?php include(”session.php”); ?> <html> <head> <title>Welcome </title> </head> <body> <h1>Welcome <?php echo $login_session; ?></h1> <h2><a href = “logout.php”>Sign Out</a></h2> </body> </html> Logout.php Finally, the logout script removes the destroys the session and redirects the user to the login page. <?php session_start(); if(session_destroy()) { header(“Location: login.php”); } ?> To start the login application, visit “http://localhost/login.php” Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message − If the query doesn’t fetch any matching row, the error message is displayed as follows − Print Page Previous Next Advertisements ”;
PHP – AJAX RSS Feed Example
PHP – AJAX RSS Feed Example ”; Previous Next 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 && 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 . “</a>”); echo(“<br>”); echo($channel_desc . “</p>”); $x = $xmlDoc->getElementsByTagName(”item”); for ($i = 0; $i<=2; $i++) { $item_title = $x->item($i)->getElementsByTagName(”title”) ->item(0)->childNodes->item(0)->nodeValue; $item_link = $x->item($i)->getElementsByTagName(”link”) ->item(0)->childNodes->item(0)->nodeValue; $item_desc = $x->item($i)->getElementsByTagName(”description”) ->item(0)->childNodes->item(0)->nodeValue; echo (“<p><a href = ”” . $item_link . “”>” . $item_title . “</a>”); echo (“<br>”); echo ($item_desc . “</p>”); } ?> It will produce the following output − Print Page Previous Next Advertisements ”;
PHP – AJAX Auto Complete Search ”; Previous Next 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 server’s 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 && 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->nodeValue}”, $q) !== false) { $result .= “{$node->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. Print Page Previous Next Advertisements ”;
PHP – XML Introduction
PHP – XML Introduction ”; Previous Next With the help of PHP’s 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 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. 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. Print Page Previous Next Advertisements ”;
PHP – Session Options
PHP – Session Options ”; Previous Next 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. Print Page Previous Next Advertisements ”;
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 ”;