1 / 46

Unit – II Part II Scripting Essentials PHP Functions Arrays File Handling

Unit – II Part II Scripting Essentials PHP Functions Arrays File Handling. PHP Functions.

hhamlet
Download Presentation

Unit – II Part II Scripting Essentials PHP Functions Arrays File Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit – II Part II Scripting Essentials PHP Functions Arrays File Handling

  2. PHP Functions A function is a set of statements that performs a particular function and optionally—returns a value. You can pull out a section of code that you have used more than once, place it into a function, and call the function by name when you want the code. • Functions have many advantages over contiguous, inline code. For example, they: • Involve less typing • Reduce syntax and other programming errors • Decrease the loading time of program files • Decrease execution time, because each function is compiled only once, no matter how often you call it • Accept arguments and can therefore be used for general as well as specific cases PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To use a function, call it by name. For example, you can see the print function in action here: print("print is a pseudo-function"); print "print doesn't require parentheses";

  3. Functions can take any number of arguments, including zero. For example, phpinfo, as shown next, displays lots of information about the current installation of PHP and requires no argument.

  4. Some of the built-in functions that use one or more arguments appear in Example 5-1. Defining a Function The general syntax for a function is as follows: The first line of the syntax indicates the following: • A definition starts with the word function. • A name follows, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores. • The parentheses are required. • One or more parameters, separated by commas, are optional.

  5. Function names are case-insensitive. • The opening curly brace starts the statements that will execute when you call the function; a matching curly brace must close it. • These statements may include one or more return statements, which force the function to cease execution and return to the calling code. • If a value is attached to the return statement, the calling code can • retrieve it. Returning a Value Let’s take a look at a simple function to convert a person’s full name to lowercase and then capitalize the first letter of each name. For our current function, we’ll use its counterpart, strtolower: The output of this experiment is as follows: PHP also provides a ucfirst function that sets the first character of a string to uppercase:

  6. make a simple call to the print function: print(5-8); The expression 5-8 is evaluated first, and the output is –3. Returning an Array There are also ways of getting multiple values from a function. The first method is to return them within an array.

  7. Returning Global Variables The global keyword followed by the variable name gives every part of your code full access to it. Recap of Variable Scope • Local variables are accessible just from the part of code where you define them. If they’re outside of a function, they can be accessed by all code outside of functions, classes, and so on. If a variable is inside a function, only that function can access the variable, and its value is lost when the function returns. • Global variables are accessible from all parts of your code. • Static variables are accessible only within the function that declared them but • retain their value over multiple calls.

  8. Arrays Arrays is a collection of similar type of elements, but in PHP you can have the elements of dissimilar type together in a single array. In each PHP, each element has two parts: key and value. The key represents the index at which the value of the element can be stored. The keys are positive integers in increasing order. Numerically Indexed Arrays The familiar print_r function (which prints out the contents of a variable, array, or object) is used to verify that the array has been correctly populated. It prints out the following:

  9. Associative Arrays • Keeping track of array elements by index works just fine, but can require extra work in terms of remembering which number refers to which product. • It can also make code hard for other programmers to follow. • This is where associative arrays come into their own. Using them, you can reference the items in an array by name rather than by number. The names (copier, inkjet, and so on) are called indexes or keys, and the items assigned to them (such as Laser Printer) are called values.

  10. Assignment Using the array Keyword PHP assign numeric identifiers implicitly, A more compact and faster assignment method uses the array keyword. • The second half assigns associative identifiers and accompanying longer product descriptions to the array $p2 using the format index => value. • The use of => is similar to the regular = assignment operator, except that you are assigning a value to an index and not to a variable. • The index is then inextricably linked with that value, unless it is assigned a new value.

  11. The foreach...as Loop Using it, you can step through all the items in an array, one at a time, and do something with them. The process starts with the first item and ends with the last one. When PHP encounters a foreach statement, it takes the first item of the array and places it in the variable following the as keyword; and each time control flow returns to the foreach, the next array element is placed in the as keyword.

  12. The list function takes an array as its argument and then assigns the values of the array to the variables listed within parentheses. Therefore, use foreach...as to create a loop that extracts values to the variable following the as, or use the each function and create your own looping system.

  13. Multidimensional Arrays $products = array( 'paper' => array( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers"), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips") ); echo "<pre>"; foreach($products as $section => $items) foreach($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> echo $products["pens"]["marker"]; Markers

  14. This statement outputs the uppercase letter Q, the eighth element down and the fourth along The <pre> and </pre> tags ensure that the output displays correctly, like this:

  15. Using Array Functions • count($ar) - How many elements in an array • is_array($ar) - Returns TRUE if a variable is an array • isset($ar['key']) - Returns TRUE if key is set in the array • sort($ar) - Sorts the array values (loses key) • ksort($ar) - Sorts the array by key • asort($ar) - Sorts array by value, keeping key association • shuffle($ar) - Shuffles the array into random order

  16. is_array Arrays and variables share the same namespace. This means that you cannot have a string variable called $fred and an array also called $fred. To check whether a variable is an array, you can use the is_array function, like this: Note that if $fred has not yet been assigned a value, an Undefined variable message will be generated. count To know exactly how many elements there are in your array. To count all the elements in the top level of an array, use a command such as this: For a multidimensional array, you can use a statement such as the following: The second parameter is optional and sets the mode to use. It should be either a 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements too.

  17. sort Sorting is so common that PHP provides a built-in function. Here, sorting is to be made either numerically or as strings, like this: You can also sort an array in reverse order using the rsort function, like this: shuffle There may be times when you need the elements of an array to be put in random order, such as when you’re creating a game of playing cards: Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE on error. explode This is a very useful function with which you can take a string containing several items separated by a single character (or string of characters) and then place each of these items into an array.

  18. The first parameter, the delimiter, need not be a space or even a single character. extract The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value.  Syntax: int extract($input_array, $extract_rule, $prefix)

  19. $input_array: This parameter is required. This specifies the array to use. $extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: • EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable. • EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable. • EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter. • EXTR_PREFIX_ALL: This rule tells that prefix all variable names accoring to $prefix parameter. • EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix. • EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing. • EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table. $prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.

  20. <?php // input array $state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA"); extract($state); // after using extract() function echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR"; ?> <?php $AS="Original"; $state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, "dup"); echo"\$AS is $AS\n\$KR is $KR\n\$OR if $OR \n\$dup_AS = $dup_AS"; ?>

  21. compact This is the inverse of extract, to create an array from variables and their values.

  22. Another use of this function is for debugging, when you wish to quickly view several variables and their values, This works by using the explode function to extract all the words from the string into an array, which is then passed to the compact function, which in turn returns an array to print_r, which finally shows its contents.

  23. reset When the foreach...as construct or the each function walks through an array, it keeps an internal PHP pointer that makes a note of which element of the array it should return next. If your code ever needs to return to the start of an array, you can issue reset, which also returns the value of that element. end As with reset, you can move PHP’s internal array pointer to the final element in an array using the end function, which also returns the value of the element

  24. PHP Strings PHP provides a number of built-in string functions which help in performing several operations while dealing with string data. 1.Getting length of a String PHP has a predefined function to get the length of a string. Strlen() displays the length of any string. It is more commonly used in validating input fields where the user is limited to enter a fixed length of characters. Syntax: strlen(string); Example:<?php echo strlen(“Welcome to Cloudways”);//will return the length of given string ?> Output: 20 2. Counting of the number of words in a String Another function which enables display of the number of words in any specific string is str_word_count(). This function is  also useful in validation of input fields. Syntax: str_word_count(string)

  25. Example: <?php echo str_word_count(“Welcome to Cloudways”);//will return the number of words in a string ?> Output: 3 3. Reversing a String Strrev() is used for reversing a string. You can use this function to get the reverse version of any string. Syntax: strrev(string); Example: <?php echo strrev(“Welcome to Cloudways”);// will return the string starting from the end ?> Output: syawduolC ot emocleW

  26. 4. Finding Text Within a String Strpos() enables searching particular text within a string. It works simply by matching the specific text in a string. If found, then it returns the specific position. If not found at all, then it will return “False”. Strops() is most commonly used in validating input fields like email. Syntax: strpos(string, text); Example: <?php echo strpos(“Welcome to Cloudways”,”Cloudways”); ?> Output: 11 5. Replacing text within a string Str_replace() is a built-in function, basically used for replacing specific text within a string. Syntax: str_replace(string to be replaced, text, string); Example: <?php echo str_replace(“cloudways”, “the programming world”, “Welcome to cloudways”); ?> Output: Welcome to the programming world

  27. 6. Converting lowercase into Title Case Ucwords() is used to convert first alphabet of every word into uppercase. Syntax: ucwords(string); Example: <?php echo ucwords(“welcome to the php world”); ?> Output: Welcome To The Php World7. Converting a whole string into UPPERCASE Strtoupper() is used to convert a whole string into uppercase. Syntax: strtoupper(string); Example: <?php echo strtoupper(“welcome to cloudways”);// It will convert all letters of string into uppercase ?> Output: WELCOME TO CLOUDWAYS

  28. 8. Converting a whole string into LOWERCASE Strtolower() is used to convert a whole string into uppercase. Syntax: strtolower(string); Example: <?php echo strtolower(“WELCOME TO CLOUDWAYS”);// It will convert all letters of string into uppercase ?> Output: welcome to cloudways 9. Repeating a String PHP provides a built-in function for repeating a string a specific number of times. Syntax: str_repeat(string, repeat); Example: <?php echo str_repeat(“=”,13); ?> Output: =============

  29. 10. Comparing Strings You can compare two strings by using strcmp(). It returns output either greater than zero, less than zero or equal to zero. If string 1 is greater than string 2 then it returns greater than zero. If string 1 is less than string 2 then it returns less than zero. It returns zero, if the strings are equal. Syntax: strcmp(string1, string2); Example: <?php echo strcmp(“Cloudways”,”CLOUDWAYS”); echo “<br>”; echo strcmp(“cloudways”,”cloudways”);//Both the strings are equal echo “<br>”; echo strcmp(“Cloudways”,”Hosting”); echo “<br>”; echo strcmp(“a”,”b”);//compares alphabetically echo “<br>”; echo strcmp(“abb baa”,”abb baa caa”);//compares both strings and returns the result ?> in terms of number of characters. Output: 1 0 -1 -1 -4

  30. 11. Displaying part of String Through substr() function you can display or extract a string from a particular position. Syntax: substr(string,start,length); Example: <?php echo substr(“Welcome to Cloudways”,6).”<br>”; echo substr(“Welcome to Cloudways”,0,10).”<br>”; ?> Output: e to Cloudways Welcome to 12. Removing white spaces from a String Trim() is dedicated to remove white spaces and predefined characters from a both the sides of a string. Syntax: trim(string,charlist); Example: <?php $str = “Wordpess Hosting”; echo $str . “<br>”; echo trim(“$str”,”Wording”); ?> Output: Wordpess Hosting pess Host

  31. File Handling Checking Whether a File Exists To determine whether a file already exists, you can use the file_exists function, which returns either TRUE or FALSE. Creating a File At this point, testfile.txt doesn’t exist, so let’s create it and write a few lines to it. Type Example 7-4 and save it as testfile.php.

  32. When you run this in a browser, all being well, you will receive the message File • 'testfile.txt' written successfully. • If you receive an error message, your hard disk may be full or, more likely, you may not have permission to create or write to the file. • Try opening the file in a text or program editor—the contents will look like this: • Always start by opening the file. You do this through a call to fopen. • Then you can call other functions; here we write to the file (fwrite), but you can also read from an existing file (fread or fgets) and do other things. • Finish by closing the file (fclose). Although the program does this for you when it ends, you should clean up by closing the file when you’re finished. • The variable $fh(which I chose to stand for file handle) to the value returned by the fopenfunction. • Thereafter, each file-handling function that accesses the opened file, such as fwriteor fclose, must be passed $fhas a parameter to identify the file being accessed. • Upon failure, FALSE will be returned by fopen. It calls the die function to end the program and give the user an error message. • The character w, which tells the function to open the file for writing.

  33. The function creates the file if it doesn’t already exist. • If the file already exists, the w mode parameter causes the fopen call to delete the old contents

  34. Reading from Files The easiest way to read from a text file is to grab a whole line through fgets. The fread function is commonly used with binary data. But if you use it on text data that spans more than one line, remember to count newline characters.

  35. Copying Files Let’s try out the PHP copy function to create a clone of testfile.txt. Moving a File To move a file, rename it with the rename function • You can use the rename function on directories, too. • To avoid any warning messages, if the original file doesn’t exist, you can call the file_exists function first to check.

  36. Deleting a File Deleting a file is just a matter of using the unlink function to remove it from the file System. As with moving a file, a warning message will be displayed if the file doesn’t exist, which you can avoid by using file_exists to first check for its existence before calling unlink. Updating Files • Often, you will want to add more data to a saved file, which you can do in many ways. • You can use one of the append write modes or you can simply open a file for reading and writing with one of the other modes that supports writing, and • move the file pointer to the correct place within the file that you wish to write to • or read from. • The file pointer is the position within a file at which the next file access will take place, whether it’s a read or a write.

  37. This program opens testfile.txt for both reading and writing by setting the mode with 'r+', which puts the file pointer right at the start. • It then uses the fgets function to read in a single line from the file. • After that, the fseek function is called to move the file pointer right to the file end, at which point the line of text that was extracted from the start of the file is then appended to file’s end and the file is closed. • The fseek function was passed two other parameters, 0 and SEEK_END. • SEEK_END tells the function to move the file pointer to the end of the file, and 0 tells it how many positions it should then be moved backward from that point.

  38. There are two other seek options available to the fseekfunction: SEEK_SET and • SEEK_CUR. • The SEEK_SET option tells the function to set the file pointer to the exact position given by the preceding parameter. • SEEK_CUR sets the file pointer to the current position plus the value of the given offset. • Therefore, if the file pointer is currently at position 18, the following call will move it to position 23: Locking Files for Multiple Accesses • To handle simultaneous users, you must use the file-locking flock function. • This function queues up all other requests to access a file until your • program releases the lock. • So, whenever your programs use write access on files that may be accessed concurrently by multiple users, you should also add file locking to them

  39. The first call to flock sets an exclusive file lock on the file referred to by $fh using the LOCK_EX parameter: • flock($fh, LOCK_EX); • From this point onward, no other processes can write to (or even read from) the file until you release the lock by using the LOCK_UN parameter, like this: • flock($fh, LOCK_UN); • As soon as the lock is released, other processes are again allowed access to the file.

  40. Reading an Entire File A handy function for reading in an entire file without having to use file handles is file_get_contents. You can also use it to fetch a file from a server across the Internet. Uploading Files • Uploading files to a web server is a subject that seems daunting to many people, but it actually couldn’t be much easier. • All you need to do to upload a file from a form is choose a special type of encoding called multipart/form-data, and your browser will handle the rest. • To see how this works, type the program in Example 7-15 and save it as upload.php. • When you run it, you’ll see a form in your browser that lets you upload a file of your choice.

  41. The first line of the multiline echo statement starts an HTML document, displays the title, and then starts the document’s body. Next we come to the form that selects the Post method of form submission, sets the target for posted data to the program upload.php (the program itself), and tells the web browser that the data posted should be encoded via the content MIME type of multipart/form-data.

  42. Using $_FILES Five things are stored in the $_FILES array when a file is uploaded, as shown in Table (where file is the file upload field name supplied by the submitting form). Content types used to be known as MIME (Multipurpose Internet Mail Extension) types. Table shows some of the more frequently used types that turn up in $_FILES['file']['type'].

More Related