PHPunit1and2

Embed Size (px)

Citation preview

  • 7/29/2019 PHPunit1and2

    1/30

    Web Programming using PHP and MYSQL

    1

    UNIT 1

    1. Name any four typical web applications.Online polls, discussion forums, content management, migration from oneplatform 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 canaccess very few resources and its storage capacity is also very low with lot ofrestrictions 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 anyrestrictions.

    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 activitieslike image over or page transition effect within the browser. Server side scriptingis the best way to approach server bound activities like accessing server resourcessuch as databases, external files etc to save and retrieve those stuffs on a laterperiod.

    6. Tabulate and compare Client Side scripting and the Server Side Scripting.Client Side Scripts Server Side Scripts

    JavaScript/ HTML/VBscript PHP/ Perl/ ASP. NET/ JSP

    Limited storage capabilities for user data

    Cookies resides inside the Clients machine

    Unlimited storage

    User data resides in the server

  • 7/29/2019 PHPunit1and2

    2/30

    Web Programming using PHP and MYSQL

    2

    Temporary Storage

    Rely on Local machines capability

    Permanent Storage

    Rely on servers capabilities

    Concern about Gathering/ Displaying Usersdata at the browser

    Localized to the User Interface

    Validates all the user inputs beforeforwarding them to the server.

    Concern about Storing/ Updating UserData into DBMS

    Any errors in the data/format to the serverprompts error message thus waste of time,waste of network resources

    7. Define the term Database.Database is a collection of data organized and classified according to somecriteria.

    8. What is DBMS?DBMS is a framework with a handsome collection of tools to store and retrievedata to and from a storage device.

    9. Name the unique feature available in RDBMS.RDBMS is Relation Database Management System which is an advanced versionto 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 providedthrough web forms and save it for future reference, Create web sites thatdynamically update themselves with new content, Manage a blog (or more thanone), Process electronic payments and track customer orders, Build customizedbar graphs, pie charts, and other statistical reports from raw numeric data, Carryout 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 writedynamically generated web pages quickly. PHP is the widely used generalpurpose scripting language that is used for web development which allows theweb developers to embed it into HTML. The language is rapidly becoming thepopular choice for data-driven web applications because of its wide support fordifferent database systems.

  • 7/29/2019 PHPunit1and2

    3/30

    Web Programming using PHP and MYSQL

    3

    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 mixof more than one scripting technology. isthe sequence to indicate the last statement of the php scripting. PHP code isembedded inside a regular HTML document, and is recognized and executed bythe web server when the document is requested through a browser. The server willexecute php code and return the output to the browser in the format required orspecified by the developer. PHP code works independently of the users webbrowser.

    For example, my sample/HEAD>

    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 andsimple syntax and is absolutely available at free of cost on the Internet, for avariety of platforms and architectures, including UNIX, Microsoft Windows, andMac OS, as well as for most web servers.

    PHP is an interpreted language which enables the developer to performincremental, iterative development and testing without going through a compile-test-debug cycle each time you change your code. This can speed thedevelopment cycle drastically. A variety of data types, a powerful object-orientedengine, an extensive library of built-in functions, and support for most currentweb 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 tomonitor online resumes.

  • 7/29/2019 PHPunit1and2

    4/30

    Web Programming using PHP and MYSQL

    4

    PHP/FI 1.0 was followed by PHP/FI 2.0 and, in turn, quickly supplanted in 1997by PHP 3.0.

    PHP 3.0, developed by Andi Gutmans and Zeev Suraski was a complete rewriteof the original PHP/FI implementation and it included support for a wider rangeof databases, including MySQL and Oracle. PHP 3.0s extensible architectureencouraged independent developers to begin creating their own languageextensions, which served toincrease the languages popularity in the developer community.

    PHP 4.0, which was released in 2003, used a new engine to deliver betterperformance, greater reliability and scalability, support for web servers other thanApache, and a host of new language features, including built-in sessionmanagement and better OOP support.

    PHP 5.0, offers a completely revamped object model that uses object handles formore 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 writtenmanual; even novices find it easy to learn. PHP can even access C libraries andtake advantage of program code written for this language, and the language isrenowned for the tremendous flexibility it allows programmers in accomplishingspecific tasks.

    PortabilityPortability With programming languages, with which a program can be made towork on different platforms. PHP is available for a wide variety of platforms,including UNIX, Microsoft Windows, Mac OS, and OS/2. Additionally, becausePHP 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.

    SpeedPHP 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 anoptimized memory manager, and the use of object handles that reduce memoryconsumption and help applications run faster.

    Open Source

  • 7/29/2019 PHPunit1and2

    5/30

    Web Programming using PHP and MYSQL

    5

    PHP source code is freely available on the Web, and developers can install anduse it without paying licensing fees or investing in expensive hardware orsoftware. Using PHP can thus significantly reduce the development costs of a

    software application, without compromising on either reliability or performance.

    ExtensiblePHPs creators built an extensible architecture that enables developers to easilyadd support for new technologies to the language through modular extensions.Extensible through its add-on modules: dynamically create image, PDF, and SWFfiles; connect to IMAP and POP3 servers; interface with MySQL, Oracle,PostgreSQL, and SQLite databases; handle electronic payments; parse XMLdocuments; and execute Perl, Java, and COM code through a PHP script. And asif all that wasnt enough, theres also an online repository of free PHP classescalled PEAR, the PHP Extension and Application Repository, which provides a

    source of reusable, bug-free PHP components.

    XML and Database SupportPHP 5.0 comes with an improved MySQL extension that enables you to takeadvantage 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 redesignedXML API built around the libxml2 toolkit; this API supports SAX, DOM, andXSLT, as well as the new SimpleXML and SOAP extensions.

    16.Write about the features of MYSQL.SpeedMySQL uses a fully multithreaded architecture; special optimizers for complextasks like joins and indexing; a query cache, which improves performance withoutany special programming needed by the user; and the capability to use differentstorage engines on a per-table basis, so that users can mix and match differentfeature sets to squeeze the maximum performance out of the system.

    ReliabilityThe 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!

    SecurityMySQL comes with a sophisticated access control and privilege system to preventunauthorized users from accessing the system. This system, implemented as afive-tiered privilege hierarchy, enables MySQL administrators to protect access tosensitive data using a combination of user- and host-based authenticationschemes. Users can be restricted to performing operations only on specified

  • 7/29/2019 PHPunit1and2

    6/30

    Web Programming using PHP and MYSQL

    6

    databases or fields, and MySQL even makes it possible to control which types ofqueries a user can run, at database, table, or field level.

    Scalability and portabilityMySQL can handle extremely large and complex databases without too much of adrop in performance. Tables of several gigabytes containing hundreds ofthousands of records are not uncommon, and the MySQL web site itself claims touse databases containing 50 million records. MySQL is available for both UNIXand 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 ofarchitectures, including Intel x86, Alpha, SPARC, PowerPC, and IA64, andsupports many different hardware configurations, from low-end 386s to high-endPentium machines.

    Ease of useMySQL is very easy to use, administer, and optimize. A simple SQL command-line interface is the primary user interface to the server; users with a more visualbent can, instead, use MySQL Control Center or MySQL Administrator, two GUIclients developed by MySQL AB for MySQL usage and administration.

    Compliance with existing standardsMySQL 4.0 supports most of the important features of the ANSI SQL-99 standardand also extends the ANSI standard with its own custom functions and data typesdesigned to improve portability and provide users with enhanced functionality.

    Wide application supportMySQL exposes APIs to many different programming languages, thereby makingit possible to write database-driven applications in the language of the developerschoice. MySQL are available in C, C++, Perl, Python, and Tcl, to offer developersmaximum freedom in designing MySQL-backed applications.

    Easy licensing policyThe MySQL RDBMS is licensed under the GPL, and users are free to downloadand modify the source code of the application to their needs, and to use it topower their applications free of cost. This licensing policy has only fuelledMySQLs 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 andimportant role as explained below.Linux provides the base operating system (OS)and server environment. The Apache web server intercepts HTTP requests andeither 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

  • 7/29/2019 PHPunit1and2

    7/30

    Web Programming using PHP and MYSQL

    7

    web server. The MySQL RDBMS serves as the data storage engine, acceptingconnections 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 Webmail client. After looking up the domain, Joes browser (the client) sends anHTTP 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 isprogrammed to automatically redirect all such requests to the PHP layer, it simplyinvokes 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 clientconnection to the MySQL RDBMS and executes them. Once the script interpreterhas completed executing the script, it returns the result to the browser, cleans upafter 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.

  • 7/29/2019 PHPunit1and2

    8/30

    Web Programming using PHP and MYSQL

    8

    Define(MyName, JERALD);Define(MyAge, 40);

    MyName and MyAge are constant variables.

    19.What is the use of form tag? Give an example.Enter your message:

    (or)

    Enter your message:

    As shown above, form tags are useful to call a user defined PHP procedure and tocollect and to transfer data from one form to another form.

    The message.php looks like:

    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 bepassed 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

  • 7/29/2019 PHPunit1and2

    9/30

    Web Programming using PHP and MYSQL

    9

    Float/ Double real numbers 0.1, 0.2, 0.3, etcString A, Loyola College etcBoolean 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} etcObject 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 asshown 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 stringis_numeric() Checks if a variable or value is a numeric stringis_float() Checks if a variable or value is a floating point numberis_int() Checks if a variable or value is an integeris_null() Checks if a variable or value is NULLis_array() Checks if a variable is an arrayis_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

  • 7/29/2019 PHPunit1and2

    10/30

    Web Programming using PHP and MYSQL

    10

    . String concatenation== Equal to=== Equal to and of the same type

    !== Not equal to or not of the same type aka != Not equal to< Less than Greater than>= Greater than or equal to&& Logical AND|| Logical ORxor 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 twodifferent strings together as shown below.

    The above PHP script returns [email protected]

    26.What is operator precedence?The rule should be followed during evaluation of the operators in an expressioninstead of executing operators as it is.

    The following list illustrates the important PHP precedence rules. (Operators onthe same line have the same level of precedence.)

    '!' '++' '--''*' '/' '%''+' '' '.''=''==' '!=' '===' '!==''&&''||'

  • 7/29/2019 PHPunit1and2

    11/30

    Web Programming using PHP and MYSQL

    11

    '?' ':'

    27.Give the syntax for simple if, if else, else if and switch statements.Syntax for simple if

    Syntax for if else

    Syntax for else if

  • 7/29/2019 PHPunit1and2

    12/30

    Web Programming using PHP and MYSQL

    12

    {do this;}

    ?>

    Syntax for switch statement

    28.Give an example for each of the following i) for simple if, ii) if else, iii) else ifand v) switch statements.

  • 7/29/2019 PHPunit1and2

    13/30

    Web Programming using PHP and MYSQL

    13

    29.Give an example for the use of ternary operators.

  • 7/29/2019 PHPunit1and2

    14/30

    Web Programming using PHP and MYSQL

    14

    echo $result;?>

    30.What is nesting? Give an example.Keeping conditional statements inside each other to handle multiple conditions isknown as nesting. For example,

    31.Give an example for merging forms with its result page.

  • 7/29/2019 PHPunit1and2

    15/30

    Web Programming using PHP and MYSQL

    15

    else{echo 'You entered 0';

    }}?>

    32.When to use method="get"?When using method="get" in HTML forms, all variable names and values aredisplayed in the URL. This method should not be used when sending passwords

    or other sensitive information! The get method is not suitable for very largevariable 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 hasno limits on the amount of information to send.

    34.What are the loop structures available in PHP?While loop

    Do loopFor loopFor each loop

    35.Give the syntax for while loop and an example.

    While() loops continue to iterate for so long as the specified conditionalexpression remains true. For example,

  • 7/29/2019 PHPunit1and2

    16/30

    Web Programming using PHP and MYSQL

    16

    $i++}?>

    36.Give the syntax for Do loop and an example.

    Do-while() loops continue to iterate for so long as the specified conditional

    expression remains true. For example,

    37.Give the syntax for For loop and an example.

    PHPs for() loop uses a counter that is initialized to a numeric value, and keepstrack of the number of times the loop is executed. Before each execution of theloop, 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 itevaluates to false, the loop will be broken and the lines following it will beexecuted instead. For example,

  • 7/29/2019 PHPunit1and2

    17/30

    Web Programming using PHP and MYSQL

    17

    38.Give the syntax for For each loop and an example.

    For example, to print the values in the associative array, the following code willbe useful.

    39.Discuss about the Form Validation.The User input should be validated on the browser whenever possible (by clientscripts). 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 ofjumping to a different page. The user will then get the error messages on the samepage 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 withmethod="get".

    40.What is the use of $_REQUEST Variable?The $_REQUEST variable can be used to collect form data sent with both theGET and POST methods.

    41.How to construct a HTML table and its contents using PHP?

  • 7/29/2019 PHPunit1and2

    18/30

    Web Programming using PHP and MYSQL

    18

    ?>

    Unit II

    42.What is an array?An array is a complex variable that stores multiple values in a single variable; Anarray variable can best be thought of as a container variable, which can containone or more values. Here is an example:

  • 7/29/2019 PHPunit1and2

    19/30

    Web Programming using PHP and MYSQL

    19

    $cars[0]="Ford";$cars[1]="Volvo";$cars[2]="BMW";

    $cars[3]="Toyota";?>(or)

    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 tocreate a slightly different type of array. Each key is unique, and corresponds to asingle value within the array. Keys may be made up of any string of characters,including control characters. Here is an example.

    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 whereasarray_push() function is used to add a new values into an array.

    46.Illustrate the use of foreach statement in PHP.

  • 7/29/2019 PHPunit1and2

    20/30

    Web Programming using PHP and MYSQL

    20

    }?>

    47.How to capture all the selected form values in a single variable? Give an example.Select the departments to participate in the event from below:

  • 7/29/2019 PHPunit1and2

    21/30

    Web Programming using PHP and MYSQL

    21

    }?>

    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 andvalues within the array. For example,

    49.Define and list the functions used in array manipulations.Function is a set of program statements that perform a specific task,and that canbe called, or executed, from anywhere in the program.

    array() - populate arrays with elementsarray_pop() - remove an element from the endarray_push() - add an element to the end of an existing array

    array_shift() - pop an element off the top of the arrayarray_unshift()- adding elements to the beginning of the arraysizeof() - To return the number of elements in an arrayforeach() - To keep track of array positionslist() - 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 elementsas 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 limitednumber of statements under a name and can be called inside the programwherever it is required. Fox example,

  • 7/29/2019 PHPunit1and2

    22/30

    Web Programming using PHP and MYSQL

    22

    elsereturn ($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 ofcode into separate packages, thereby reducing unnecessary code repetition and

    redundancies. These separations of code into independent subsections also makethe code easier to understand and debug.2. Because functions are defined once (but used many times), they are easy tomaintain. A change to the function code need only be implemented in a singleplacethe function definitionwith no changes needed anywhere else.

    3. Because functions force developers to think in abstract terms (define input andoutput values, set global and local scope, and turn specific tasks into genericcomponents), they encourage better software design and help in creatingextensible 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 orSuper 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, althoughscript 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 thefile cannot be found.

    53.Describe about file handling mechanism in PHP.PHP comes with a powerful and flexible file manipulation API, which enablesdevelopers 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 afile and how to write data into a file.

  • 7/29/2019 PHPunit1and2

    23/30

    Web Programming using PHP and MYSQL

    23

    Reading Data from a File

    Writing Data to a File

    54.List out functions that are useful for testing file attributess.file_exists() Returns a Boolean indicating whether the file existsis_dir() Returns a Boolean indicating whether the specified path is a

    directoryis_file() Returns a Boolean indicating whether the specified file is a regular

    fileis_link() Returns a Boolean indicating whether the specified file is a

    symbolic linkis_executable() Returns a Boolean indicating whether the specified file isexecutableis_readable() Returns a Boolean indicating whether the specified fileis readableis_writable() Returns a Boolean indicating whether the specified fileis writablefilesize() Gets file size, in bytesfilemtime() Gets last modification time of filefileatime() Gets last access time of filefileowner() Gets file owner

    filegroup() Gets file groupfileperms() Gets file permissionsfiletype() 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 avariable whereas file_put_contents is the function to write contents into a file.

    56.Write PHP script to Obtain Directory Listings.

  • 7/29/2019 PHPunit1and2

    24/30

    Web Programming using PHP and MYSQL

    24

    57.Describe about Sessions with suitable PHP coding.HTTP protocol treats each request for a web page as a unique and independenttransaction, with no relationship whatsoever to the transactions that preceded it.As the stateless nature of the HTTP protocol makes it impossible to identifywhich transactions belong to which client or user. A common solution to theproblem is to use sessions to store information about each client and track itsactivities. This session data is preserved for the duration of the visit, and is usuallydestroyed on its conclusion.

    The Client transactions are identified through unique numbers; these identifiersare 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 passedfrom 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 generatea session ID. Once a session has been created, it becomes possible to register anynumber of session variables as shown beolw.

  • 7/29/2019 PHPunit1and2

    25/30

    Web Programming using PHP and MYSQL

    25

    On subsequent pages, calls to the session_start() function re-create the priorsession environment by restoring the values of the $_SESSION associative array.This can be tested by attempting to access the values of the session variablesregistered in the previous attempt.

    Destroying a Sessionsession_destroy() function is to erase session data as shown below.

    58.What is cookie?The cookie is a feature which allows web sites to store client-specific informationin 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 aparticular 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 toa maximum size of 4KB.3. A cookie usually possesses five types of attributes which includes Name- Setsthe name and value of the cookie,Expires - Sets the date and time at which the cookie expires, path- Sets the top-level 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 flagindicating that the cookie should be transmitted only over a secure HTTPconnection.4. Of all the five attributes, only the first is not optional.

  • 7/29/2019 PHPunit1and2

    26/30

    Web Programming using PHP and MYSQL

    26

    60.How to set/ retrieve data to/from a cookie?Setting Cookies

    Or multiple cookies

    Retrieving Cookie Data

    Deleting Cookies

    To delete a cookie, simply use setcookie() with its name to set the cookies expirydate to a value in the past.

    61.Write PHP code to get date and time.

  • 7/29/2019 PHPunit1and2

    27/30

    Web Programming using PHP and MYSQL

    27

    $current_date = $current['mday'] . '.' . $current['mon'] . '.'. $current['year'];

    echo $current_time. $current_date;

    ?>62.Illustrate the use of escapeshellarg() and escapeshellcmd() functions.

  • 7/29/2019 PHPunit1and2

    28/30

    Web Programming using PHP and MYSQL

    28

    $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();}?>CatalogPlease add items from the list below to your shopping cart.

  • 7/29/2019 PHPunit1and2

    29/30

    Web Programming using PHP and MYSQL

    29

    Shopping cart

  • 7/29/2019 PHPunit1and2

    30/30

    Web Programming using PHP and MYSQL

    30

    }}}

    ?>TOTAL