You are on page 1of 30

Web Programming using PHP and MYSQL

UNIT 1
1. Name any four typical web applications. Online polls, discussion forums, content management, migration from one platform to another, brightly colored Flash animations, live video feeds etc. 2. What are the two General Tasks expected in the web application? 1. Gather information and save it somewhere Web browser (Client) to DBMS (Server) 2. Retrieve it and show/ present it DBMS( Server) to Web browser(Client). 3. What do you mean by LAMP? LAMP is a development environment with the combination of Linux, Apache, MySQL and PHP. 4. Differentiate client side scripting from server side scripting. Client Side Scripting programs run in a client application i.e. browser. It can access very few resources and its storage capacity is also very low with lot of restrictions where as the Server Side Scripting runs on web server i.e. on an operating system with a lot of memory and storage capacity without any restrictions. 5. Compare the merits of Client Side scripting with the Server Side Scripting. Client side scripting is the most efficient way to do all interfaces related activities like image over or page transition effect within the browser. Server side scripting is the best way to approach server bound activities like accessing server resources such as databases, external files etc to save and retrieve those stuffs on a later period. 6. Tabulate and compare Client Side scripting and the Server Side Scripting.

Client Side Scripts


JavaScript/ HTML/VBscript Limited storage capabilities for user data Cookies resides inside the Clients machine

Server Side Scripts


PHP/ Perl/ ASP. NET/ JSP Unlimited storage User data resides in the server

Web Programming using PHP and MYSQL Temporary Storage Rely on Local machines capability Concern about Gathering/ Displaying Users data at the browser Localized to the User Interface Validates all the user inputs before forwarding them to the server. Permanent Storage Rely on servers capabilities Concern about Storing/ Updating User Data into DBMS Any errors in the data/format to the server prompts error message thus waste of time, waste of network resources

7. Define the term Database. Database is a collection of data organized and classified criteria. 8. What is DBMS? DBMS is a framework with a handsome collection of tools to store and retrieve data to and from a storage device. 9. Name the unique feature available in RDBMS. RDBMS is Relation Database Management System which is an advanced version to DBMS where data are grouped by means of relations. 10. Notify typical server side scripting applications. Build a search engine that responds to user queries, Record user input provided through web forms and save it for future reference, Create web sites that dynamically update themselves with new content, Manage a blog (or more than one), Process electronic payments and track customer orders, Build customized bar graphs, pie charts, and other statistical reports from raw numeric data, Carry out online surveys and polls, and create reports of the results. 11. What is the goal of PHP? The main goal of the PHP language is to allow web developers to write dynamically generated web pages quickly. PHP is the widely used general purpose scripting language that is used for web development which allows the web developers to embed it into HTML. The language is rapidly becoming the popular choice for data-driven web applications because of its wide support for different database systems. according to some

Web Programming using PHP and MYSQL 12. Briefly explain about the embedding PHP into HTML. Embedding is the technique widely used in the web development platform since Java scripting days. This is the technique which permits a web developer to mix of more than one scripting technology. <?php is the sequence helps the web developer to indicate the starting position of the php scripting sequences and ?> is the sequence to indicate the last statement of the php scripting. PHP code is embedded inside a regular HTML document, and is recognized and executed by the web server when the document is requested through a browser. The server will execute php code and return the output to the browser in the format required or specified by the developer. PHP code works independently of the users web browser. For example, <HTML><HEAD><TITLE>my sample</TITLE>/HEAD> <BODY> <?php echo <H1>. WELCOME TO ECONTENTS; ?> </BODY> </HTML> 13. What made PHP so popular among other web development tools in the market? PHP is the open-source server-side scripting language which uses a clear and simple syntax and is absolutely available at free of cost on the Internet, for a variety of platforms and architectures, including UNIX, Microsoft Windows, and Mac OS, as well as for most web servers. PHP is an interpreted language which enables the developer to perform incremental, iterative development and testing without going through a compiletest-debug cycle each time you change your code. This can speed the development cycle drastically. A variety of data types, a powerful object-oriented engine, an extensive library of built-in functions, and support for most current web technologies and protocols complete the picture. The close-knit relationship between PHP and MySQL, both open-source projects, makes possible some powerful synergies. 14. Describe the evolution of PHP. The first version of PHP, PHP/FI, was developed by Rasmus Lerdorf in 1995 to monitor online resumes.

