We need to create an HTML form that allows you to choose the file to be uploaded. Note: please make sure you have form method type is post and enctype=”mutipart/form-data” to to handle file uploading process successfully. HTML Code <form enctype=”multipart/form-data” action=”process.php” method=”POST”> Choose File : <input name=”myfile” type=”file” /> <input type=”submit” value=”Upload” /> </form> Now create a PHP file process.php for handling file information <?php // get the uploaded file name $filename= $_FILES[‘myfile’][‘name’]; // get the file type $filetype= $_FILES[‘myfile’][‘type’]; // get the file size (in bytes) $filesize= $_FILES[‘myfile’][‘size’]; // You may put your validations here i.e restrict file size if($filesize>=1000000) { echo “ File is too Large, Maximum file size should be 1 MB”; exit; } // Validation to check if uploaded file is an Image if($filetype !=”image/jpeg” && $filetype !=”image/png” && $filetype !=”image/gif” && $filetype !=”image/JPEG” $filetype !=”image/PNG”) { echo “ Only Images allowed , Kindly upload valid Image.”; exit; } else { // create a folder – upload (in the same location where you have this PHP file) to move uploaded image from your local computer to server $target = “upload/”; $target = $target . basename( $_FILES[‘myfile’][‘name’]) ; move_uploaded_file($_FILES[‘myfile’][‘tmp_name’], $target); echo ” Image Uploaded Successfully”; } ?> You will be saving your uploaded images to a folder on the web server, which means you need a directory that is writable by the web server. To make the folder writable by the web server, you can use your FTP client for the same. To write the uploaded image to the target folder, you use the function move_uploaded_file. This PHP function will retrieve the image and move it to the designated location.
Sending email – Mail Function in PHP
Almost in every web application sending automated email by system is the common requirement. So, it’s very common and important part that must be known by developer. The simple example, when a visitor to your website fills out a enquiry form. mail function return a boolen value, return true if email sent successfully, false otherwise Syntax: mail ($to , $subject , $message, $additional_headers); $to: This is the first parameter of mail function hold the email address of receiver, the address to which email has to be sent. $subject: Every email should have subject. This parameter cannot contain any newline characters. $message: This is the actual body or content of email to send. Please note that every line should be break by \n and every line should not exceed the limit of 70 characters. $addintional_header: This contain additional header values like From, CC or Bcc etc. This is the optional parameter in mail function. Example <?php $to = “info@websjyoti.com”; $subject = “Welcome to Webs Jyoti”; $txt = “Hi, You received a new enquiry from user. this is an automated mail”; $headers = “From: sales@websjyoti.com” . “\r\n” ; mail($to,$subject,$txt,$headers); echo “Mail sent successfully”; ?>
Managing Sessions & Cookies
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.