Skip to main content

PHP Advanced

PHP Date and Time The PHP date() function is used to format a date and/or a time. The PHP Date() Function The PHP date() function formats a timestamp to a more readable date and time. Syntax date(format,timestamp) Parameter Description format Required. Specifies the format of the timestamp timestamp Optional. Specifies a timestamp. Default is the current date and time A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. Get a Date The required format parameter of the date() function specifies how to format the date (or time). Here are some characters that are commonly used for dates: d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits) l (lowercase 'L') - Represents the day of the week Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional formatting. The example below formats today's date in three different ways: Example "; echo "Today is " . date("Y.m.d") . "
"; echo "Today is " . date("Y-m-d") . "
"; echo "Today is " . date("l"); ?> PHP Tip - Automatic Copyright Year Use the date() function to automatically update the copyright year on your website: Example © 2010- Get a Time Here are some characters that are commonly used for times: H - 24-hour format of an hour (00 to 23) h - 12-hour format of an hour with leading zeros (01 to 12) i - Minutes with leading zeros (00 to 59) s - Seconds with leading zeros (00 to 59) a - Lowercase Ante meridiem and Post meridiem (am or pm) The example below outputs the current time in the specified format: Example Note that the PHP date() function will return the current date/time of the server! Get Your Time Zone If the time you got back from the code is not correct, it's probably because your server is in another country or set up for a different timezone. So, if you need the time to be correct according to a specific location, you can set the timezone you want to use. The example below sets the timezone to "America/New_York", then outputs the current time in the specified format: Example Create a Date With mktime() The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above). The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Syntax mktime(hour, minute, second, month, day, year) The example below creates a date and time with the date() function from a number of parameters in the mktime() function: Example Create a Date From a String With strtotime() The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Syntax strtotime(time, now) The example below creates a date and time from the strtotime() function: Example PHP is quite clever about converting a string to a date, so you can put in various values: Example "; $d=strtotime("next Saturday"); echo date("Y-m-d h:i:sa", $d) . "
"; $d=strtotime("+3 Months"); echo date("Y-m-d h:i:sa", $d) . "
"; ?> However, strtotime() is not perfect, so remember to check the strings you put in there. More Date Examples The example below outputs the dates for the next six Saturdays: Example "; $startdate = strtotime("+1 week", $startdate); } ?> The example below outputs the number of days until 4th of July: Example PHP Include Files The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website. PHP include and require Statements It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement. The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will continue So, if you want the execution to go on and show users the output, even if the include file is missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use the require statement to include a key file to the flow of execution. This will help avoid compromising your application's security and integrity, just in-case one key file is accidentally missing. Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file. Syntax include 'filename'; or require 'filename'; PHP include Examples Example 1 Assume we have a standard footer file called "footer.php", that looks like this: Copyright © 1999-" . date("Y") . " W3Schools.com

"; ?> To include the footer file in a page, use the include statement: Example

Welcome to my home page!

Some text.

Some more text.

Example 2 Assume we have a standard menu file called "menu.php": Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial'; ?> All pages in the Web site should use this menu file. Here is how it can be done (we are using a
element so that the menu easily can be styled with CSS later): Example

Welcome to my home page!

Some text.

Some more text.

Example 3 Assume we have a file called "vars.php", with some variables defined: Then, if we include the "vars.php" file, the variables can be used in the calling file: Example

Welcome to my home page!

PHP include vs. require The require statement is also used to include a file into the PHP code. However, there is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute: Example

Welcome to my home page!

If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error: Example

Welcome to my home page!