Web Programming using PHP and MYSQL PHP/FI 1.0 was followed by PHP/FI 2.0 and, in turn, quickly supplanted in 1997 by PHP 3.0. PHP 3.0, developed by Andi Gutmans and Zeev Suraski was a complete rewrite of the original PHP/FI implementation and it included support for a wider range of databases, including MySQL and Oracle. PHP 3.0s extensible architecture encouraged independent developers to begin creating their own language extensions, which served to increase the languages popularity in the developer community. PHP 4.0, which was released in 2003, used a new engine to deliver better performance, greater reliability and scalability, support for web servers other than Apache, and a host of new language features, including built-in session management and better OOP support. PHP 5.0, offers a completely revamped object model that uses object handles for more consistent behavior when passing objects around, as well as abstract classes, destructors, multiple interfaces, and class type hints. PHP 5.0 also includes better exception handling, a more consistent XML toolkit, improved MySQL support, and a better memory manager. 15. Write about the features of PHP. Simplicity PHP uses a consistent and logical syntax since it comes with a clearly written manual; even novices find it easy to learn. PHP can even access C libraries and take advantage of program code written for this language, and the language is renowned for the tremendous flexibility it allows programmers in accomplishing specific tasks. Portability Portability With programming languages, with which a program can be made to work on different platforms. PHP is available for a wide variety of platforms, including UNIX, Microsoft Windows, Mac OS, and OS/2. Additionally, because PHP code is interpreted and not compiled, PHP scripts written on one platform usually work as is on any other platform for which an interpreter exists. Speed PHP scripts run faster than most other scripting languages like JSP, ASP.NET, and Perl. PHP 5.0 improves performance even further through the use of an optimized memory manager, and the use of object handles that reduce memory consumption and help applications run faster. Open Source

Web Programming using PHP and MYSQL PHP source code is freely available on the Web, and developers can install and use it without paying licensing fees or investing in expensive hardware or software. Using PHP can thus significantly reduce the development costs of a software application, without compromising on either reliability or performance. Extensible PHPs creators built an extensible architecture that enables developers to easily add support for new technologies to the language through modular extensions. Extensible through its add-on modules: dynamically create image, PDF, and SWF files; connect to IMAP and POP3 servers; interface with MySQL, Oracle, PostgreSQL, and SQLite databases; handle electronic payments; parse XML documents; and execute Perl, Java, and COM code through a PHP script. And as if all that wasnt enough, theres also an online repository of free PHP classes called PEAR, the PHP Extension and Application Repository, which provides a source of reusable, bug-free PHP components. XML and Database Support PHP 5.0 comes with an improved MySQL extension that enables you to take advantage of new features in the MySQL RDBMS (including subqueries, transactions, and referential integrity), and the language also supports DB2, PostgreSQL, Oracle, mSQL, MS-SQL, Informix, More free Sybase, and SQLite. Alternatively, if its XML youre after, PHP 5.0 offers a completely redesigned XML API built around the libxml2 toolkit; this API supports SAX, DOM, and XSLT, as well as the new SimpleXML and SOAP extensions. 16. Write about the features of MYSQL. Speed MySQL uses a fully multithreaded architecture; special optimizers for complex tasks like joins and indexing; a query cache, which improves performance without any special programming needed by the user; and the capability to use different storage engines on a per-table basis, so that users can mix and match different feature sets to squeeze the maximum performance out of the system. Reliability The MySQL RDBMS has been tested and certified for use in high-volume, mission-critical applications by some of the worlds largest organizations, including NASA, HP, and Yahoo! Security MySQL comes with a sophisticated access control and privilege system to prevent unauthorized users from accessing the system. This system, implemented as a five-tiered privilege hierarchy, enables MySQL administrators to protect access to sensitive data using a combination of user- and host-based authentication schemes. Users can be restricted to performing operations only on specified

