Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-02-26 02:10:34

Description: CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

Search

Read the Text Version

UNIT - 6: REGULAR EXPRESSIONS STRUCTURE 6.0 Learning Objectives 6.1 Introduction 6.2 Regular Expression Syntax (POSIX) 6.3 Brackets 6.4 Quantifiers 6.5 Predefined Character Ranges 6.6 Summary 6.7 Keywords 6.8 Learning Activity 6.9 Unit End Questions 6.10 References 6.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe regular expressions  Know the syntax of regular expressions  State the importance and use of brackets  List the various quantifiers 6.1 INTRODUCTION Regular Expressions, commonly known as \"regex\" or \"RegExp\", are a specially formatted text strings used to find patterns in text. Regular expressions are one of the most powerful tools available today for effective and efficient text processing and manipulations. For example, it can be used to verify whether the format of data i.e., name, email, phone number, etc. entered by the user was correct or not, find or replace matching string within text content, and so on. 101 CU IDOL SELF LEARNING MATERIAL (SLM)

6.2 REGULAR EXPRESSION SYNTAX (POSIX) Regular expression syntax includes the use of special characters (do not confuse with the HTML special characters). The characters that are given special meaning within a regular expression, are: *? + [ ] ( ) { } ^ $ | \\. You will need to backslash these characters whenever you want to use them literally. For example, if you want to match \".\", you'd have to write \\. All other characters automatically assume their literal meanings. 6.3 BRACKETS Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A character class always matches a single character out of a list of specified characters that means the expression [abc] matches only a, b or c character. Negated character classes can also be defined that match any character except those contained within the brackets. A negated character class is defined by placing a caret (^) symbol immediately after the opening bracket, like this [^abc]. You can also define a range of characters by using the hyphen (-) character inside a character class, like [0-9]. Let's look at some examples of character classes: RegExp What it Does [abc] Matches any one of the characters a, b, or c. [^abc] Matches any one character other than a, b, or c. [a-z] Matches any one character from lowercase a to lowercase z. [A-Z] Matches any one character from uppercase a to uppercase z. [a-Z] Matches any one character from lowercase a to uppercase Z. [0-9] Matches a single digit between 0 and 9. [a-z0-9] Matches a single character between a and z or between 0 and 9. 102 CU IDOL SELF LEARNING MATERIAL (SLM)

6.4 QUANTIFIERS We use quantifiers in order to specify the number of times that a group of characters or a character can be repeated in a regular expression. For example, in order to find a match to the string \"Mississippi\", we can use the following expression: 1$regex = \"/Mis{2}is{2}ip{2}i/\"; The {2} in the expression means exactly 2 times. The following table gives examples to the use of quantifiers: The quantifier Searches for n{x} the letter 'n' exactly x times n{2} the letter 'n' exactly 2 times n{x,y} 'n' between x and y times n{2,3} 'n' between 2 and 3 times n{x,} 'n' at least x times n{2,} 'n' at least 2 times n{,y} 'n' not more then y times n{,3} 'n' not more than 3 times For example, we can find a match to both \"color\" and \"colour\" by using the following regular expression: 1$regex = \"colou{0,1}r\"; Here, the use of the quantifier makes the 'u' optional. Other regex quantifiers are less specific: 103 CU IDOL SELF LEARNING MATERIAL (SLM)

The quantifier Searches for * zero times or more + at least 1 time ? zero or 1 time For example, the following expression can match both \"color\" and \"colour\". 1$regex = \"colou?r\"; Since the \"?\" metacharacter makes the one character that it follows optional, the regular expression finds a match with or without the \"u\". 6.5 PREDEFINED CHARACTER RANGES For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set − Sr. Expression & Description No 1 [[: alpha:]] It matches any string containing alphabetic characters aA through zZ. 2 [[:digit:]] It matches any string containing numerical digits 0 through 9. 3 [[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9. 4 [[:space:]] 104 CU IDOL SELF LEARNING MATERIAL (SLM)

It matches any string containing a space. 6.6 SUMMARY Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Sometimes regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings. The exact sequences of characters are unpredictable beforehand, so the regex helps in fetching the required strings based on a pattern definition. Regular expressions are used almost everywhere in today’s application programming.  Regular expressions help in validation of text strings which are of programmer’s interest.  It offers a powerful tool for analyzing, searching a pattern and modifying the text data.  It helps in searching specific string pattern and extracting matching results in a flexible manner.  It helps in parsing text files looking for a defined sequence of characters for further analysis or data manipulation.  With the help of in-built regexes functions, easy and simple solutions are provided for identifying patterns.  It effectively saves a lot of development time, which are in search of specific string pattern.  It helps in important user information validations like email address, phone numbers and IP address.  It helps in highlighting special keywords in a file based on search result or input.  It helps in identifying specific template tags and replacing those data with the actual data as per the requirement.  Regexes are very useful for creation of HTML template system recognizing tags.  Regexes are mostly used for browser detection, spam filteration, checking password strength and form validations. 6.7 KEYWORDS  Regex- Regular Expressions, commonly known as \"regex\" or \"RegExp  Quantifiers-We use quantifiers in order to specify the number of times that a group of characters 105 CU IDOL SELF LEARNING MATERIAL (SLM)

 character classes - For your programming convenience several predefined character ranges, also known as character classes  [[:alnum:]]-It matches any string containing alphanumeric characters aA through zZ and 0 through  [[:space:]]-It matches any string containing a space. 6.8 LEARNING ACTIVITY 1. Write a PHP script that checks if a string contains another string ___________________________________________________________________________ ___________________________________________________________________________ 2. Write a PHP script that removes the whitespaces from a string ___________________________________________________________________________ ___________________________________________________________________________ 6.9 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is regular expression? 2. What are qualifiers? 3. Give regular expression syntax. 4. Why brackets used for? 5. What is Predefined Character Ranges? Long Questions 1. Retrieve all lines from a text file that do not contain /the /. Retrieve all lines that contain \"the\" with lower- or upper-case letters. 2. Retrieve lines that contain a word of any length that starts with t and ends with e. Modify this so that the word has at least three characters. 3. Retrieve lines that start with a. Retrieve lines that start with a and end with n. Hint: You need to specify the beginning of the line, \"a\", any number of any characters in the middle, \"n\", end of line. 4. Retrieve blank lines. Think of at least two ways of doing this. 5. Retrieve lines that contain a word that starts with an upper-case letter. B. Multiple Choice Questions 1. The POSIX implementation of regular expression was deprecated in the PHP version… 106 CU IDOL SELF LEARNING MATERIAL (SLM)