Use require when the file is required by the application. Use include when the file is not required and application should continue when file is not found. PHP File Handling File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP Manipulating Files PHP has several functions for creating, reading, uploading, and editing files. Be careful when manipulating files! When you are manipulating files you must be very careful. You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, and deleting the content of a file by accident. PHP readfile() Function The readfile() function reads a file and writes it to the output buffer. Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this: AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of bytes read on success): Example PHP File Open/Read/Close In this chapter we will teach you how to open, read, and close a file on the server. PHP Open File - fopen() A better method to open files is with the fopen() function. This function gives you more options than the readfile() function. We will use the text file, "webdictionary.txt", during the lessons: AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file: Example Tip: The fread() and the fclose() functions will be explained below. The file may be opened in one of the following modes: Modes Description r Open a file for read only. File pointer starts at the beginning of the file w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x Creates a new file for write only. Returns FALSE and an error if file already exists r+ Open a file for read/write. File pointer starts at the beginning of the file w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. The following PHP code reads the "webdictionary.txt" file to the end: fread($myfile,filesize("webdictionary.txt")); PHP Close File - fclose() The fclose() function is used to close an open file. It's a good programming practice to close all files after you have finished with them. You don't want an open file running around on your server taking up resources! The fclose() requires the name of the file (or a variable that holds the filename) we want to close: PHP Read Single Line - fgets() The fgets() function is used to read a single line from a file. The example below outputs the first line of the "webdictionary.txt" file: Example Note: After a call to the fgets() function, the file pointer has moved to the next line. PHP Check End-Of-File - feof() The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached: Example "; } fclose($myfile); ?> PHP Read Single Character - fgetc() The fgetc() function is used to read a single character from a file. The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached: Example Note: After a call to the fgetc() function, the file pointer moves to the next character. PHP File Create/Write In this chapter we will teach you how to create and write to a file on the server. PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a). The example below creates a new file called "testfile.txt". The file will be created in the same directory where the PHP code resides: Example $myfile = fopen("testfile.txt", "w") PHP File Permissions If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive. PHP Write to File - fwrite() The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written. The example below writes a couple of names into a new file called "newfile.txt": Example Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first contained "John Doe" and second contained "Jane Doe". After we finished writing, we closed the file using the fclose() function. If we open the "newfile.txt" file it would look like this: John Doe Jane Doe PHP Overwriting Now that "newfile.txt" contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file. In the example below we open our existing file "newfile.txt", and write some new data into it: Example If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just wrote is present: Mickey Mouse Minnie Mouse PHP File Upload With PHP, it is easy to upload files to the server. However, with ease comes danger, so always be careful when allowing file uploads! Configure The "php.ini" File First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On: file_uploads = On Create The HTML Form Next, create an HTML form that allow users to choose the image file they want to upload:
Select image to upload:
Some rules to follow for the HTML form above: Make sure that the form uses method="post" The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice: The type="file" attribute of the tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next. Create The Upload File PHP Script The "upload.php" file contains the code for uploading a file: PHP script explained: $target_dir = "uploads/" - specifies the directory where the file is going to be placed $target_file specifies the path of the file to be uploaded $uploadOk=1 is not used yet (will be used later) $imageFileType holds the file extension of the file (in lower case) Next, check if the image file is an actual image or a fake image Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there. Check if File Already Exists Now we can add some restrictions. First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0: // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } Limit File Size The file input field in our HTML form above is named "fileToUpload". Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0: // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } Limit File Type The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0: // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } Complete Upload File PHP Script The complete "upload.php" file now looks like this: 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> PHP Cookies What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. Create Cookies With PHP A cookie is created with the setcookie() function. Syntax setcookie(name, value, expire, path, domain, secure, httponly); Only the name parameter is required. All other parameters are optional. PHP Create/Retrieve a Cookie The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set: Example "; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> Note: The setcookie() function must appear BEFORE the tag. Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). Modify a Cookie Value To modify a cookie, just set (again) the cookie using the setcookie() function: Example "; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> Delete a Cookie To delete a cookie, use the setcookie() function with an expiration date in the past: Example Check if Cookies are Enabled The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable: Example 0) { echo "Cookies are enabled."; } else { echo "Cookies are disabled."; } ?> PHP Sessions A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer. What is a PHP Session? When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application. Tip: If you need a permanent storage, you may want to store the data in a database. Start a PHP Session A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION. Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables: Example Note: The session_start() function must be the very first thing in your document. Before any HTML tags. Get PHP Session Variable Values Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php"). Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()). Also notice that all session variable values are stored in the global $_SESSION variable: Example "; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> Another way to show all the session variable values for a user session is to run the following code: Example How does it work? How does it know it's me? Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session. Modify a PHP Session Variable To change a session variable, just overwrite it: Example Destroy a PHP Session To remove all global session variables and destroy the session, use session_unset() and session_destroy(): Example PHP Filters Validating data = Determine if the data is in proper form. Sanitizing data = Remove any illegal character from the data. The PHP Filter Extension PHP filters are used to validate and sanitize external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker. The filter_list() function can be used to list what the PHP filter extension offers: Example $filter) { echo ''; } ?>
Filter Name Filter ID
' . $filter . '' . filter_id($filter) . '
Why Use Filters? Many web applications receive external input. External input/data can be: User input from a form Cookies Web services data Server variables Database query results You should always validate external data! Invalid submitted data can lead to security problems and break your webpage! By using PHP filters you can be sure your application gets the correct input! PHP filter_var() Function The filter_var() function both validate and sanitize data. The filter_var() function filters a single variable with a specified filter. It takes two pieces of data: The variable you want to check The type of check to use Sanitize a String The following example uses the filter_var() function to remove all HTML tags from a string: Example Hello World!"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr; ?> Validate an Integer The following example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid": Example Tip: filter_var() and Problem With 0 In the example above, if $int was set to 0, the function above will return "Integer is not valid". To solve this problem, use the code below: Example Validate an IP Address The following example uses the filter_var() function to check if the variable $ip is a valid IP address: Example Sanitize and Validate an Email Address The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address: Example Sanitize and Validate a URL The following example uses the filter_var() function to first remove all illegal characters from a URL, then check if $url is a valid URL: Example PHP Filters Advanced Validate an Integer Within a Range The following example uses the filter_var() function to check if a variable is both of type INT, and between 1 and 200: Example array("min_range"=>$min, "max_range"=>$max))) === false) { echo("Variable value is not within the legal range"); } else { echo("Variable value is within the legal range"); } ?> Validate IPv6 Address The following example uses the filter_var() function to check if the variable $ip is a valid IPv6 address: Example Validate URL - Must Contain QueryString The following example uses the filter_var() function to check if the variable $url is a URL with a querystring: Example Remove Characters With ASCII Value > 127 The following example uses the filter_var() function to sanitize a string. It will both remove all HTML tags, and all characters with ASCII value > 127, from the string: Example Hello WorldÆØÅ!"; $newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); echo $newstr; ?> PHP Callback Functions Callback Functions A callback function (often referred to as just "callback") is a function which is passed as an argument into another function. Any existing function can be used as a callback function. To use a function as a callback function, pass a string containing the name of the function as the argument of another function: Example Pass a callback to PHP's array_map() function to calculate the length of every string in an array: Starting with version 7, PHP can pass anonymous functions as callback functions: Example Use an anonymous function as a callback for PHP's array_map() function: Callbacks in User Defined Functions User-defined functions and methods can also take callback functions as arguments. To use callback functions inside a user-defined function or method, call it by adding parentheses to the variable and pass arguments as with normal functions: Example Run a callback from a user-defined function: PHP and JSON What is JSON? JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language. PHP and JSON PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode() PHP - json_encode() The json_encode() function is used to encode a value to JSON format. Example This example shows how to encode an associative array into a JSON object: 35, "Ben"=>37, "Joe"=>43); echo json_encode($age); ?> Example This example shows how to encode an indexed array into a JSON array: PHP - json_decode() The json_decode() function is used to decode a JSON object into a PHP object or an associative array. Example This example decodes JSON data into a PHP object: The json_decode() function returns an object by default. The json_decode() function has a second parameter, and when set to true, JSON objects are decoded into associative arrays. Example This example decodes JSON data into a PHP associative array: PHP - Accessing the Decoded Values Here are two examples of how to access the decoded values from an object and from an associative array: Example This example shows how to access the values from a PHP object: Peter; echo $obj->Ben; echo $obj->Joe; ?> Example This example shows how to access the values from a PHP associative array: PHP - Looping Through the Values You can also loop through the values with a foreach() loop: Example This example shows how to loop through the values of a PHP object: $value) { echo $key . " => " . $value . "
"; } ?> Example This example shows how to loop through the values of a PHP associative array: $value) { echo $key . " => " . $value . "
"; } ?> PHP Exceptions What is an Exception? An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use. Throwing an Exception The throw statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed. If an exception is not caught, a fatal error will occur with an "Uncaught Exception" message. Lets try to throw an exception without catching it: Example The result will look something like this: Fatal error: Uncaught Exception: Division by zero in C:\webfolder\test.php:4 Stack trace: #0 C:\webfolder\test.php(9): divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4 The try...catch Statement To avoid the error from the example above, we can use the try...catch statement to catch exceptions and continue the process. Syntax try { code that can throw exceptions } catch(Exception $e) { code that runs when an exception is caught } Example Show a message when an exception is thrown: The catch block indicates what type of exception should be caught and the name of the variable which can be used to access the exception. In the example above, the type of exception is Exception and the variable name is $e. The try...catch...finally Statement The try...catch...finally statement can be used to catch exceptions. Code in the finally block will always run regardless of whether an exception was caught. If finally is present, the catch block is optional. Syntax try { code that can throw exceptions } catch(Exception $e) { code that runs when an exception is caught } finally { code that always runs regardless of whether an exception was caught } Example Show a message when an exception is thrown and then indicate that the process has ended: Example Output a string even if an exception was not caught: The Exception Object The Exception Object contains information about the error or unexpected behaviour that the function encountered. Syntax new Exception(message, code, previous) Parameter Values Parameter Description message Optional. A string describing why the exception was thrown code Optional. An integer that can be used used to easily distinguish this exception from others of the same type previous Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter Methods When catching an exception, the following table shows some of the methods that can be used to get information about the exception: Method Description getMessage() Returns a string describing why the exception was thrown getPrevious() If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null getCode() Returns the exception code getFile() Returns the full path of the file in which the exception was thrown getLine() Returns the line number of the line of code which threw the exception Example Output information about an exception that was thrown: getCode(); $message = $ex->getMessage(); $file = $ex->getFile(); $line = $ex->getLine(); echo "Exception thrown in $file on line $line: [Code $code] $message"; } ?>

Comments

Popular posts from this blog

MySQL Databases PDO

PHP MySQL Use The ORDER BY Clause Select and Order Data From a MySQL Database The ORDER BY clause is used to sort the result-set in ascending or descending order. The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC To learn more about SQL, please visit our SQL tutorial. Select and Order Data With MySQLi The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"].

PHP OOP

PHP - What is OOP? From PHP5, you can also write PHP code in an object-oriented style. Object-Oriented programming is faster and easier to execute. PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions. Object-oriented programming has several advantages over procedural programming: OOP is faster and easier to execute OOP provides a clear structure for the programs OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug OOP makes it possible to create full reusable applications with less code and shorter development time Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the applicatio

PHP - AJAX

PHP - AJAX Introduction AJAX is about updating parts of a web page, without reloading the whole page. What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX AJAX is Based on Internet Standards AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) AJAX applications are browse