The basic task of both cookies and sessions is to store visitor data so that it can be accessed by every page on a website. Cookies: Cookies are small text files that are stored in the visitor’s browser for a specific time or for a long -lifespan. Cookies can be edited by the visitor. in short Cookies are client-side files that contain user information. Sessions: Sessions are small files that are stored on the website’s server. Sessions have a limited lifespan, they expire when the browser is closed or logged out from the session. Sessions cannot be edited by the visitor or user. Session Max life time is 1440 Seconds(24 Minutes) as defined in php.ini file however you may change it accordingly In short, cookies serve on the visitor’s computer and sessions serve on server. By giving each visitor a cookie with a unique ID, I can use that cookie to recognize each visitor when they return. I can then use sessions to handle the page-to-page data exchange that actually provides each visitor with their customized settings and information, which are provided by each visitor and stored in a database until they are reference by the unique ID stored in the cookie.
Require () and Include () function in PHP
The Include() and require() statements are used to insert codes written in other files, in the flow of execution. The main of using include and require functions to integrate one page code or content into another page. You can maintain usually some repeated functionality in the form of PHP file and finally you can call it wherever you want. See, the following example demonstrates how to integrate a menu content in other pages of PHP. There is a page in menu.php and it can be included in some other pages of the website. Menu.php <a href=”index.php”>Home</a> <a href=”services.php”>Services</a> <a href=”about.php”>About Us</a> <a href=”contact.php”>Contact Us</a> The following page index.php uses above menu.php content. See the below code how it follows <head> <title>My Web page</title> </head> <body> <?php include “menu.php “; ?> </body> Difference between Include and require: The main difference between include and require statements in PHP is that if any error occurred include will raise an error message and then will continue the rest of the code placed in the page where as require will raise a fetal error and terminates execution. Function require () throws an error (E_COMPILE_ERROR) and stop the script. Function include () throws a warning (E_WARNING) but the script will continue. require_once() function require_once is useful if the result of the code is necessary but subsequent inclusions would throw an error. That goes for scripts with functions for instance. If such a script would be included more than once an error would be thrown since functions cannot be redeclared. include_once() Function include_once is useful in the case of including remote files and not wanting them to be included several times due to an HTTP overhead. This is also usefull in payment gateway and process on e-commerce websites. Examples <head> <title>My Web page</title> </head> <body> <div class=”header”> <?php Include_once “menu.php “; ?> </div> <div class=”footer”> <?php Include_once “menu.php “; ?> </div> </body> In this example you will see warning when you attempt to recall file “menu.php”
Introduction to Ajax
Ajax (Asynchronous Java script And XML) Introduction In Jesse Garrett’s original article that coined the term, it was AJAX. The “X” in AJAX really stands for XML HTTP Request though, and not XML. Jesse later conceded that Ajax should be a word and not an acronym and updated his article to reflect his change in heart. So “Ajax” is the correct casing. As its name implies, Ajax relies primarily on two technologies to work: JavaScript and the XML HTTP Request. Standardization of the browser DOM (Document Object Model) and DHTML also play an important part in Ajax’s success, but for the purposes of our discussion we won’t examine these technologies in depth. How Ajax Works At the heart of Ajax is the ability to communicate with a Web server asynchronously without taking away the user’s ability to interact with the page. The XML HTTP Request is what makes this possible. Ajax makes it possible to update a page without a refresh. By Ajax, we can refresh a particular DOM object without refreshing the full page. Let’s see now what actually happens when a user submits a request: Web browser requests for the content of just the part of the page that it needs. Web server analyzes the received request and builds up an XML message which is then sent back to the Web browser. After the Web browser receives the XML message, it parses the message in order to update the content of that part of the page. The XML HTTP Request object is part of a technology called Ajax (Asynchronous JavaScript and XML). Using Ajax, data could then be passed between the browser and the server, using the XML HTTP Request API, without having to reload the web page. With the widespread adoption of the XML HTTP Request object it quickly became possible to build web applications like Google Maps, and Gmail that used XML HTTP Request to get new map tiles, or new email without having to reload the entire page. Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it’s imperative that a callback be used to handle the response. Steps of AJAX Operation A client event occurs. An XML HTTP Request object is created. The XML HTTP Request object is configured. The XML HTTP Request object makes an asynchronous request to the Webserver. The Webserver returns the result containing XML document. The XML HTTP Request object calls the callback() function and processes the result. The HTML DOM is updated.
Data types in Mysql / Mariadb
Numeric Data Types: INT (Integer): Int data type represents an integer of normal size. So simply it can used to store numeric value. There are also BIGINT, MEDIUMINT, SMALLINT and TINYINT which represent different range of integer values. DECIMAL: Decimal data type represents numbers with specific floating values. Maximum permitted value is 65 and maximum decimals are 30. There are also FLOAT and DOUBLE to store numeric values with floating point. BOOLEAN: This data type associates a value 0 with ―”false”, and a value 1 with true. Date and Time Data Types: DATE: The DATE data type represents a date in “YYYY-MM-DD” format. TIME: The TIME data type represents a time in “HH:MM:SS” format. DATETIME: The DATETIME data type represents date and time in “YYYY-MM-DD HH:MM:SS” format. TIMESTAMP: This data type represents a timestamp of the “YYYY-MM-DD HH:MM:SS” format. It mainly used to insert current date and time of record insertion / updation and deletion process. String Data Types: CHAR: This data type represents a fixed-length string. default value is 1. VARCHAR: This data type represents a variable-length string of 0 to 65535. TEXT: This data type represents a text column with a maximum length of 65,535 characters. Some more Text data types are MEDIUMTEXT, LONGTEXT and TINYTEXT. ENUM: The ENUM data type represents a string object and allows only a single value from a given list. SET: The SET data type represents a string object having zero or more values from a given list.
The do-while loop
Difference Between while and do…while Loop: With a while loop, the condition to be evaluated is tested at the beginning of each loop statement, so if the conditional expression evaluates to false, the loop will never be executed. With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop statement. Example: <?php $i = 1; do { $i++; echo $i . “<br>”; } while($i <= 3); ?> Output: 2 3 4
The While Loop
A While loop is used when we have to repeat a set of statements as long as the condition is false. It could be the best where number of repetition is not known earlier or in advance. It can be explain in plain English as “Keep doing something until a condition is true”. Syntax: while (condition) { // Set of statements goes here; } Example <?php $ct=5; while($ct<=50) { echo $ct . “<br>”; $ct = $ct+5; } ?> Output: 5 10 15 20 25 30 35 40 45 50 The do…while loop example: <?php $i = 1; do { $i++; echo $i . “<br>”; } while($i <= 3); ?> Output: 2 3 4 Difference Between while and do…while Loop: With a while loop, the condition to be evaluated is tested at the beginning of each loop statement, so if the conditional expression evaluates to false, the loop will never be executed. With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop statement.
PHP -Building Blocks
If –else statements: if…else statement – executes set of codes if a condition is true and another code if the condition is false Within a statement, if a certain condition is true, then something happens. Otherwise, something else happens. We can continue adding else statements as many times as we need. So, within PHP statement, we first define the variable and then set up the conditional statements like this: Syntax: if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example 1: <?php $avg = 50 if ($avg>60) { echo “You have a good score”; } else { echo “Score is less than average”; } ?> Example 2: <?php $status = 1; if ($status== 1) { print (“<img src =images/right.jpg>”); } else { print (“<img src =images/cross.jpg>”); } ?> The variable called $status has been assigned a value of 1.The first line of if statement tests to see what is inside of the variable called $status. It‘s testing to see whether this variable has a value of 1.
The For Loop
PHP for loop can be used to traverse set of code for the specified number of times. For example if you want to repeat something ten or twenty times. It should be used if number of iteration is known otherwise I recommend you to use while loop. Syntax: for (Initialization; Condition; Progressive) { //set of statements to be executed; } Parameters: Initialization: Initialize the loop counter value Condition: Check for condition. If it evaluates to TRUE, the loop continues. If FALSE then the loop ends. Progressive: Increase / Decrease the loop counter value Example: for($var=1; $var<=20; $var=$var+1) { echo $var .” “; } Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Example: to display 1st 20 natural numbers in drop-down list <?php echo “<select>”; for($i=1; $i<=20; $i++) { echo ―”<option>”.$i. “</option>”; } echo “</select>”; ?> Please note inside loop area we are using variable $i to display values in drop-down list as we use variable that changes slightly each time.
PHP Superglobals
We already learned about variables, but there are some Readymade or predefined keywords in PHP that can be used without you having to create them first. Predefined or Superglobals variables are used to provide information from and about the web server, the web browser, and the user. There are several types of Super Global Variables:- $_GET – Is used to pass data through URL. Example: http://websjyoti.com?id=2 $_POST – Is used to pass data to server by hiding from URL. $_REQUEST – Is the combination of $_GET, $_POST, and $_COOKIE. $_SESSION – is used to maintain session and data from Local machine to Server. $_COOKIE – Is used to save/get user data on same machine in browser cookies. $_SERVER – Is an associative array which is used to know server information i.e. IP address, Host name, query string, file name etc. $_FILES – Is used to handle uploaded files operations in PHP. i.e. file size, type, name etc. Example – $_SERVER Superglobals: <?php echo”Current IP Address is: “.$_SERVER[‘REMOTE_ADDR’]; echo “You are at page: “.$_SERVER[‘PHP_SELF’]; ?> Functions: Functions in PHP behave similarly to functions in C. When we define the functions, we must specify what values the function can expect to receive. So let’s create a function. We need to give the function a name and tell it what variables to expect. We also need to define the function before we call it. <?php function sum($f1, $f2) { $f3=$f1+$f2 return $f3; } echo sum(10,8); ?> Output: 18 So First, we created our function. Notice how we defined two new variables, called $f1 and $f2. When we call the function, each variable is assigned a value based on the order in which it appears. Then we simply added the two numbers together and returned the result. “Return” here simply means to send the result back.
Arrays in PHP
An array is a data structure that stores similar type of values in a common variable. Arrays are also called homogeneous data type. For example if you want to store 50 numbers then instead of defining variables it is easy to define an array with size of 50. In PHP, the array() function is used to create an array Arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero. $x=array(“laxmi”,”hirdesh”,”rahim”,”ashu”,”amit”); // To count number of elements stored in array x echo count($x); // To populate value from any specific index or position //echo $x[1]; // output – Hirdesh // To print all elements in array x – using for-each loop echo ” <br>Names are :”; foreach ($x as $val) { echo $val . ” “; } echo “<br> using for loop <br>”; 50 for($i=0; $i<count($x); $i++) { echo $x[$i] . “<br>”; } Sorting Arrays: PHP provides many easy ways to sort array values in predefined orders- arsort: Sorts the array in descending value order and maintains the key/value relationship asort: Sorts the array in ascending value order and maintains the key/value relationship rsort: Sorts the array in descending value order sort: Sorts the array in ascending value order // Examples – Sorting of arrays $x=array(“laxmi”,”hirdesh”,”rahim”,”ashu”,”amit”, “mohit”); // rsort for DESC and simply sort for ASC sort($x); foreach ($x as $val) { echo $val . ” “; }