Web Programming using PHP and MYSQL databases or fields, and MySQL even makes it possible to control which types of queries a user can run, at database, table, or field level. Scalability and portability MySQL can handle extremely large and complex databases without too much of a drop in performance. Tables of several gigabytes containing hundreds of thousands of records are not uncommon, and the MySQL web site itself claims to use databases containing 50 million records. MySQL is available for both UNIX and non-UNIX operating systems, including Linux, Solaris, FreeBSD, OS/2, MacOS, and Windows 95, 98, Me, 2000, XP, and NT. It runs on a range of architectures, including Intel x86, Alpha, SPARC, PowerPC, and IA64, and supports many different hardware configurations, from low-end 386s to high-end Pentium machines. Ease of use MySQL is very easy to use, administer, and optimize. A simple SQL commandline interface is the primary user interface to the server; users with a more visual bent can, instead, use MySQL Control Center or MySQL Administrator, two GUI clients developed by MySQL AB for MySQL usage and administration. Compliance with existing standards MySQL 4.0 supports most of the important features of the ANSI SQL-99 standard and also extends the ANSI standard with its own custom functions and data types designed to improve portability and provide users with enhanced functionality. Wide application support MySQL exposes APIs to many different programming languages, thereby making it possible to write database-driven applications in the language of the developers choice. MySQL are available in C, C++, Perl, Python, and Tcl, to offer developers maximum freedom in designing MySQL-backed applications. Easy licensing policy The MySQL RDBMS is licensed under the GPL, and users are free to download and modify the source code of the application to their needs, and to use it to power their applications free of cost. This licensing policy has only fuelled MySQLs popularity, creating an active and enthusiastic global community of MySQL developers and users. 17. Explain the LAMP development framework. LAMP (Linux, Apache, MySQL, and PHP) platform plays a specific and important role as explained below.Linux provides the base operating system (OS) and server environment. The Apache web server intercepts HTTP requests and either serves them directly or passes them on to the PHP interpreter for execution. The PHP interpreter parses and executes PHP code, and returns the results to the

Web Programming using PHP and MYSQL web server. The MySQL RDBMS serves as the data storage engine, accepting connections from the PHP layer and inserting, modifying, or retrieving data.

1. A user opens his web browser at home and types in the URL for his online Web mail client. After looking up the domain, Joes browser (the client) sends an HTTP request to the corresponding server IP address. 2. The Apache web server handling HTTP requests for the domain receives the request and notes that the URI ends with a .php suffix. Because the server is programmed to automatically redirect all such requests to the PHP layer, it simply invokes the PHP interpreter and passes it the contents of the named file. 3. The PHP interpreter parses the file, executing the code in the special PHP tags. If the code includes database queries, the PHP interpreter opens a client connection to the MySQL RDBMS and executes them. Once the script interpreter has completed executing the script, it returns the result to the browser, cleans up after itself, and goes back into hibernation. 4. The results returned by the interpreter are transmitted to the Users browser by the Apache server.

18. How a PHP variable name differs from any other programming languages? PHP uses $ sign before all the variables except for the constants. $a = 0; $a is an integer variable. $k=Loyola College; $k is a string variable.

Web Programming using PHP and MYSQL Define(MyName, JERALD); Define(MyAge, 40); MyName and MyAge are constant variables.

19. What is the use of form tag? Give an example. <form method="post" action="message.php"> Enter your message: <input type="text" name="msg" size="30"> <input type="submit" value="Send"> </form>

(or) <form method="get" action="message.php"> Enter your message: <input type="text" name="msg" size="30"> <input type="submit" value="Send"> </form> As shown above, form tags are useful to call a user defined PHP procedure and to collect and to transfer data from one form to another form. The message.php looks like: <?php // retrieve form data in a variable $input = $_POST['msg']; // print it echo "You said: <i>$input</i>"; ?> 20. What is $_POST / $_GET? How to use them in PHP? $_POST/ $_GET is a special PHP container variable/ global array used to access the value of the form variable. To get the value of the form variable, the name of form variable must be passed throgh the global array. For example, to access 'msg', it is expected to type $_POST['msg'] or $_GET['msg'] depends on the method invoked.