a. 5.2 b. 5.3 c. 5.4 d. 6 2. State whether the following statements about regular expression are TRUE or FALSE. i. A regular expression is nothing more than a pattern of characters itself that was matched against a certain parcel of text. ii. It may be a pattern with which you are already familiar or it may be a pattern with specific meaning in the context of the word of pattern matching. a. i-True, ii-False b. i-False, ii-True c. i-False, ii-False d. i-True, ii-True 3... are used to represent a list or range of characters to be matched. a. [] b. {} c. () d. /* 4. In PHP’s regular expression … matches any string containing at least one a. a. a* b. a c. a+ d. a {1} 5. The regular expression … matches any string containing zero or more a’s. a. a* b. a c. a+ d. a{1} Answers 107 1-b, 2-d, 3-a, 4-c, 5-a CU IDOL SELF LEARNING MATERIAL (SLM)

6.10 REFERENCES Textbooks  T1: Steven Holzner, WordPress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGrady, Wordpress, O’Reilly, Shroff Publishers. 108 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 7: OBJECTS STRUCTURE 7.0 Learning Objectives 7.1 Introduction 7.2 Declaring a class 7.3 Creating an object 7.4 Accessing properties and methods 7.5 Summary 7.6 Keywords 7.7 Learning Activity 7.8 Unit End Questions 7.9 References 7.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe nature of human resource management  Identify scope of human resource  State the need and importance of HRM  List the functions of HRM 7.1 INTRODUCTION Objects are real-world entities. Objects are defined from classes in Object-Oriented Programming like PHP. When a class is defined, we can create many objects out of the class. Example Class Car is defined, then Mercedes, BMW, Skoda are all objects of the Class Car. A class is a blueprint of an object. A class contains variables and functions. These data variables are called properties and data functions are called data methods. The definition of an object goes like this, an object is an instance of a class. We can create an instance of the class by using the new keyword. We can create multiple instances of the class. These instances can now access the class functions, the class members. 109 CU IDOL SELF LEARNING MATERIAL (SLM)

7.2 DECLARING A CLASS To design your program or code library in an object-oriented fashion, you'll need to define your own classes, using the class keyword. A class definition includes the class name and the properties and methods of the class. Class names are case-insensitive and must conform to the rules for PHP identifiers. The class name stdClass is reserved. Here's the syntax for a class definition: class classname [ extends baseclass ] { [ var $property [ = value ]; ... ] [ function functionname (args) { // code } ... ] } 7.3 CREATING AN OBJECT Creating an object is the same as instantiating a class. This instance is created using the new keyword. This process is called instantiation. Since objects are instances of a class and can be created using a new keyword let us take a look at how these instances are created. Syntax: objectname = new Classname(); Examples: $parrot = new Bird(); $pigeon = new Bird(); $woodpecker = new Bird(); Above are three different objects of the class Bird. Using these objects we can access the properties and functions of the class Bird. 110 CU IDOL SELF LEARNING MATERIAL (SLM)

7.4 ACCESSING PROPERTIES AND METHODS Once you have an object, you can use the -> notation to access methods and properties of the object: $object->propertyname $object->methodname([arg, ... ]) For example: printf(\"Rasmus is %d years old.\\n\", $rasmus->age); // property access $rasmus->birthday(); // method call $rasmus->set_age(21); // method call with arguments Methods are functions, so they can take arguments and return a value: $clan = $rasmus->family('extended'); PHP does not have the concept of private and public methods or properties. That is, there’s no way to specify that only the code in the class should be able to directly access a particular property or method. Encapsulation is achieved by convention—only an object’s code should directly access its properties—rather than being enforced by the language itself. You can use variable variables with property names: $prop = 'age'; echo $rasmus->$prop; A static method is one that is called on a class, not on an object. Such methods cannot access properties. The name of a static method is the class name, followed by two colons and the function name. For instance, this calls the p( ) method in the HTML class: HTML::p(\"Hello, world\"); A class’s documentation tells you which methods are static. Assignment creates a copy of an object with identical properties. Changing the copy does not change the original: $f = new Person('Fred', 35); $b = $f; // make a copy $b->set_name('Barney'); // change the copy printf(\"%s and %s are best friends.\\n\", ... 7.5 SUMMARY  A class defines everything that an instance object of will contain. A class can be thought of as a cookie cutter, and objects as the cookies.  An attribute is a data container such as a variable, or array. An attribute is available to the class scope and is defined, or instantiated, with the var keyword. 111 CU IDOL SELF LEARNING MATERIAL (SLM)

 A method is a function inside a class that is available to its scope. A method is still defined with the function keyword.  An object is instantiated from a class by using the new keyword.  Class members (attributes and methods) can be accessed through the object with the - > operator. And, when accessing members, we do not use the $ symbol as a prefix.  When accessing a class member directly, without instantiating an object, we use the scope resolution operator (double colon -: :).  Class members defined as const or static must be accessed with the scope resolution operator. 7.6 KEYWORD  Object-an Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also known as instances.  Class-Classes are the blueprints of objects  OOP- is a way to treat data and behaviour as single, reusable units.  Methods-Method is actually a function used in the context of a class/object. 7.7 LEARNING ACTIVITY 1. Write a simple PHP class which displays the following string. ___________________________________________________________________________ ___________________________________________________________________________ 2. Write a PHP class that sorts an ordered integer array with the help of sort () function. ___________________________________________________________________________ ___________________________________________________________________________ 7.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Define OOP. 2. What is object? 3. How to define Object? 4. What is class? 5. How to define class? 6. How to call class through object? 112 CU IDOL SELF LEARNING MATERIAL (SLM)

Long Questions 113 1. Define a class with example? 2. What Is Object Oriented Programming? 3. What are the main features of OOPs? 4. Calculate the difference between two dates using PHP OOP approach. 5. Write a PHP class that calculates the factorial of an integer. B. Multiple Choice Questions 1. Objects are also known as ______. a. Reference b. Template c. Class d. instances 2. Object is created using ____ keyword? a. create b. object c. new d. None of these 3. A member function typically accesses members of _____ object only a. Current b. previous c. next d. All of these 4. Constructor is also called ____ function a. Find b. Key c. Automatic d. magic 5. Which one of the following functions is used to determine object type? a. obj_type() b. type() CU IDOL SELF LEARNING MATERIAL (SLM)

c. is_a() d. is_obj() Answers 1-d, 2-c, 3-a. 4-d, 5-c 7.9 REFERENCES Textbooks  T1: Steven Holzner, WordPress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGrady, WordPress, O’Reilly, Shroff Publishers. 114 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 8: PHP FILE HANDLING STRUCTURE 8.0 Learning Objectives 8.1 Introduction 8.2 Understanding file & Directory 8.3 File functions 8.4 working with directories 8.5 building a text editor 8.6 File Uploading & Downloading Topic1 8.7 Summary 8.8 Keywords 8.9 Learning Activity 8.10 Unit End Questions 8.11 References 8.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Include the code from one script file inside another script file  Open files  Close files  Read data from files  Write data to file 8.1 INTRODUCTION Files are stored in directories on a hard drive, and because they retain their data after the computer is shut down, they are a persistent storage mechanism, instead of temporary storage such as RAM. As a server-side programming language, PHP allows you to work with files and directories stored on the Web server. This is very useful, because it means your PHP scripts can store information outside the scripts themselves. This chapter is all about the PHP functions for working with the file system 115 CU IDOL SELF LEARNING MATERIAL (SLM)

8.2 UNDERSTANDING FILE & DIRECTORY A file is very much like a typed document that you might find on someone's desk or in a filing cabinet; it's an item that contains a collection of related information. On a computer, examples of files include text documents, spreadsheets, digital pictures, and even songs. Every picture you take with a digital camera, for example, is a separate file, and a music CD might contain a dozen individual song files. Your computer represents files with icons. By looking at a file's icon, you can tell at a glance what kind of file it is. Here are some common file icons: You can tell what kind of file an icon represents by its appearance A folder is little more than a container in which you can store files. If you put thousands of paper files on someone's desk, it would be virtually impossible to find any particular one when you needed it. That's why people often store paper files in folders inside a filing cabinet. Arranging files into logical groups makes it easy to locate any particular file. Folders on your computer work exactly the same way. A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as your PHP scripts simply provide the directory name. To create a new directory in a different directory, specify the full path when calling mkdir(). A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable): <?php $result = mkdir (\"/path/to/directory\", \"0777\"); ?> <google>ADSDAQBOX_FLOW</google> 8.3 FILE FUNCTIONS PHP provides a convenient way of working with files via its rich collection of built-in functions. Operating systems such as Windows and MAC OS are not case sensitive while Linux or Unix operating systems are case sensitive. Adopting a naming conversion such as lower-case letters only for file naming is a good practice that ensures maximum cross platform compatibility. Let’s now look at some of the most commonly used PHP file functions. PHP File_exists Function 116 CU IDOL SELF LEARNING MATERIAL (SLM)

This function is used to determine whether a file exists or not.  It comes in handy when we want to know if a file exists or not before processing it.  You can also use this function when creating a new file and you want to ensure that the file does not already exist on the server. The file_exist function has the following syntax. <?php file_exists($filename); ?> HERE,  “file_exists()” is the PHP function that returns true if the file exists and false if it does not exist.  “$file_name” is the path and name of the file to be checked The code below uses file_exists function to determine if the file my_settings.txt exists. <?php if (file_exists('my_settings.txt')) { echo 'file found!'; } else { echo 'my_settings.txt does not exist'; } ?> Save the above code in a file named file_function.php Assuming you saved the file in phptuts folder in htdocs, open the URL http://localhost/phptuts/file_function.php in your browser You will get the following results. 117 CU IDOL SELF LEARNING MATERIAL (SLM)

PHP Fopen Function The fopen function is used to open files. It has the following syntax <?php fopen($file_name,$mode,$use_include_path,$context); ?> HERE,  “fopen” is the PHP open file function  “$file_name” is the name of the file to be opened  “$mode” is the mode in which the file should be opened, the table below shows the modes Mode Description r  Read file from beginning.  Returns false if the file doesn’t exist.  Read only r+  Read file from beginning  Returns false if the file doesn’t exist.  Read and write 118 CU IDOL SELF LEARNING MATERIAL (SLM)

w  Write to file at beginning  truncate file to zero length  If the file doesn’t exist attempt to create it.  Write only w+  Write to file at beginning, truncate file to zero length  If the file doesn’t exist attempt to create it.  Read and Write a  Append to file at end  If the file doesn’t exist attempt to create it.  Write only a+  Php append to file at end  If the file doesn’t exist attempt to create it  Read and write  “$use_include_path” is optional, default is false, if set to true, the function searches in the include path too.  “$context” is optional, can be used to specify the context support. PHP Fwrite Function The fwrite function is used to write files. It has the following syntax <?php fwrite($handle, $string, $length); ?> HERE,  “fwrite” is the PHP function for writing to files  “$handle” is the file pointer resource  “$string” is the data to be written in the file.  “$length” is optional, can be used to specify the maximum file length. 119 CU IDOL SELF LEARNING MATERIAL (SLM)

PHP Fclose Function Is used to close a file in php which is already open It has the following syntax. <?php fclose($handle); ?> HERE,  “fclose” is the PHP function for closing an open file  “$handle” is the file pointer resource. Let’s now look at an example that creates my_settings.txt. We will use the following functions.  Fopen  Fwrite  fclose The code below “create_my_settings_file.php” implements the above example. Open a file <?php $fh = fopen(\"my_settings.txt\", 'w') or die(\"Failed to create file\"); ?> Closing a file <?php fclose($fh); ?> 120 CU IDOL SELF LEARNING MATERIAL (SLM)

Create File <?php $fh = fopen(\"my_settings.txt\", 'w') or die(\"Failed to create file\"); $text = <<<_END localhost;root;pwd1234;my_database _END; fwrite($fh, $text) or die(\"Could not write to file\"); fclose($fh); echo \"File 'my_settings.txt' written successfully\"; ?> 8.4 WORKING WITH DIRECTORIES Creating Directories in PHP A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as your PHP script simply provide the directory name. To create a new directory in a different directory specify the full path when calling mkdir(). A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable): <?php $result = mkdir (\"/path/to/directory\", \"0777\"); ?> 121 CU IDOL SELF LEARNING MATERIAL (SLM)

<google>ADSDAQBOX_FLOW</google> Deleting a Directory Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted. Finding and Changing the Current Working Directory It is unlikely that a web application will be able to perform all of its file related tasks in a single directory. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP script. The current working directory can be identified using the getCwd() function: <?php $current_dir = getCwd(); echo \"Current directory is $current_dir\"; ?> The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory: <?php $current_dir = getCwd(); echo \"Current directory is $current_dir <br>\"; chdir (\"/tmp\"); $current_dir = getCwd(); echo \"Current directory is now $current_dir <br>\"; 122 ?> CU IDOL SELF LEARNING MATERIAL (SLM)

8.5 BUILDING A TEXT EDITOR This is a simple set of scripts to edit, view, and delete text files that are stored on a web server. Put edit.php, view.php, delete.php, and styles.css in a folder, then create a subfolder called 'txt' and set permissions to 717. View.php <!DOCTYPE HTML> <html> <head> <meta charset=\"utf-8\"> <title>Text Viewer</title> <meta name=\"description\" content=\"Viewer\"> <meta name=\"viewport\" content=\"width=device-width\"> <link rel=\"stylesheet\" href=\"styles.css\"> </head> <?php // first we need to see if we actually GET anything $gettest = $_GET['p']; if ( isset($gettest) ){ // THEN do this shit // need to lowercase the filename $gettest = strtolower($gettest); // remove all whitespace $gettest = preg_replace('/\\s+/', '', $gettest); // set file to read $filename ='txt/'.$gettest.'.txt'; // check if file exists if (file_exists($filename)) { // now open the file $fh = @fopen($filename, \"r\"); 123 CU IDOL SELF LEARNING MATERIAL (SLM)

// read file contents $data = @fread($fh, filesize($filename)); // then close it fclose($fh); } echo '<body style=\"font-family: monospace;\">'; echo nl2br($data); echo '</body>'; // and if we got no p variable don't do anything } else { echo \"<h1>No file to view</h1>\"; } ?> </html> Edit.php <!DOCTYPE HTML> <html> <head> <meta charset=\"utf-8\"> <title>Text Editor</title> <meta name=\"description\" content=\"Editor\"> <meta name=\"viewport\" content=\"width=device-width\"> <!-- <link rel=\"shortcut icon\" href=\"img/icon.ico\" type=\"image/x-icon\" /> --> <!-- CSS --> <!-- <link href=\"css/bootstrap.min.css\" rel=\"stylesheet\"> --> <link rel=\"stylesheet\" href=\"styles.css\"> <!-- JS <script src=\"js/vendor/jquery.min.js\"></script> <script src=\"js/script.js\"></script>--> </head> 124 CU IDOL SELF LEARNING MATERIAL (SLM)

<?php 125 // first we need to see if we actually GET anything $gettest = $_GET['p']; if ( isset($gettest) ){ // THEN do this shit // need to lowercase the filename $gettest = strtolower($gettest); // remove all whitespace $gettest = preg_replace('/\\s+/', '', $gettest); // set file to read $filename ='txt/'.$gettest.'.txt'; // check if file exists if (file_exists($filename)) { // now we check if we are renaming the file // check if variable has been set $renamed = @$_GET['renamed']; if ( isset($renamed) ){ // and lowercase filename $renamed = strtolower($renamed); // strip whitespace $renamed = preg_replace('/\\s+/', '', $renamed); // check to see if other files with the same name exist foreach(glob('txt/*.txt') as $txtfile){ $txtfile = basename($txtfile,\".txt\"); // echo $txtfile; // echo $renamed; // if we do find the same name then we have to figure out wtf we're doing with it if ( $renamed == $txtfile ) { // then what? run the rename function again to get a new variable CU IDOL SELF LEARNING MATERIAL (SLM)

echo '<script>var renamed = prompt(\"There is already a file named that! Try again\"); var filename = \"'.$renamed.'\"; if (renamed != \"\" && renamed != filename) { var renamed = renamed.toLowerCase(); var renamed = renamed.replace(/\\s/g, \"\"); Window. Location = \"edit.php?p='.$gettext.'&renamed=\" + renamed; } else { alert(\"Could not rename file\"); window.location = \"edit.php\"; } </script>'; $renamed = \"\"; } } if ( $renamed != \"\" ) { // make it reference an actual file $renamedFile = 'txt/'.$renamed.'.txt'; // and rename it rename($filename,$renamedFile); // we still have to set this filename $filename = $renamedFile; // actually I give up and just want to reload with the new filename // duhh I think this should work echo '<script>window.location = \"edit.php?p='.$renamed.'\"</script>'; } } // now open the file $fh = @fopen($filename, \"r\"); // read file contents $data = @fread($fh, filesize($filename)); 126 CU IDOL SELF LEARNING MATERIAL (SLM)

// then close it fclose($fh); } else { // if not, create it fopen($filename, \"w+\"); // read file contents $data = @fread($fh, filesize($filename)); // close file @fclose($fh); } // and if we got no p variable, take us to the first text file } else { foreach(glob('txt/*.txt') as $txtfile) { // get filename only $txtfile = basename($txtfile,\".txt\"); echo '<script>window.location = \"edit.php?p='.$txtfile.'\"</script>'; break; } } echo '<body> <div class=\"main-container\"> <div class=\"editor-view\"> <form action=\"\" method= \"post\" > <textarea rows=\"20\" name=\"newd\">'.$data.'</textarea> <input type=\"submit\" value=\"Save\" align=\"right\"> </form> </div> <div class=\"menu-view\"> 127 CU IDOL SELF LEARNING MATERIAL (SLM)

<font style=\"font-size: 70%; text-align: center;\"><center>Saved Files - (x) to delete, DL to download, V to view</center></font> <table align=\"center\">'; //<ul id=\"notes-list\">'; // get list of txt files (I think this works) // loop text files foreach(glob('txt/*.txt') as $txtfile) { $txtfile = basename($txtfile,\".txt\"); // take out .txt // put some fucking tables in here // also we can add direct links to each text file to download // don't add a link for the currently open file if ( $gettest == $txtfile ) { echo '<tr><td>'.$txtfile.'</td><td align=\"center\"><a href=\"delete.php?p='.$txtfile.'\" style=\"text- decoration: none;\"><font color=\"red\">(x)</font></a></td><td><a href=\"txt/'.$txtfile.'.txt\">DL</a></td><td><a href=\"view.php?p='.$txtfile.'\">V</a></td></tr>' ; } else { echo '<tr><td><a href=\"edit.php?p='.$txtfile.'\">'.$txtfile.'</a></td ><td align=\"center\"><a href=\"delete.php?p='.$txtfile.'\" style=\"text- decoration: none;\"><font color=\"red\">(x)</font></a></td><td><a href=\"txt/'.$txtfile.'.txt\">DL</a></td><td><a href=\"view.php?p='.$txtfile.'\">V</a></td></tr>' ; 128 CU IDOL SELF LEARNING MATERIAL (SLM)

} } //</ul> echo '<script> function newFile() { var txtfile = prompt(\"Name of new text file\"); if (txtfile != \"\") { var txtfile = txtfile.toLowerCase(); var txtfile = txtfile.replace(/\\s/g, \"\"); window.location = \"edit.php?p=\" + txtfile; } } function renameFile() { var renamed = prompt(\"New name to rename file\"); if (renamed != \"\") { var renamed = renamed.toLowerCase(); var renamed = renamed.replace(/\\s/g, \"\"); window.location = \"edit.php?p='.$gettest.'&renamed=\" + renamed; } }</script> <tr><td> <button onclick=\"newFile()\">New File</button> </td><td> <button onclick=\"renameFile()\" align=\"right\">Rename</button> </td></tr> </table> </div> </div> </body>'; 129 CU IDOL SELF LEARNING MATERIAL (SLM)

$newdata = @$_POST['newd']; 130 if (isset($newdata)) { // open file $fw = fopen($filename, 'w') or die('Could not open file!'); // write to file // added stripslashes to $newdata // strip tags if someone is using html or php tags that is a no-no $newdata = strip_tags($newdata); $fb = fwrite($fw,stripslashes($newdata)) or die('Could not write to file'); // close file fclose($fw); echo '<script> location = location </script> '; } ?> </html> Delete.php <?php // set file to read $filename ='txt/'.$_GET['p'].'.txt'; // check if file exists if (file_exists($filename)) { unlink($filename); } foreach(glob('txt/*.txt') as $txtfile) { $txtfile = basename($txtfile,\".txt\"); CU IDOL SELF LEARNING MATERIAL (SLM)

echo '<script>window.location = \"editor.php?p='.$txtfile.'\"</script>'; 131 break; } Style.css html, body { height: 90%; } a{ color:black; text-align: left; } h3 { margin-top: 0px; margin-right: 30px } table { /* border: none; */ width: 75%; text-align: left; } textarea { width: 80%; height: 90%; } html { CU IDOL SELF LEARNING MATERIAL (SLM)

box-sizing: border-box; 132 } *, *:before, *:after { box-sizing: inherit; } .main-container { width: 100%; height: 90%; position: relative; } .editor-view { /* background: green; */ width: 99%; float: left; height: 90%; } .list { /* background: green; */ overflow:auto; height:500px; width: 80%; } .menu-view { /* background: red; */ position: fixed; float:right; CU IDOL SELF LEARNING MATERIAL (SLM)

text-align:center; top: 0; right: 0; width: 22%; z-index: 10; } 8.6 BUILDING A TEXT EDITOR How you can upload files of various formats including .zip, .pdf, .docx, .ppt, as well as image files through a form using PHP to be stored in a folder on our server. We will also record the name of the uploaded files and related info such as the file name, size, and the number of downloads in a database table. Create a new PHP project folder and call it file-upload-download. Create a subfolder inside this folder called uploads (this is where our uploaded files will be stored), and a file called index.php. index.php is where we will create our file upload form. Open it and put this code inside it: index.php: <?php include 'filesLogic.php';?> <!DOCTYPE html> <html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"style.css\"> <title>Files Upload and Download</title> </head> <body> <div class=\"container\"> <div class=\"row\"> <form action=\"index.php\" method=\"post\" enctype=\"multipart/form-data\" > <h3>Upload File</h3> <input type=\"file\" name=\"myfile\"><br> <button type=\"submit\" name=\"save\">upload</button> 133 CU IDOL SELF LEARNING MATERIAL (SLM)

