PHP â The “use” Statement ”; Previous Next The “use” keyword in PHP is found to be associated with multiple purposes, such as aliasing, inserting traits and inheriting variables in closures. Aliasing Aliasing is accomplished with the use operator. It allows you to refer to an external fully qualified name with an alias or alternate name. Example Take a look at the following example − use Mynamespacemyclass as Another; $obj = new Another; You can also have groupped use declaration as follows − use somenamespace{ClassA, ClassB, ClassC as C}; use function somenamespace{fn_a, fn_b, fn_c}; use const somenamespace{ConstA, ConstB, ConstC}; Traits With the help of use keyword, you can insert a trait into a class. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. Example Take a look at the following example − <?php trait mytrait { public function hello() { echo “Hello World from ” . __TRAIT__ .; } } class myclass { use mytrait; } $obj = new myclass(); $obj->hello(); ?> It will produce the following output − Hello World from mytrait Closures Closure is also an anonymous function that can access variables outside its scope with the help of the “use” keyword. Example Take a look at the following example − <?php $maxmarks=300; $percent=function ($marks) use ($maxmarks) { return $marks*100/$maxmarks; }; $m = 250; echo “marks=$m percentage=”. $percent($m); ?> It will produce the following output − marks=250 percentage=83.333333333333 Print Page Previous Next Advertisements ”;
Category: php
PHP – Variables
PHP – Variables ”; Previous Next A variable in PHP is a named memory location that holds data belonging to one of the data types. PHP uses the convention of prefixing a dollar sign ($) to the name of a variable. Variable names in PHP are case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As per the naming convention, “$name”, “$rate_of_int”, “$Age”, “$mark1” are examples of valid variable names in PHP. Invalid variable names: “name” (not having $ prefix), “$rate of int” (whitespace not allowed), “$Age#1” (invalid character #), “$11” (name not starting with alphabet). Variables are assigned with the “=” operator, with the variable on the left hand side and the expression to be evaluated on the right. No Need to Specify the Type of a Variable PHP is a dynamically typed language. There is no need to specify the type of a variable. On the contrary, the type of a variable is decided by the value assigned to it. The value of a variable is the value of its most recent assignment. Take a look at this following example − <?php $x = 10; echo “Data type of x: ” . gettype($x) . “n”; $x = 10.55; echo “Data type of x now: ” . gettype($x) . “”; ?> It will produce the following output − Data type of x: integer Data type of x now: double Automatic Type Conversion of Variables PHP does a good job of automatically converting types from one to another when necessary. In the following code, PHP converts a string variable “y” to “int” to perform addition with another integer variable and print 30 as the result. Take a look at this following example − <?php $x = 10; $y = “20”; echo “x + y is: “, $x+$y; ?> It will produce the following output − x + y is: 30 Variables are Assigned by Value In PHP, variables are always assigned by value. If an expression is assigned to a variable, the value of the original expression is copied into it. If the value of any of the variables in the expression changes after the assignment, it doesn’t have any effect on the assigned value. <?php $x = 10; $y = 20; $z = $x+$y; echo “(before) z = “. $z . “n”; $y=5; echo “(after) z = “. $z . “”; ?> It will produce the following output − (before) z = 30 (after) z = 30 Assigning Values to PHP Variables by Reference You can also use the way to assign values to PHP variables by reference. In this case, the new variable simply references or becomes an alias for or points to the original variable. Changes to the new variable affect the original and vice versa. To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). Take a look at this following example − <?php $x = 10; $y = &$x; $z = $x+$y; echo “x=”. $x . ” y=” . $y . ” z = “. $z . “n”; $y=20; $z = $x+$y; echo “x=”. $x . ” y=” . $y . ” z = “. $z . “”; ?> It will produce the following output − x=10 y=10 z = 20 x=20 y=20 z = 40 Variable Scope Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types − Local Variables Global Variables Static Variables Function Parameters Variable Naming Rules for naming a variable is − Variable names must begin with a letter or underscore character. A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc There is no size limit for variables. Print Page Previous Next Advertisements ”;
PHP – Type Casting
PHP – Type Casting ”; Previous Next The term “Type Casting” refers to conversion of one type of data to another. Since PHP is a weakly typed language, the parser coerces certain data types into others while performing certain operations. For example, a string having digits is converted to integer if it is one of the operands involved in the addition operation. Implicit Type Casting Here is an example of coercive or implicit type casting − <?php $a = 10; $b = ”20”; $c = $a+$b; echo “c = ” . $c; ?> In this case, $b is a string variable, cast into an integer to enable addition. It will produce the following output − c = 30 Let”s take another example. Here, an integer variable $a is converted to a string so that it is concatenated with a string variable. <?php $a = 10; $b = ”20”; $c = $a.$b; echo “c = ” . $c; ?> It will produce the following output − c = 1020 In addition to such coercive type conversion, there are other ways to explicitly cast one type of data to other. You can use PHP’s type casting operators or type casting functions for this purpose. Type Casting Operators To convert an expression of one type to another, you need to put the data type of the latter in parenthesis before the expression. $var = (type)expr; Some of the type casting operators in PHP are − (int) or (integer) casts to an integer (bool) or (boolean) casts to a boolean (float) or (double) or (real) casts to a float (string) casts to a string (array) casts to an array (object) casts to an object Casting to Integer You can easily convert a float value to an integer. Take a look at the following example − <?php $a = 9.99; $b = (int)$a; var_dump($b); ?> It will produce the following output − int(9) Note that the float value is not rounded to the nearest integer; instead it just returns the integer part. String to Integer Conversion The (int) operator also coverts a string to integer. The conversion is straightforward if the string consists of just digits. <?php $a = “99”; $b = (int)$a; var_dump($b); ?> Here, you will get the following output − int(99) Even if the string contains a floating point number, the (int) operator returns just the integer part. Now let”s take another example to understand a special case. If the string is alphanumeric, casting with (int) works differently. If the string starts with digits followed by non-numeric characters, only the initial digits are considered. If the string starts with non-numeric characters and the digits are in the middle, the csting operator returns “0”. Take a look at the following example − <?php $a = “10 Rs.”; $b = (int)$a; var_dump($b); $a = “$100”; $b = (int)$a; var_dump($b); ?> It will produce the following output − int(10) int(0) Casting to Float Type You can use either the (float) or (double) casting operator to explicitly convert a variable or expression to a float. <?php $a = 100; $b = (double)$a; var_dump($b); ?> It will produce the following output − float(100) A string containing any valid numeric representation may be cast to a float type by using a casting operator. <?php $a = “100”; $b = (double)$a; var_dump($b); $a = “9.99”; $b = (float)$a; var_dump($b); ?> Here, you will get the following output − float(100) float(9.99) The string gets converted to float even when it embeds a scientific notation of float. Take a look at the following example − <?php $a = “1.23E01”; $b = (double)$a; var_dump($b); $a = “5.5E-5″; $b = (float)$a; var_dump($b); ?> It will produce the following output − float(12.3) float(5.5E-5) All the non-numeric characters after the floating point numbers are ignored. Similarly, the string converts to “0” if it starts with any non-numeric character. See the following example − <?php $a = “295.95 only”; $b = (double)$a; var_dump($b); $a = “$2.50”; $b = (float)$a; var_dump($b); ?> It will produce the following output − float(295.95) float(0) Casting to String Type By using a casting operator, any expression evaluating to a floating-point or integer may be cast to a string type. Few examples are given below − <?php $a = 100; $b = (string)$a; var_dump($b); $x = 55.50; $y = (string)$x; var_dump($y); ?> You will get the following output − string(3) “100” string(4) “55.5” Casting to Bool Type Any non-zero number, either integer or float, is cast to true with (bool) operator. An expression evaluating to “0” returns false. A string is always cast to true. Take a look at the following example − <?php $a = 100; $b = (bool)$a; $x = 0; $y = (bool)$x; $m = “Hello”; $n = (bool)$m; var_dump($b); var_dump($y); var_dump($n); ?> It will produce the following output − bool(true) bool(false) bool(true) Type Casting Functions PHP includes the following built-in functions for performing type casting − intval() floatval() strval() Let”s discuss these built-in functions in detail. The intval() Function This function gets the integer value of a variable. intval(mixed $value, int $base = 10): int The $base parameter is 10 by default, which means the value is converted to decimal number. If the value is a float, the intval() function returns an integer, discarding the
PHP – MySQL
PHP & MySQL ”; Previous Next PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. What you should already have ? You have gone through MySQL tutorial to understand MySQL Basics. Downloaded and installed a latest version of MySQL. Created database user guest with password guest123. If you have not created a database then you would need root user and its password to create a database. We have divided this chapter in the following sections − Connecting to MySQL database − Learn how to use PHP to open and close a MySQL database connection. Create MySQL Database Using PHP − This part explains how to create MySQL database and tables using PHP. Delete MySQL Database Using PHP − This part explains how to delete MySQL database and tables using PHP. Insert Data To MySQL Database − Once you have created your database and tables then you would like to insert your data into created tables. This session will take you through real example on data insert. Retrieve Data From MySQL Database − Learn how to fetch records from MySQL database using PHP. Using Paging through PHP − This one explains how to show your query result into multiple pages and how to create the navigation link. Updating Data Into MySQL Database − This part explains how to update existing records into MySQL database using PHP. Deleting Data From MySQL Database − This part explains how to delete or purge existing records from MySQL database using PHP. Using PHP To Backup MySQL Database − Learn different ways to take backup of your MySQL database for safety purpose. Print Page Previous Next Advertisements ”;
PHP – Special Types
PHP â Special Types ”; Previous Next PHPâs two data types â resource and NULL â are classified as special types. An object of resource type refers to external resources like database connection, file streams etc. On the other hand, a NULL data type is a variable without any data assigned to it. In this chapter, we shall learn more about these types. Resource Type A PHP program often needs to interact with an external environment such as a database, or a disk file etc. These are treated as resources in PHP. Resource is a special data type that refers to any such external resource. PHP uses relevant functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable. PHP”s Zend engine uses reference counting system. Hence, a resource with zero reference count is destroyed automatically by garbage collector and the memory used by resource data type need not be freed manually. Different built-in PHP functions return respective resource variables. Subsequently, PHP uses them for interacting with the corresponding external environment. For example, the fopen() function returns a file resource, which acts as a file handle and the read/write operations on the file are facilitated by this resource variable. The following table summarizes different functions that return resource variables − Resource Type Built-in functions Definition Produced Sold bzip2 bzopen() bzclose() Bzip2 file curl curl_init() curl_close() Curl session ftp ftp_connect(), ftp_close() FTP stream mssql link mssql_connect() mssql_close() Link to Microsoft SQL Server database mysql link mysql_connect() mysql_close() Link to MySQL database mysql result mysql_db_query(), mysql_free_result() MySQL result oci8 connection oci_connect() oci_close() Connection to Oracle Database ODBC link odbc_connect() odbc_close() Link to ODBC database pdf document pdf_new() pdf_close() PDF document stream opendir() closedir() Dir handle stream fopen(), tmpfile() fclose() File handle socket socket_create() Socket_close() Socket handle xml xml_parser_create() xml_parser_free() XML parser zlib gzopen() gzclose() gz-compressed file zlib.deflate deflate_init() None() incremental deflate context zlib.inflate inflate_init() None() incremental inflate context PHP has get_resource_type() function that returns resource type of a variable. get_resource_type ( resource $handle ) : string where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type. There is also get_resource_id() function an integer identifier for the given resource. get_resource_id(resource $resource): int Example This function provides a type-safe way for generating the integer identifier for a given resource. <?php $fp = fopen(“hello.php”, “r”); $resource = get_resource_type($fp); $id = get_resource_id($fp); echo “The resource type is : $resource The resource ID is : $id”; ?> It will produce the following output − The resource type is : stream The resource ID is : 5 NULL type In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function. $var=NULL; It is possible to cast variable of other type to null, although casting null to other type has been deprecated from PHP 7.2. In earlier versions, casting was done using (unset)$var syntax Example The following example shows how to assign NULL to a variable <?php $var=NULL; var_dump($var); ?> It will produce the following output − NULL Example The following example performs null variable to other primary variables − <?php $var = NULL; var_dump( (int) $var); var_dump((float)$var); var_dump((bool) $var) ; var_dump( (boolean) $var); ?> It will produce the following output − int(0) float(0) bool(false) bool(false) Print Page Previous Next Advertisements ”;
PHP – Simple XML Parser
PHP – Simple XML Parser ”; Previous Next The SimpleXML extension of PHP provides a very simple and easy to use toolset to convert XML to an object that can be processed with normal property selectors and array iterators. It is a tree_based parser, and works well with simple XML files, but may face issues when working with larger and complex XML documents. The following functions are defined in SimpleXML extension − simplexml_load_file The simplexml_load_file() function interprets an XML file into an object − simplexml_load_file( string $filename, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespace_or_prefix = “”, bool $is_prefix = false ): SimpleXMLElement|false A well-formed XML document in the given file is converted into an object. The filename parameter is a string representing the XML file to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure. Example Take a look at the following example − <?php $xml = simplexml_load_file(“test.xml”) or die(“Error: Cannot create object”); print_r($xml); ?> It will produce the following output − SimpleXMLElement Object ( [Course] => Android [Subject] => Android [Company] => TutorialsPoint [Price] => $10 ) simplexml_load_string The simplexml_load_string() function interprets an XML file into an object. simplexml_load_string( string $filename, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespace_or_prefix = “”, bool $is_prefix = false ): SimpleXMLElement|false A well-formed XML document in the given string is converted into an object. The $data parameter is a string representing the XML document to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure. Example Take a look at the following example − <?php $data = “<?xml version = ”1.0” encoding = ”UTF-8”?> <note> <Course>Android</Course> <Subject>Android</Subject> <Company>TutorialsPoint</Company> <Price>$10</Price> </note>”; $xml = simplexml_load_string($data) or die(“Error: Cannot create object”); print_r($xml); ?> It will produce the following output − SimpleXMLElement Object ( [Course] => Android [Subject] => Android [Company] => TutorialsPoint [Price] => $10 ) simplexml_import_dom The simplexml_import_dom() function constructs a SimpleXMLElement object from a DOM node. simplexml_import_dom(SimpleXMLElement|DOMNode $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element. The node parameter is a DOM Element node. The optional class_name may be given so that simplexml_import_dom() will return an object of the specified sub class of the SimpleXMLElement class. The value returned by this function is a SimpleXMLElement or null on failure. Example Take a look at the following example − <?php $dom = new DOMDocument; $dom->loadXML(”<books><book><title>PHP Handbook</title></book></books>”); if (!$dom) { echo ”Error while parsing the document”; exit; } $s = simplexml_import_dom($dom); echo $s->book[0]->title; ?> It will produce the following output − PHP Handbook Get the Node Values The following code shows how to get the node values from an XML file and the XML should be as follows − <?xml version = “1.0” encoding = “utf-8”?> <tutorialspoint> <course category = “JAVA”> <title lang = “en”>Java</title> <tutor>Gopal</tutor> <duration></duration> <price>$30</price> </course> <course category = “HADOOP”> <title lang = “en”>Hadoop</title>. <tutor>Satish</tutor> <duration>3</duration> <price>$50</price> </course> <course category = “HTML”> <title lang = “en”>html</title> <tutor>raju</tutor> <duration>5</duration> <price>$50</price> </course> <course category = “WEB”> <title lang = “en”>Web Technologies</title> <tutor>Javed</tutor> <duration>10</duration> <price>$60</price> </course> </tutorialspoint> Example PHP code should be as follows − <?php $xml = simplexml_load_file(“books.xml”) or die(“Error: Cannot create object”); foreach($xml->children() as $books) { echo $books->title . “<br> “; echo $books->tutor . “<br> “; echo $books->duration . “<br> “; echo $books->price . “<hr>”; } ?> It will produce the following output − Java Gopal $30 ________________________________________ Hadoop Satish 3 $50 ________________________________________ html raju 5 $50 ________________________________________ Web Technologies Javed 10 $60 ________________________________________ Print Page Previous Next Advertisements ”;
PHP – Try…Catch
PHP Tryâ¦Catch ”; Previous Next In PHP, the keywords try, catch, throw and finally are provided to deal with exceptions. Whereas an Error is an unexpected program result, which cannot be handled by the program itself and the program has to be terminated with die() or setting a custom error handler. On the other hand, an exception refers to an unexpected situation which can be handled in such a way that the program may keep running after throwing the exception out of its normal flow. An exception can be thrown, and caught with the catch keyword within PHP code. A code block which is potentially prone to exception is surrounded by a try block. Each try must have at least one corresponding catch or finally block. Try, Throw, Catch, and Finally The four exception related keywords have the following role to play − Try − A block of code where some exception is likely to occur is placed in “try” block. If exception is not triggered, the code continues execution. However, if exception does occur, it is “thrown”. The execution is halted and PHP looks for matching “catch” block. If the exception is not caught, PHP issues a Fatal Error. Throw − Here is how you trigger an exception. Each “throw” must have at least one “catch” or “finally” block. Catch − a block that retrieves an exception and creates an object containing the exception information. Multiple catch blocks can be used to catch different exceptions. Finally − Code within a finally block is always executed after throw or catch block. Example Here is an example of exception handling technique. The code renders two text fields on the browser and asks the user to enter two numbers for their division to be performed. If the second number (denominator) is 0, an exception is thrown and the program enters the catch block and prints the exception message. Otherwise the result of division is displayed. <html> <body> <form action=”<?php echo $_SERVER[”PHP_SELF”];?>” method=”post”> <h3>First No: <input type=”text” name=”first”/></h3> <h3>Second No: <input type=”text” name=”second”/></h3> <input type=”submit” value=”Submit” /> </form> <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $x = $_POST[”first”]; $y = $_POST[”second”]; echo “$x $y”; try { if ($y == 0) { throw new Exception(“Division by Zero”); } $z = $x/$y; echo “<h3>x = $x y = $y Division = $z<br>”; } catch (Exception $e) { echo “<h3> Exception: ” . $e->getMessage(); } } ?> </body> </html> It will produce the following output − Case 1: x = 10 y = 5 Division = 2 Case 2: x = 10 y = 0 Exception: Division by Zero The Exception Class PHP throws an object of Exception class. In PHP, Exception class is the base for user exceptions. It implements throwable interface. This class defines the following methods − getMessage() This function returns the Exception message as a string − final public Exception::getMessage(): string getCode() This function returns the exception code as int in Exception − final public Exception::getCode(): int Take a look at the following example − try { throw new Exception(“Some error message”, 30); } catch(Exception $e) { echo “The exception code is: ” . $e->getCode(); } getFile() This function returns the filename in which the exception was created − final public Exception::getFile(): string Take a look at the following example − try { if ($y == 0) { throw new Exception(“Division by Zero”); } $z = $x/$y; echo “<h3>x = $x y = $y Division = $z<br>”; } catch (Exception $e) { echo “<h3> Exception: ” . $e->getMessage(). ” in ” . $e->getFile(); } It will produce the following output − Exception: Division by Zero in C:xampphtdocshello.php getLine() This function returns the line number where the exception was created − final public Exception::getLine(): int Example Take a look at the following example − <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $x = $_POST[”first”]; $y = $_POST[”second”]; echo “$x $y”; try { if ($y == 0) { throw new Exception(“Division by Zero”); } $z = $x/$y; echo “<h3>x = $x y = $y Division = $z<br>”; } catch (Exception $e) { echo “<h3> Exception: ” . $e->getMessage(). ” in ” . $e->getLine() . ” of ” . $e->getFile(); } } ?> It will produce the following output − Exception: Division by Zero in 21 of C:xampphtdocshello.php Multiple Catch Blocks PHP allows a series of catch blocks following a try block to handle different exception cases. Multiple catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions. Example The following example uses catch blocks to process DivisioByZeroError, TypeError, ArgumentCountError and InvalidArgumentException conditions. There is also a catch block to handle general Exception. <?php declare(strict_types=1); function divide(int $a, int $b) : int { return $a / $b; } $a=10; $b=0; try { if (!$b) { throw new DivisionByZeroError(”Division by zero.”); if (is_int($a)==FALSE || is_int($b)==FALSE) throw new InvalidArgumentException(“Invalid type of arguments”); $result=divide($a, $b); echo $result; } // if argument types not matching catch (TypeError $x) { echo $x->getMessage(); } // if denominator is 0 catch (DivisionByZeroError $y) { echo $y->getMessage(); } // if number of arguments not equal to 2 catch (ArgumentCountError $z) { echo $z->getMessage(); } // if argument types not matching catch (InvalidArgumentException $i) { echo $i->getMessage(); } // any uncaught exception catch (Exception $ex) { echo $ex->getMessage(); } ?> To begin with, since denominator is 0, “divide by 0” error will be displayed − Division by 0 Set $b=3 which will cause TypeError because divide function is expected to return integer but division results in float. divide(): Return
PHP – Quick Guide
PHP – Quick Guide ”; Previous Next PHP – Introduction PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was supposed to be an abbreviation for “Personal Home Page”, but it now stands for the recursive initialism “PHP: Hypertext Preprocessor”. Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI) programs in C, which he used to maintain in his personal homepage. Later on, He extended them to work with web forms and to communicate with databases. This implementation of PHP was “Personal Home Page/Forms Interpreter” or PHP/FI. Today, PHP is the world’s most popular server-side programming language for building web applications. Over the years, it has gone through successive revisions and versions. PHP Versions PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He called this suite of scripts “Personal Home Page Tools”. It can be regarded as PHP version 1.0. In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version 2.0 status. PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface for multiple databases, protocols and APIs, object-oriented programming support, and consistent language syntax. PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers, HTTP sessions, output buffering, secure ways of handling user input and several new language constructs. PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP”s development team includes dozens of developers and others working on PHP-related and supporting projects such as PEAR, PECL, and documentation. PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP 7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations and Anonymous Classes. PHP 8.0 was released on 26 November 2020. This is a major version having many significant improvements from its previous versions. One standout feature is Just-in-time compilation (JIT) that can provide substantial performance improvements. The latest version of PHP is 8.2.8, released on July 4th, 2023. PHP Application Areas PHP is one of the most widely used language over the web. Here are some of the application areas of PHP − PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Although it is especially suited to web development, you can also build desktop standalone applications as PHP also has a command-line interface. You can use PHP-GTK extension to build GUI applications in PHP. PHP is widely used for building web applications, but you are not limited to output only HTML. PHP”s ouput abilities include rich file types, such as images or PDF files, encrypting data, and sending emails. You can also output easily any text, such as JSON or XML. PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. PHP also supports other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, etc. Here are some more important features of PHP − PHP performs system functions. It can create, open, read, write, and close the files. PHP can handle forms. It can gather data from files, save data to a file, through email you can send data, return data to the user. You add, delete, modify elements within your database through PHP. Access cookies variables and set cookies. Using PHP, you can restrict users to access some pages of your website. It can encrypt data. PHP provides a large number of reusable classes and libraries are available on “PEAR” and “Composer”. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. “Composer” is a dependency management tool in PHP. PHP – Installation You can start learning the basics of programming in PHP with the help of any of the online PHP compilers freely available on the Internet. This will help in getting acquainted with the features of PHP without installing it on your computer. Later on, install a full-fledged PHP environment on your local machine. One such online PHP compiler is provided by Tutorialpoint’s “Coding Ground for Developers”. Visit https://www.tutorialspoint.com/codingground.htm, enter PHP script and execute it. However, to be able to learn the advanced features of PHP, particularly related to the web concepts such as server variables, using backend databases, etc., you need to install the PHP environment on your local machine. In order to develop and run PHP Web pages, you neeed to install three vital components on your computer system. Web Server − PHP will work with virtually all Web Server software, including Microsoft”s Internet Information Server (IIS), NGNIX, or Lighttpd etc. The most often used web server software is the freely available Apache Server. Download Apache for free here − https://httpd.apache.org/download.cgi Database − PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here − https://www.mysql.com/downloads/ PHP Parser − In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to
PHP – AJAX Introduction
PHP – AJAX Introduction ”; Previous Next 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 − Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications. XML − It is used to exchange data between web server and client. The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server. HTML and CSS − It is used to provide markup and style to the webpage text. DOM − It is used to interact with and alter the webpage layout and content dynamically. To use AJAX with PHP, you will need to use the XMLHttpRequest object in JavaScript to send requests to the PHP server. The PHP server will then process the request and return a response, typically in the form of JSON or XML. The JavaScript code can then parse the response and update the web page accordingly. The XMLHttpRequest object in JavaScript is a browser-based API that allows developers to make HTTP requests to a server without reloading the page. This is the foundation of AJAX programming, which allows for dynamic and interactive web applications. The XMLHttpRequest object can be used to − Retrieve data from a server, such as JSON, XML, or HTML. Send data to a server, such as form data or file uploads. Update a web page without reloading it. Create chat applications and other interactive features. To use the XMLHttpRequest object, you first need to create a new instance of it. Then, you can use the open() method to specify the HTTP method and request URL. Next, you can set any request headers, if needed. Finally, you can send the request using the send() method. Example Here is a simple JavaScript code of how to use the XMLHttpRequest object to retrieve data from a server − // Create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // Set the HTTP method and request URL xhr.open(“GET”, “test.php”); // Send the request xhr.send(); // Listen for the onload event to be fired xhr.onload = function() { // Check the status code to ensure the request was successful if (xhr.status === 200) { // Get the response data. var users = JSON.parse(xhr.responseText); // Do something with the user data. } else { // Handle the error } }; The PHP script on the server retrieves the data from AJAX request and sends back the response. // Get the request data. $name = $_GET[“name”]; // Create a response object. $response = new stdClass(); $response->message = “Hello, $name!”; // Send the response back to the client. header(“Content-Type: application/json”); echo json_encode($response); Print Page Previous Next Advertisements ”;
PHP – CSRF
PHP â CSRF ”; Previous Next The acronym “CSRF” stands for Cross-Site Request Forgery. CSRF is an Internet exploit that involves a trusted website user issuing unauthorized commands. Providing adequate protection to a PHP web application against this attack can be achieved by taking the measures explained in this chapter. By default, the browser uses the “GET” request method to send data. This is commonly used as the exploit point in a CSRF. To inject commands into a specific website, the attacker employs HTML tags like “IMG.” For example, the url endpoint of a web application such as “/delete.php?empcode=1234” deletes account as passed from empcode parameter of a GET request. Now, if an authenticated user come across the following script in any other application. <img src=”http://example.com/delete.php?empcode=1234″ width=”0″ height=”0″ border=”0″> Inadvertently causes the data related to empcode=1234 to be deleted. A common workaround for this problem is the use of CSRF tokens. A CSRF token is a string of random characters embedded into requests so that a web application can trust that a request has been received from an expected source as per the normal workflow. Steps to Implement CSRF The steps to implement CSRF token protection in PHP are as follows − Begin the script by starting a new session. Generate a token of random characters. You can use any of the several built-in function that PHP provides for generation of random string. Let use md5() function to obtain the hash value of uniqueid() function that generates a unique randome string. Inside the HTML form to be provided for the user to submit the data, include a hidden file with its value as the random token generated in the above step. The token can is then validated by the server against the user session after form submission to eliminate malicious requests. You can also add another session variable whose value is the current time, and send an expiry time for the validation purpose. Example Here is the PHP code that implements CSRF token verification mechanism. The following script generates a token and embeds in a HTML form. <?php session_start(); if(!isset($_SESSION[“csrf_token”])) { // No token present, generate a new one $token = md5(uniqid(rand(), true)); $_SESSION[“csrf_token”] = $token; } else { // Reuse the token $token = $_SESSION[“csrf_token”]; } ?> <html> <body> <form method=”get” action=”test.php”> <input type=”text” name=”empcode” placeholder=”empcode” /> <input type=”hidden” name=”csrf_token” value=”<?php echo $token;?>” /> <input type=”submit” /> </form> </body> </html> The form is submitted to “test.php” script as below − <?php session_start(); echo “hello”; if ($_GET[“csrf_token”] == $_SESSION[“csrf_token”]) { // Reset token echo $_GET[“csrf_token”] . “<br>”; echo $_SESSION[“csrf_token”] . “<br>”; echo “<h3>CSRF token validation successful. Proceed to further action</h3>”; } else { echo “<h3>CSRF token validation failed</h3>”; } ?> It will produce the following output − To simulate the failure of CSRF validation, open the inspect tool of the browser, edit the value in the hidden field manually and submit the form to see that the tokens donât match leading to the validation failure. Print Page Previous Next Advertisements ”;