21. Name the simple data types supported by PHP. Integers 0,1,2,3 etc

Web Programming using PHP and MYSQL Float/ Double real numbers 0.1, 0.2, 0.3, etc String A, Loyola College etc Boolean True or False Array set of values {0,1,2,3}or {0.1,0.2,0.3}or {A, B, C} or {Henry, Santhosh, Karthick} etc Object stores instances of classes. 22. How to set, clear and get the type of a variable? To explicitly set a variable to a particular type, the settype() function is used as shown below. settype($a, 'int'); To clear the type of a variable, the unset() function is used as shown below. unset($a); To return the type of a variable, the gettype() funtion is used as shown below. gettype($a); 23. Name the functions that are used for detecting data type of variables. is_bool() Checks if a variable or value is Boolean is_string() Checks if a variable or value is a string is_numeric() Checks if a variable or value is a numeric string is_float() Checks if a variable or value is a floating point number is_int() Checks if a variable or value is an integer is_null() Checks if a variable or value is NULL is_array() Checks if a variable is an array is_object() Checks if a variable is an object 24. Describe about Operators. PHP comes with over 15 operators, including operators for assignment, arithmetic, string, comparison, and logical operations as shown below. Operator = + * / % Description Assignment Addition Subtraction Multiplication Division; returns quotient Division; returns modulus

Web Programming using PHP and MYSQL . == === !== <> aka != < <= > >= && || xor ! ++ -String concatenation Equal to Equal to and of the same type Not equal to or not of the same type Not equal to Less than Less than or equal to Greater than Greater than or equal to Logical AND Logical OR Logical XOR Logical NOT Addition by 1 Subtraction by 1

25. Demonstrate the use of string operator. The string concatenation operator, represented by a period (.), used to add two different strings together as shown below. <?php $username = 'jeraldinico'; $domain = 'gmail.com'; $email = $username echo $email; ?>

. '@' . $domain;

The above PHP script returns jeraldinico@gmail.com 26. What is operator precedence? The rule should be followed during evaluation of the operators in an expression instead of executing operators as it is. The following list illustrates the important PHP precedence rules. (Operators on the same line have the same level of precedence.) '!' '++' '--' '*' '/' '%' '+' '' '.' '<' '<=' '>' '>=' '==' '!=' '===' '!==' '&&' '||'

10

Web Programming using PHP and MYSQL '?' ':'

27. Give the syntax for simple if, if else, else if and switch statements. Syntax for simple if <?php if (conditional test) { do this; } ?>

Syntax for if else <?php if (conditional test) { do this; } else { do this; } ?>

Syntax for else if <?php if (conditional test #1) { do this; } elseif (conditional test #2) { do this; } ... elseif (conditional test #n) { do this; } else

11

Web Programming using PHP and MYSQL { do this; } ?> Syntax for switch statement <?php switch (condition variable) { case possible result #1: do this; case possible result #2: do this; ... case possible result #n: do this; case default; do this; } ?>

28. Give an example for each of the following i) for simple if, ii) if else, iii) else if and v) switch statements. <?php if ($mark >= 40) { echo 'Pass!'; } ?>

<?php if ($mark >= 40) { echo 'Pass!'; } else { echo 'Fail!'; } ?>

12

Web Programming using PHP and MYSQL <?php if ($country == 'IN') { $capital = 'Delhi'; } elseif ($country == 'UK') { $capital = 'London'; } elseif ($country == 'US') { $capital = 'Washington'; } elseif ($country == 'FR') { $capital = 'Paris'; } else { $capital = 'Unknown'; } ?>

<?php switch ($country) { case 'IN': $capital = 'Delhi'; case 'UK': $capital = 'London'; break; case 'US': $capital = 'Washington'; break; case 'FR': $capital = 'Paris'; break; default: $capital = 'Unknown'; break; } ?> 29. Give an example for the use of ternary operators. <?php $result = $mark > 39 ? 'Pass!' : 'Fail!';

13