</form> </div> </div> </body> </html> It's a very simple form that takes just the input field for our file and an upload button. In the head section, we are linking to our style.css file to provide some styling to our form. Create that file in the root of our application and add this CSS code to it: style.css: form { width: 30%; margin: 100px auto; padding: 30px; border: 1px solid #555; } input { width: 100%; border: 1px solid #f1e1e1; display: block; padding: 5px 10px; } button { border: none; padding: 10px; border-radius: 5px; } table { width: 60%; border-collapse: collapse; margin: 100px auto; 134 CU IDOL SELF LEARNING MATERIAL (SLM)

} th, td { height: 50px; vertical-align: center; border: 1px solid black; } At the top of index.php, we are including filesLogic.php file. This is the file that contains all the logic of receiving our submitted file and saving it to the uploads folder as well as storing the file information in the database. Let's create this file now. filesLogic.php: <?php // connect to the database $conn = mysqli_connect('localhost', 'root', '', 'file-management'); // Uploads files if (isset($_POST['save'])) { // if save button on the form is clicked // name of the uploaded file $filename = $_FILES['myfile']['name']; // destination of the file on the server $destination = 'uploads/' . $filename; // get the file extension $extension = pathinfo($filename, PATHINFO_EXTENSION); // the physical file on a temporary uploads directory on the server 135 $file = $_FILES['myfile']['tmp_name']; CU IDOL SELF LEARNING MATERIAL (SLM)