Web Programming using PHP and MYSQL echo $result; ?> 30. What is nesting? Give an example. Keeping conditional statements inside each other to handle multiple conditions is known as nesting. For example, <?php if ($country == 'India') { if ($state == 'Tamilnadu') { if ($city == 'Chennai') { $home = true; } } } ?> 31. Give an example for merging forms with its result page. <html> <head></head> <body> <?php if (!$_POST['submit']) { ?> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Enter a number: <input name="number" size="2"> <input type="submit" name="submit" value="Go"> </form> <?php } else { $number = $_POST['number']; if ($number > 0) { echo 'You entered a positive number'; } elseif ($number < 0) { echo 'You entered a negative number'; }

14

Web Programming using PHP and MYSQL else { echo 'You entered 0'; } } ?> </body> </html>

32. When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. This method should not be used when sending passwords or other sensitive information! The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters. 33. When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. 34. What are the loop structures available in PHP? While loop Do loop For loop For each loop 35. Give the syntax for while loop and an example. <?php while (condition is true) { do this; } ?> While() loops continue to iterate for so long as the specified conditional expression remains true. For example, <?php $1=1; while ($i<=100) { echo $1;

15

Web Programming using PHP and MYSQL $i++ } ?> 36. Give the syntax for Do loop and an example. <?php do { do this; } while (condition is true); ?> Do-while() loops continue to iterate for so long as the specified conditional expression remains true. For example, <?php $i=0; do { echo $i; $i++; } while ($i<=100); ?> 37. Give the syntax for For loop and an example. <?php for (initialize counter; conditional test; update counter) { do this; } ?> PHPs for() loop uses a counter that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, a conditional statement is tested. If it evaluates to true, the loop will execute once more and the counter will be incremented by 1 (or more) positions. If it evaluates to false, the loop will be broken and the lines following it will be executed instead. For example, <?php for ($i=1;$i<=100 ;$i++) { echo $i; } ?>

16

Web Programming using PHP and MYSQL 38. Give the syntax for For each loop and an example. <?php for each ($variable as $key => $value) { do this; } ?> For example, to print the values in the associative array, the following code will be useful. <?php for each ($price as $key => $value) { echo $key. "-". $value; } ?> 39. Discuss about the Form Validation. The User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load. The server validation is good if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. In PHP, the predefined $_GET variable is used to collect values in a form with method="get". 40. What is the use of $_REQUEST Variable? The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. 41. How to construct a HTML table and its contents using PHP?

<html> <head></head> <body> <?php if (!$_POST['submit']) {

17

Web Programming using PHP and MYSQL ?> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> Enter number of rows <input name="rows" type="text" size="4"> and columns <input name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table"> </form> <?php } else { ?> <table border="1" cellspacing="5" cellpadding="0"> <?php // from form input $rows = $_POST['rows']; $columns = $_POST['columns']; // rows for ($r = 1; $r <= $rows; $r++) { echo "<tr>"; // columns for ($c = 1; $c <= $columns; $c++) { echo "<td>&nbsp;</td>\n"; } echo "</tr>\n"; } ?> </table> <?php } ?> </body> </html>

Unit II
42. What is an array? An array is a complex variable that stores multiple values in a single variable; An array variable can best be thought of as a container variable, which can contain one or more values. Here is an example: <?php 18

Web Programming using PHP and MYSQL $cars[0]="Ford"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; ?> (or) <?php $flavors = array('strawberry', 'grape', 'vanilla', 'caramel', 'chocolate'); ?> 43. What are the three kinds of arrays supported by PHP? 1. Numeric array - An array with a numeric index. 2. Associative array - An array where each ID key is associated with a value. 3. Multidimensional array - An array containing one or more arrays. 44. What is an associative array? How to define an associative array in PHP? PHP also enables the developer to replace indices with user-defined keys to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array. Keys may be made up of any string of characters, including control characters. Here is an example. <?php $fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape'); ?> 45. What are the functions used to add new values, remove a value from an array? The array_pop() function is used to remove an array element whereas array_push() function is used to add a new values into an array. 46. Illustrate the use of foreach statement in PHP. <html> <head></head> <body> <ul> <?php $shoppingList = array('Pen', 'Pencil','Rubber'); foreach ($shoppingList as $item) { echo "<li>$item";

19

Web Programming using PHP and MYSQL } ?> </ul> </body> </html> 47. How to capture all the selected form values in a single variable? Give an example. <html> <head></head> <body> <?php if (!$_POST['submit']) { ?> Select the departments to participate in the event from below: <br /> <form action="<?=$_SERVER['PHP_SELF']?>" method="POST"> <select name="options[]" multiple> <option value="Computer Science">Computer Science</option> <option value="Computer Application">Computer Application</option> <option value="Commerce">Commerce</option> <option value="Visual Communication">Visual Communication</option> <option value="Physics">Physics</option> <option value="Chemistry"> Chemistry</option> </select> <input type="submit" name="submit" value="Select"> </form> <?php } else { if (is_array($_POST['options'])) { echo 'Here is your selection: <br />'; foreach ($_POST['options'] as $o) { echo "<i>$o</i><br />"; } } else { echo 'Nothing selected'; }

20

Web Programming using PHP and MYSQL } ?> </body> </html> 48. How to list the keys and values in an associative array? The array_keys() and array_values() functions to get a list of all the keys and values within the array. For example, <?php $menu = array('breakfast' => 'Idly', 'lunch' => 'Indian meals', 'dinner' => 'Dosa'); $result1 = array_keys($menu); $result2 = array_values($menu); echo $result1 . " ". $result2; ?> 49. Define and list the functions used in array manipulations. Function is a set of program statements that perform a specific task,and that can be called, or executed, from anywhere in the program. array() - populate arrays with elements array_pop() - remove an element from the end array_push() - add an element to the end of an existing array array_shift() - pop an element off the top of the array array_unshift()- adding elements to the beginning of the array sizeof() - To return the number of elements in an array foreach() - To keep track of array positions list() - assigns array elements to variables. extract() - converting the key-value pairs into corresponding variable-value pairs. explode() - splits a string into smaller components and then returns those elements as an array. 50. Explain about User Defined Function and notify its merits. A User Defined Function is the function in which the developer groups a limited number of statements under a name and can be called inside the program wherever it is required. Fox example, <?php function fact( $n) { if ($n = 1) return (1);

21

Web Programming using PHP and MYSQL else return ($n * fact( $n-1)); } echo fact(3); ?> which snippets returns [3x2x1] 6. The merits of User Defined Functions are: 1. User-defined functions enable developers to extract commonly used pieces of code into separate packages, thereby reducing unnecessary code repetition and redundancies. These separations of code into independent subsections also make the code easier to understand and debug. 2. Because functions are defined once (but used many times), they are easy to maintain. A change to the function code need only be implemented in a single placethe function definitionwith no changes needed anywhere else. 3. Because functions force developers to think in abstract terms (define input and output values, set global and local scope, and turn specific tasks into generic components), they encourage better software design and help in creating extensible applications. 51. List super global variables in PHP. The $_SERVER, $_POST, $_GET, $_REQUEST, $GLOBALS, $_FILE, $_SESSION, and $_COOKIE arrays are known as Super Global Variables or Super Duper Variables. 52. How to import files into a PHP script? The include() and require() functions are helpful to import files into a PHP script. The include() function generates a warning if the file cannot be found, although script processing continues. However, the require() function forces a file to be included in the script and generates a fatal error that stops script processing if the file cannot be found. 53. Describe about file handling mechanism in PHP. PHP comes with a powerful and flexible file manipulation API, which enables developers to view and modify file attributes, read and list directory contents, alter file permissions, retrieve file contents into a variety of native data structures, and search for files based on specific patterns. Let us see how to read data from a file and how to write data into a file.

22

Web Programming using PHP and MYSQL

Reading Data from a File <?php $file = '/My Documents/projects.txt'; $fh = fopen($file, 'r') or die('Could not open file!'); $data = fread($fh, filesize($file)) or die('Could not read file!'); fclose($fh); echo $data; ?> Writing Data to a File <?php $file = '/My Documents/projects.txt'; $fh = fopen($file, 'w') or die('Could not open file!'); fwrite($fh, 'Hello, file!') or die('Could not write to file'); fclose($fh); ?> 54. List out functions that are useful for testing file attributess. Returns a Boolean indicating whether the file exists Returns a Boolean indicating whether the specified path is a directory is_file() Returns a Boolean indicating whether the specified file is a regular file is_link() Returns a Boolean indicating whether the specified file is a symbolic link is_executable() Returns a Boolean indicating whether the specified file is executable is_readable() Returns a Boolean indicating whether the specified file is readable is_writable() Returns a Boolean indicating whether the specified file is writable filesize() Gets file size, in bytes filemtime() Gets last modification time of file fileatime() Gets last access time of file fileowner() Gets file owner filegroup() Gets file group fileperms() Gets file permissions filetype() Gets file type 55. Notify the use of file_get_contents and file_put_contents. file_get_contents is function useful to copy the contents of a file directly to a variable whereas file_put_contents is the function to write contents into a file. 56. Write PHP script to Obtain Directory Listings. file_exists() is_dir()

23

Web Programming using PHP and MYSQL <?php $count = 0; $dir = "/bin"; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($filename = readdir($dh)) !== false) { if (($filename != ".") && ($filename != "..")) { $count++; echo $dir . "/" . $filename . "\n"; } } closedir($dh); } } echo "-- $count FILES FOUND --"; ?> 57. Describe about Sessions with suitable PHP coding. HTTP protocol treats each request for a web page as a unique and independent transaction, with no relationship whatsoever to the transactions that preceded it. As the stateless nature of the HTTP protocol makes it impossible to identify which transactions belong to which client or user. A common solution to the problem is to use sessions to store information about each client and track its activities. This session data is preserved for the duration of the visit, and is usually destroyed on its conclusion. The Client transactions are identified through unique numbers; these identifiers are used to re-create each clients prior session environment whenever required. The session identifier may be stored on the client in a cookie or it may be passed from page to page in the URL. Creating a Session and Registering Session Variables In PHP, the session_start() function is used to create a client session and generate a session ID. Once a session has been created, it becomes possible to register any number of session variables as shown beolw.

24

Web Programming using PHP and MYSQL

<?php session_start(); $_SESSION['username'] = 'jeraldinico'; $_SESSION['role'] = 'admin'; ?> On subsequent pages, calls to the session_start() function re-create the prior session environment by restoring the values of the $_SESSION associative array. This can be tested by attempting to access the values of the session variables registered in the previous attempt.

<?php session_start(); echo $_SESSION['username']; ?> Destroying a Session session_destroy() function is to erase session data as shown below. <?php session_start(); $_SESSION = array(); session_destroy(); ?> 58. What is cookie? The cookie is a feature which allows web sites to store client-specific information in a file on the client system, and retrieve this information on an as-needed basis. 59. What are ground rules about cookies? 1. Because cookies are used to record information about your activities on a particular site, they can only be read by the site that created them. 2. A single domain cannot set more than 20 cookies, and each cookie is limited to a maximum size of 4KB. 3. A cookie usually possesses five types of attributes which includes Name- Sets the name and value of the cookie, Expires - Sets the date and time at which the cookie expires, path- Sets the toplevel directory on the domain from which cookie data can be accessed, domain Sets the domain for which the cookie is valid,and secure - Sets a Boolean flag indicating that the cookie should be transmitted only over a secure HTTP connection. 4. Of all the five attributes, only the first is not optional.

25

Web Programming using PHP and MYSQL

60. How to set/ retrieve data to/from a cookie? Setting Cookies <?php $result = setcookie('username', 'admin', mktime()+86400, '/'); if (!$result) { echo "Unable to set cookie"; } ?> Or multiple cookies <?php setcookie('username', 'admin', mktime()+86400, '/'); setcookie('role', '2', mktime()+1800, '/secure/web/'); setcookie('country', 'IN', 0, '/'); ?> Retrieving Cookie Data <?php if ($_COOKIE['username']) { echo "Welcome back, " . $_COOKIE['username']; } else { echo "Is this your first time here? Take our guided tour!"; } ?> Deleting Cookies To delete a cookie, simply use setcookie() with its name to set the cookies expiry date to a value in the past. <?php setcookie('username', ''NULL, mktime()-10000, '/'); ?> 61. Write PHP code to get date and time. <?php $current = getdate(); $current_time = $current['hours'] . ':' . $current['minutes'] . ':' . $current['seconds'];

26

Web Programming using PHP and MYSQL $current_date = $current['mday'] . '.' . $current['mon'] . '.'. $current['year']; echo $current_time. $current_date; ?> 62. Illustrate the use of escapeshellarg() and escapeshellcmd() functions. <html> <head></head> <body> <?php if (!$_POST['submit']) { ?> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Enter path: <input type="text" name="path"> <input type="submit" name="submit" value="Go!"> </form> <?php } else { $path = escapeshellarg($_POST['path']); $output = `/bin/du -s $path`; $outputArray = explode("\t", $output); $size = $outputArray[0]; echo "$path occupies $size bytes"; } ?> </body> </html> 63. Write PHP code for Session-Based Shopping Cart. <?php session_start(); if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); } $catalogFile = "catalog.dat"; if (file_exists($catalogFile)) { $data = file($catalogFile); foreach ($data as $line) { $lineArray = explode(':', $line); $sku = trim($lineArray[0]);

27

Web Programming using PHP and MYSQL

$CATALOG[$sku]['desc'] = trim($lineArray[1]); $CATALOG[$sku]['price'] = trim($lineArray[2]); } } else { die("Could not find catalog file"); } if ($_POST['add']) { foreach ($_POST['a_qty'] as $k => $v) { if ($v > 0) { $_SESSION['cart'][$k] = $_SESSION['cart'][$k] + $v; } } } else if ($_POST['update']) { foreach ($_POST['u_qty'] as $k => $v) { if ($v != "" && $v >= 0) { $_SESSION['cart'][$k] = $v; } } } else if ($_POST['clear']) { $_SESSION = array(); session_destroy(); } ?> <html> <head></head> <body> <h2>Catalog</h2> Please add items from the list below to your shopping cart. <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> <table border="0" cellspacing="10">

28

Web Programming using PHP and MYSQL <?php foreach ($CATALOG as $k => $v) { echo "<tr><td colspan=2>"; echo "<b>" . $v['desc'] . "</b>"; echo "</td></tr>\n"; echo "<tr><td>"; echo "Price per unit: " . $CATALOG[$k]['price']; echo "</td><td>Quantity: "; echo "<input size=4 type=text name=\"a_qty[" . $k . "]\">"; echo "</td></tr>\n"; } ?> <tr> <td colspan="2"> <input type="submit" name="add" value="Add items to cart"> </td> </tr> </table> <hr /> <hr /> <h2>Shopping cart</h2> <table width="100%" border="0" cellspacing="10"> <?php $total = 0; if (is_array($_SESSION['cart'])) { foreach ($_SESSION['cart'] as $k => $v) { if ($v > 0) { $subtotal = $v * $CATALOG[$k]['price']; $total += $subtotal; echo "<tr><td>"; echo "<b>$v unit(s) of " . $CATALOG[$k]['desc'] . "</b>"; echo "</td><td>"; echo "New quantity: <input size=4 type=text name=\"u_qty[" . $k . "]\">"; echo "</td></tr>\n"; echo "<tr><td>"; echo "Price per unit: " . $CATALOG[$k]['price']; echo "</td><td>"; echo "Sub-total: " . sprintf("%0.2f", $subtotal); echo "</td></tr>\n"; 29

Web Programming using PHP and MYSQL } } } ?> <tr> <td><b>TOTAL</b></td> <td><b><?=sprintf("%0.2f", $total)?></b></td> </tr> <tr> <td><input type="submit" name="update" value="Update Cart"></td> <td><input type="submit" name="clear" value="Clear Cart"></td> </tr> </table> </form> </body> </html>

30

You might also like