$size = $_FILES['myfile']['size']; if (!in_array($extension, ['zip', 'pdf', 'docx'])) { echo \"You file extension must be .zip, .pdf or .docx\"; } elseif ($_FILES['myfile']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte echo \"File too large!\"; } else { // move the uploaded (temporary) file to the specified destination if (move_uploaded_file($file, $destination)) { $sql = \"INSERT INTO files (name, size, downloads) VALUES ('$filename', $size, 0)\"; if (mysqli_query($conn, $sql)) { echo \"File uploaded successfully\"; } } else { echo \"Failed to upload file.\"; } } } At the top of this file, we are connecting to a database but we've not yet created it yet. Let's do that now. Create a new database called file-management. Under this database, create a table called files and give it the following fields.  id - INT  name - VARCHAR(255)  size - INT  downloads Now open index.php file in your browser. Click on the file input field and select any file from your machine to upload. 136 CU IDOL SELF LEARNING MATERIAL (SLM)

Note: Depending on your php configuration, your file may fail to upload if the size exceeds the upload_max_filesize value set in your php.ini file. You can always configure this info in your php.ini file. Increase the values of post_max_size and upload_max_filesize . Having selected your file, you can click on the upload button. If everything goes well, your file will be uploaded to the uploads folder in your project and a new record will be created in the files table in the database containing the filename, size, and downloads count. Now our file has been uploaded. You can check your uploads folder and database table to confirm that it was successful. Let's display it so that the user can view it and click on it to download it. First, we need to fetch the file info from the database. Open filesLogic.php and add these 3 lines of code just below the line where we connect to the database: <?php // connect to database $conn = mysqli_connect('localhost', 'root', '', 'file-management'); $sql = \"SELECT * FROM files\"; $result = mysqli_query($conn, $sql); $files = mysqli_fetch_all($result, MYSQLI_ASSOC); This selects all files information from the database and sets it to an array variable called $files. Now create a file called downloads.php in the root folder of our application and add this code inside it: downloads.php: <?php include 'filesLogic.php';?> <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"style.css\"> <title>Download files</title> </head> 137 CU IDOL SELF LEARNING MATERIAL (SLM)

<body> <table> <thead> <th>ID</th> <th>Filename</th> <th>size (in mb)</th> <th>Downloads</th> <th>Action</th> </thead> <tbody> <?php foreach ($files as $file): ?> <tr> <td><?php echo $file['id']; ?></td> <td><?php echo $file['name']; ?></td> <td><?php echo floor($file['size'] / 1000) . ' KB'; ?></td> <td><?php echo $file['downloads']; ?></td> <td><a href=\"downloads.php?file_id=<?php echo $file['id'] ?>\">Download</a></td> </tr> <?php endforeach;?> </tbody> </table> </body> </html> Now on this page, the files information from the database are listed each along with its size in KB and number of downloads. There is also a download button against each file. What remains now is the code that actually downloads the file from our uploads folder. Let's write the code right away. Open filesLogic.php again and add this code at the end of the file: 138 CU IDOL SELF LEARNING MATERIAL (SLM)

filesLogic.php: // Downloads files if (isset($_GET['file_id'])) { $id = $_GET['file_id']; // fetch file to download from database $sql = \"SELECT * FROM files WHERE id=$id\"; $result = mysqli_query($conn, $sql); $file = mysqli_fetch_assoc($result); $filepath = 'uploads/' . $file['name']; if (file_exists($filepath)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filepath)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize('uploads/' . $file['name'])); readfile('uploads/' . $file['name']); // Now update downloads count $newCount = $file['downloads'] + 1; $updateQuery = \"UPDATE files SET downloads=$newCount WHERE id=$id\"; mysqli_query($conn, $updateQuery); exit; } } 139 CU IDOL SELF LEARNING MATERIAL (SLM)

When we were listing the files, each download button (or rather, download link) had a parameter called file_id attached to it. So when you click on the download link of a file, that file's id is sent to the filesLogic.php page and is grabbed by this piece of code we just added now. The code then fetches that particular file info from the database using the file_id parameter and then stores the file info in a variable called $file. Using PHP's file_exists() method with the full path to our file as an argument we check that the file actually exists in our uploads folder. Then we proceed to set some headers and finally respond with the file to the user using the readFile() function in PHP. After the file is downloaded, we update the downloads count for that particular file in the database. 8.7 SUMMARY All modern software requires to interact with files. They either require to accept inputs in the form of files or either generate output and add it to the file. In either scenario, the capability of integrating with files has become an integral feature of almost all software that is used to run businesses. For any application, the handling of files is necessary. The file must be processed for some tasks to be performed. File handling in PHP is similar to file handling by any language such as C. PHP has a lot of normal file functions to work with. 8.8 KEYWORD  Files-A collection of related data or program records stored as a unit with a single name.  Directory-an organizing unit in a computer's file system for storing and locating files.  basename()-Returns filename component of path  chgrp()-Changes file group  chmod()-Changes file mode 8.9 LEARNING ACTIVITY 1. Write a program to create a file in php. ___________________________________________________________________________ ___________________________________________________________________________ 2. Perform delete, update functions on the file created above. ___________________________________________________________________________ ___________________________________________________________________________ 140 CU IDOL SELF LEARNING MATERIAL (SLM)

8.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Define files? 2. Give example of different file extensions. 3. What directories contains? 4. Define Open () function. 5. Define fwrite () function. Long Questions 1. How files are created in PHP and how they are handled? 2. Describe valid modes in PHP used while opening the file? 3. How do PHP files work? 4. What is PHP File Handling in PHP? B. Multiple Choice Questions 1. The filesize () function returns the file size in ___________ a. bits b. bytes c. kilobytes d. gigabytes 2. Which one of the following PHP functions is used to determine a file’s last access time? a. fileltime() b. filectime() c. fileatime() d. filetime() 3. Which one of the following function is capable of reading a file into an array? a. file() b. arrfile() c. arr_file() d. file_arr() 4. Which one of the following function is capable of reading a file into a string variable? a. file_contents() 141 CU IDOL SELF LEARNING MATERIAL (SLM)

b. file_get_contents() c. file_content() d. file_get_content() 5. Which one of the following function is capable of reading a specific number of characters from a file? a. fgets() b. fget() c. fileget() d. filegets() Answers 1-b, 2-c, 3-a. 4-b, 5-a 8.11 REFERENCES Textbooks  T1: Steven Holzner, WordPress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGrady, WordPress, O’Reilly, Shroff Publishers. 142 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 9: PHP SESSION & COOKIES STRUCTURE 9.0 Learning Objectives 9.1 Introduction 9.2 Starting & Destroying PHP Session 9.3 turning on auto session 9.4 Anatomy of cookie 9.5 Setting-accessing-deleting cookies with PHP 9.6 Sessions without cookies. 9.7 Summary 9.8 Keywords 9.9 Learning Activity 9.10 Unit End Questions 9.11 References 9.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  State Starting & Destroying PHP Session  Explain turning on auto session  Know Anatomy of cookie  Setting-accessing-deleting cookies with PHP 9.1 INTRODUCTION Cookies, or browser cookies, are small pieces of data which the web server asks the client's web browser to store. Each request back to the server will include these pieces of data. The data is organized as key/value pairs. 9.2 STARTING & DESTROYING PHP SESSION Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start () function. It will create a new session and generate a unique session ID for the user. The PHP code in the example below simply starts a new session. 143 CU IDOL SELF LEARNING MATERIAL (SLM)

Example <?php // Starting session session_start(); ?> The session_start() function first checks to see if a session already exists by looking for the presence of a session ID. If it finds one, i.e. if the session is already started, it sets up the session variables and if doesn't, it starts a new session by creating a new session ID. If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array, as shown in the following example: Example <?php // Starting session session_start(); // Removing session data if(isset($_SESSION[\"lastname\"])){ unset($_SESSION[\"lastname\"]); } ?> However, to destroy a session completely, simply call the session_destroy() function. This function does not need any argument and a single call destroys all the session data. Example <?php // Starting session session_start(); // Destroying session session_destroy(); ?> 144 CU IDOL SELF LEARNING MATERIAL (SLM)

9.3 TURNING ON AUTO SESSION If you want to start a session automatically, you will have to find the below line in your php.ini file and change the value from 0 to 1 and restart your server. Here is the example to set the value of auto_start using configuration file in PHP. 1 2 3 session.auto_start = 0 By replacing or adding the value of session.auto_start to 1, you can check that a session is initiated for every PHP files. 9.4 ANATOMY OF COOKIE Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to \"forget\" the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser's headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive 145 CU IDOL SELF LEARNING MATERIAL (SLM)

User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[\"name\"]. 9.5 SETTING-ACCESSING-DELETING COOKIES WITH PHP PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately. setcookie(name, value, expire, path, domain, security); Here is the detail of all the arguments −  Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.  Value − This sets the value of the named variable and is the content that you actually want to store.  Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.  Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.  Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.  Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. 146 CU IDOL SELF LEARNING MATERIAL (SLM)

Following example will create two cookies name and age these cookies will be expired after one hour. <?php setcookie(\"name\", \"John Watkin\", time()+3600, \"/\",\"\", 0); setcookie(\"age\", \"36\", time()+3600, \"/\", \"\", 0); ?> <html> <head> <title>Setting Cookies with PHP</title> </head> <body> <?php echo \"Set Cookies\"?> </body> </html> 9.6 SESSIONS WITHOUT COOKIES PHP does two things in order to work without cookies: 1. For every HTML form that PHP finds in your HTML code (which of course can be part of a PHP file), PHP will automatically add a hidden input tag with the name PHPSESSID right after the <form> tag. The value of that hidden input tag would be whatever value PHP assigns your session ID. So, for example, the hidden input could look something like this: <form> <input type=\"hidden\" name=\"PHPSESSID\" value=\"12345678\" > </form> This way, when the form is submitted to the server, PHP will be able to retrieve the session 147 CU IDOL SELF LEARNING MATERIAL (SLM)

identifier from the form and will know who it is communicating with on the other end, and will also know which session to associate the form parameters with if it is adding the form parameters to the PHP session. 2. PHP will find all the links in your HTML code, and will modify those links so that they have a GET parameter appended to the link itself. That GET parameter will also have the name of PHPSESSID, and the value will of course be the unique session identifier – so the PHP session ID will basically be a part of the URL query string. So, for example, if your code has a link that originally looks like this: <a href=\"http://www.example.com\">Go to this link><a/> When modified by PHP to include the session ID, it could look something like this: <a href=\"http://www.example.com?PHPSESSID=72aa95axyz6cd67d82ba0f809277326dd\">Go to this link</> PHPSESSID can have it’s name changed in php ini file Note that we said PHPSESSID is the name that will be used to hold the PHP session value. The name PHPSESSID can actually be changed to whatever you want if you modify the session.name value in the php.ini file. 9.7 SUMMARY The main takeaways are that cookies live on the users browser while session files live on the server file system. Sessions still use cookies, but it is only to provide a PHP Session ID, or a reference to the Session file that lives on the server. 9.8 KEYWORD  Cookies-Cookies are arbitrary pieces of data, usually chosen and first sent by the web server, and stored on the client computer by the web browser.  set cookie ($name, $value, $expire)-dedicated function for setting cookies  PHP Sessions- A session is a way to store information (in variables) to be used across multiple pages.  Auto session-When session start () is called or when a session auto starts  PHPSESSID- PHPSESSID is the name that will be used to hold the PHP session value 148 CU IDOL SELF LEARNING MATERIAL (SLM)

9.9 LEARNING ACTIVITY 1. Use your browser to delete the cookie associated with session-cookis-1.php, and access that page again. Describe what appears now in the \"History Information\" section of that page. ___________________________________________________________________________ ___________________________________________________________________________ 2. Examine what, if any, other cookies your browser has stored recently. Make a list of work you have done on the Web over the past week, and give a rough estimate of the fraction of your Web-based work that has yielded cookies on your computer. ___________________________________________________________________________ ___________________________________________________________________________ 9.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is cookie and session in PHP? 2. How cookies are used in PHP? 3. What are cookies and session in PHP with example? 4. How to start auto session? 5. How to destroy session? Long Questions 1. What is the Difference Between Sessions and Cookies in PHP? 2. How to use cookies in php for login? 3. Write a code to start cookies session. 4. Write a code to Sessions without cookies. 5. What is session management for cookies? B. Multiple Choice Questions 1. PHP sessions are created using the . . .. function. a. session_starts() b. sessions_start() c. session_start() d. None of these 2. When you want to store user data in a session use the . . . . array. 149 CU IDOL SELF LEARNING MATERIAL (SLM)

a. $_SESSION b. SYS_SESSION c. $SESSION d. $_SESSIONS 3. Sessions allow you to a. store persistent user preference on a site b. save user authentication information from page to page c. create multipage forms d. All of these 4. A snapshot of the session data can be taken at any time and written out to a file. a. True b. False 5. When the session data is written to a file, it can be read back, decoded and applied to the current session using the . . . . Function. a. session_reset() b. session_get_cookie_params() c. session_encode() d. session_decode() Answers 1-c, 2-a, 3-d, 4-a, 5-d 9.11 REFERENCES Textbooks  T1: Steven Holzner, WordPress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGrady, WordPress, O’Reilly, Shroff Publishers. 150 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook