Chapter 4 Working with Files and Directories PHP Programming.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

The Web Warrior Guide to Web Design Technologies
1 PHP Storing and Retrieving Data. string fgets(resource handle [, int length]) Reads and returns one line from a file; moves file pointer to next line.
More on PHP Coding Lab no. 6 Advance Database Management System.
Objectives Handling magic quotes Understand file permissions
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
More on Functions PHP mod 4 B. Simple Mail Transfer Protocol (SMTP) mail($to, $subject, $msg, $mailheaders); m08/8-1simple_form.html m08/8-1send_simpleform.php.
Chapter 10.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Chapter 6 Working with Files and Directories PHP Programming with MySQL.
Chapter 10 Managing State Information PHP Programming with MySQL.
Guide To UNIX Using Linux Third Edition
Objectives Learn about state information
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)Slide Topic Files.
U NIT 4 F ILE U PLOAD. I. C REATE AN U PLOAD -F ILE F ORM - With PHP, it is possible to upload files to the server.To allow users to upload files from.
MS3304: Week 4 PHP & HTML Forms. Overview HTML Forms elements refresher Sending data to a script via an HTML form –The post vs. get methods –Name value.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Chapter 4 Handling User Input PHP Programming with MySQL 2nd Edition
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
XHTML Introductory1 Forms Chapter 7. XHTML Introductory2 Objectives In this chapter, you will: Study elements Learn about input fields Use the element.
JavaScript, Fourth Edition
Week Three CIT 354 Internet II. 2 Objectives Displaying Dynamic Content Sending Using Your File System Common Programming Errors Summary Quiz,
Chapter 8 Cookies And Security JavaScript, Third Edition.
PHP Programming with MySQL Slide 6-1 CHAPTER 6 Working with Files and Directories.
18. PHP File Operations Opening a File
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
PHP Programming with MySQL Slide 10-1 CHAPTER 10 Managing State Information.
Fall 2004CSI University of Ottawa Introduction to PHP Basic principles and syntax.
3 1 Sending Data Using an Online Form CGI/Perl Programming By Diane Zak.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Storing and Retrieving Data
5 1 Data Files CGI/Perl Programming By Diane Zak.
Outline Overview Opening a file How to create a file ? Closing a File Check End-of-file Reading a File Line by Line Reading a File Character by Character.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
Chapter 5 Working with Files and Directories PHP Programming with MySQL 2 nd Edition.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Advanced Web 2012 Lecture 6 Sean Costain Files Sean Costain 2012 Php allows for the : Creation Reading Appending Deleting Uploading And Closing.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
PHP-5- Working with Files and Directories. Reading Files PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 9 Structures and Sequential Access Files.
Company LOGO In the Name of Allah,The Most Gracious, The Most Merciful King Khalid University College of Computer and Information System Web pages Development.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
15 – PHP(5) Informatics Department Parahyangan Catholic University.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
CGS 3066: Web Programming and Design Spring 2016 PHP.
Uploading in PHP CPTE 212 2/24/2015 John Beckett.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Unit 7 How to Upload Files. A very useful aspect of PHP is its ability to manage file uploads to your server. Before you can use PHP to manage your uploads,
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
PHP File Handling. Opening a file Fopen(filename,mode) Closing a file Fclose(filename)
Chapter 6 Persistence-Saving and Retrieving Data
CGS 3066: Web Programming and Design Spring 2016
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Objectives In this chapter, you will:
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Arrays and files BIS1523 – Lecture 15.
CHAPTER 5 WORKING WITH FILES AND DIRECTORIES PHP PROGRAMMING WITH MYSQL 2ND EDITION MODIFIED BY ANITA PHILIPP –SPRING 2012.
Topics Introduction to File Input and Output
<?php require("header.htm"); ?>
Chapter 4 Working with Files and Directories PHP Programming
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
File Input and Output.
Topics Introduction to File Input and Output
Presentation transcript:

Chapter 4 Working with Files and Directories PHP Programming

2 Objectives Open and close files Write data to files Read data from files Manage files and directories Upload Files

Name of Book3 Opening and Closing File Streams A stream is a channel used for accessing a resource that you can read from and write to The input stream reads data from a resource (such as a file) The output stream writes data to a resource 1. Open the file stream with the fopen() function 2. Write data to or read data from the file stream 3. Close the file stream with the fclose() function

Name of Book4 Opening a File Stream A handle is a special type of variable that PHP uses to represent a resource such as a file The fopen() function opens a handle to a file stream The syntax for the fopen() function is: open_file = fopen(“text file”, “mode”); A file pointer is a special type of variable that refers to the currently selected line or character in a file

Name of Book5 Opening a File Stream (continued) Table 6-1 Mode arguments of the fopen() function

Name of Book6 Opening a File Stream (continued) $BowlersFile = fopen(“bowlers.txt”, “r+”); Figure 6-1 Location of the file pointer when the fopen() function uses a mode argument of “r+”

Name of Book7 Opening a File Stream (continued) $BowlersFile = fopen(“bowlers.txt”, “a+”); Figure 6-2 Location of the file pointer when the fopen() function uses a mode argument of “a+”

Name of Book8 Closing a File Stream Use the fclose function when finished working with a file stream to save space in memory $BowlersFile = fopen(“bowlers.txt”, “a”); $NewBowler = “Gosselin, Don\n”; fwrite($BowlersFile, $NewBowler); fclose($BowlersFile);

Name of Book9 Writing Data to Files PHP supports two basic functions for writing data to text files: file_put_contents() function writes or appends a text string to a file fwrite() function incrementally writes data to a text file

Name of Book10 Writing Data to Files (continued) Escape sequences used to identify the end of a line: UNIX/Linux platforms use the \n carriage return Macintosh platforms use \r carriage return Windows uses both the \r carriage return escape sequence and the \n newline escape sequence

Name of Book11 Writing an Entire File The file_put_contents() function writes or appends a text string to a file The syntax for the file_put_contents() function is: file_put_contents (filename, string[, options])

Name of Book12 file_put_contents() Function $TournamentBowlers = “Blair, Dennis\n”; $TournamentBowlers.= “Hernandez, Louis\n”; $TournamentBowlers.= “Miller, Erica\n”; $TournamentBowlers.= “Morinaga, Scott\n”; $TournamentBowlers.= “Picard, Raymond\n”; $BowlersFile = “bowlers.txt”; file_put_contents($BowlersFile, $TournamentBowlers);

Name of Book13 file_put_contents() Function (continued) if (file_put_contents($BowlersFile, $TournamentBowlers) > 0) echo “ Data was successfully written to the $BowlersFile file. ”; else echo “ No data was written to the $BowlersFile file. ”; If no data was written to the file, the function returns a value of 0 Use the return value to determine whether data was successfully written to the file

Name of Book14 Writing an Entire File (continued) The FILE_USE_INCLUDE_PATH constant searches for the specified filename in the path that is assigned to the include_path directive in your php.ini configuration file The FILE_APPEND constant appends data to any existing contents in the specified filename instead of overwriting it

Name of Book15 Writing an Entire File (continued) Coast City Bowling Tournament <?php if (isset($_GET['first_name']) && isset($_GET['last_name'])) { $BowlerFirst = $_GET['first_name']; $BowlerLast = $_GET['last_name']; $NewBowler = $BowlerLast. “, “. “$BowlerFirst”. “\n”; $BowlersFile = “bowlers.txt”; if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo “ {$_GET['first_name']} {$_GET['last_name']} has been registered for the bowling tournament! ”; else echo “ Registration error! ”; } else echo “ To sign up for the bowling tournament, enter your first and last name and click the Register button. ”; ?> <form action=”BowlingTournament.php” method=”get” enctype=”application/x-www-form-urlencoded”> First Name: Last Name:

Name of Book16 Writing an Entire File (continued) Figure 6-6 Bowling registration form

Name of Book17 Handling Magic Quotes Magic quotes automatically adds a backslash (\) to any: Single quote (') Double quote (”) NULL character contained in data that a user submits to a PHP script My best friend's nickname is “Bubba” My best friend\'s nickname is \”Bubba\”

Name of Book18 Handling Magic Quotes (continued) Table 6-2 Magic quote directives Disable magic quotes in your php.ini configuration file and instead manually escape the strings with the addslashes() function

Name of Book19 addslashes() Function Accepts a single argument representing the text string you want to escape and returns a string containing the escaped string $Nickname = addslashes($_GET['nickname']); echo $Nickname; // My best friend\'s nickname is \”Bubba\”. With magic quotes enabled: My best friend\\\'s nickname is \\\”Bubba\\\”

Name of Book20 stripslashes() Function Removes slashes that were added with the addslashes() function To prevent the display of escaped characters, use the stripslashes() function with the text you want to print if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo “ ”. stripslashes($_GET['first_name']). “ “. stripslashes($_GET['last_name']). “ has been registered for the bowling tournament! ”; else echo “ Registration error! ”;

Name of Book21 stripslashes() Function (continued) if (isset($_GET['first_name']) && isset($_GET['last_name'])) { $BowlerFirst = addslashes($_GET['first_name']); $BowlerLast = addslashes($_GET['last_name']); $NewBowler = $BowlerLast. “, “. “$BowlerFirst”. “\n”; $BowlersFile = “bowlers.txt”; if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo “ {$_GET['first_name']}{$_GET['last_name']} has been registered for the bowling tournament! ”; else echo “ Registration error! ”; } else echo “ To sign up for the bowling tournament, enter your first and last name and click the Register button. ”;

Name of Book22 stripslashes() Function (continued) Figure 6-7 Output of text with escaped characters

Name of Book23 Writing Data Incrementally Use the fwrite() function to incrementally write data to a text file The syntax for the fwrite() function is: fwrite($handle, data[, length]); The fwrite() function returns the number of bytes that were written to the file If no data was written to the file, the function returns a value of 0

Name of Book24 Locking Files To prevent multiple users from modifying a file simultaneously use the flock() function The syntax for the flock() function is: flock($handle, operation) Table 6-3 Operational constants of the flock() function

Name of Book25 Reading an Entire File Table 6-4 PHP functions that read the entire contents of a text file

Name of Book26 file_get_contents() Function Reads the entire contents of a file into a string $DailyForecast = “ San Francisco daily weather forecast : Today: Partly cloudy. Highs from the 60s to mid 70s. West winds 5 to 15 mph. Tonight: Increasing clouds. Lows in the mid 40s to lower 50s. West winds 5 to 10 mph. ”; file_put_contents(“sfweather.txt”, $DailyForecast); $SFWeather = file_get_contents(“sfweather.txt”); echo $SFWeather;

Name of Book27 readfile() Function Prints the contents of a text file along with the file size to a Web browser readfile(“sfweather.txt”);

Name of Book28 file() Function Reads the entire contents of a file into an indexed array Automatically recognizes whether the lines in a text file end in \n, \r, or \r\n $January = “48, 42, 68\n”; $January.= “48, 42, 69\n”; $January.= “49, 42, 69\n”; $January.= “49, 42, 61\n”; $January.= “49, 42, 65\n”; $January.= “49, 42, 62\n”; file_put_contents(“sfjanaverages.txt”, $January);

Name of Book29 file() Function (continued) $JanuaryTemps = file(“sfjanaverages.txt”); for ($i=0; $i<count($JanuaryTemps); ++$i) { $CurDay = explode(“, “, $JanuaryTemps[$i]); echo “ Day “. ($i + 1). “ ”; echo “High: {$CurDay[0]} ”; echo “Low: {$CurDay[1]} ”; echo “Mean: {$CurDay[2]} ”; }

Name of Book30 file() Function (continued) Figure 6-8 Output of individual lines in a text file

Name of Book31 Reading Data Incrementally Table 6-5 PHP functions that iterate through a text file The fgets() function uses the file pointer to iterate through a text file

Name of Book32 Reading Data Incrementally (continued) You must use fopen() and fclose() with the functions listed in Table 6-5 Each time you call any of the functions in Table 6-5, the file pointer automatically moves to the next line in the text file (except for fgetc() ) Each time you call the fgetc() function, the file pointer moves to the next character in the file

Name of Book33 Reading Directories Table 6-6 PHP directory functions

Name of Book34 Reading Directories (continued) To iterate through the entries in a directory, open a handle to the directory with the opendir() function Use the readdir() function to return the file and directory names from the open directory Use the closedir() function to close a directory handle

Name of Book35 Reading Directories (continued) $Dir = “C:\\PHP”; $DirOpen = opendir($Dir); while ($CurFile = readdir($DirOpen)) { echo $CurFile. “ ”; } closedir($DirOpen);

Name of Book36 scandir() Function Returns an indexed array containing the names of files and directories in the specified directory $Dir = “C:\\PHP”; $DirEntries = scandir($Dir); foreach ($DirEntries as $Entry) { echo $Entry. “ ”; }

Name of Book37 Creating Directories The mkdir() function creates a new directory To create a new directory within the current directory: Pass just the name of the directory you want to create to the mkdir() function mkdir(“bowlers”);

Name of Book38 Creating Directories (continued) To create a new directory in a location other than the current directory: Use a relative or an absolute path mkdir(“..\\tournament”); mkdir(“C:\\PHP\\utilities”);

Name of Book39 Creating Directories (continued) Figure 6-9 Warning that appears if a directory already exists

Name of Book40 Obtaining File and Directory Information Table 6-7 PHP file and directory status functions

Name of Book41 Obtaining File and Directory Information (continued) $DailyForecast = “ San Francisco daily weather forecast : Today: Partly cloudy. Highs from the 60s to mid 70s. West winds 5 to 15 mph. Tonight: Increasing clouds. Lows in the mid 40s to lower 50s. West winds 5 to 10 mph. ”; $WeatherFile = “sfweather.txt”; if (is_writable($WeatherFile)) { file_put_contents($WeatherFile, $DailyForecast); echo “ The forecast information has been saved to the $WeatherFile file. ”; } else echo “ The forecast information cannot be saved to the $WeatherFile file. ”;

Name of Book42 Obtaining File and Directory Information (continued) Table 6-8 Common file and directory information functions

Name of Book43 Obtaining File and Directory Information (continued) $Dir = “C:\\PHP”; if(is_dir($Dir)) { echo “ ”; echo “ Filename File Size File Type ”; $DirEntries = scandir($Dir); foreach ($DirEntries as $Entry) { echo “ $Entry ”. filesize($Dir. “\\”. $Entry). “ ”. filetype($Dir. “\\”. $Entry). “ ”; } echo “ ”; } else echo “ The directory does not exist. ”;

Name of Book44 Obtaining File and Directory Information (continued) Figure 6-10 Output of script with file and directory information functions

Name of Book45 Copying and Moving Files Use the copy() function to copy a file with PHP The function returns a value of true if it is successful or false if it is not The syntax for the copy() function is: copy(source, destination) For the source and destination arguments: Include just the name of a file to make a copy in the current directory, or Specify the entire path for each argument

Name of Book46 Copying and Moving Files (continued) if (file_exists(“sfweather.txt”)) { if(is_dir(“history”)) { if (copy(“sfweather.txt”, “history\\sfweather txt”)) echo “ File copied successfully. ”; else echo “ Unable to copy the file! ”; } else echo (“ The directory does not exist! ”); } else echo (“ The file does not exist! ”);

Name of Book47 Renaming Files and Directories Use the rename() function to rename a file or directory with PHP The rename() function returns a value of true if it is successful or false if it is not The syntax for the rename() function is: rename(old_name, new_name)

Name of Book48 Removing Files and Directories Use the unlink() function to delete files and the rmdir() function to delete directories Pass the name of a file to the unlink() function and the name of a directory to the rmdir() function Both functions return a value of true if successful or false if not Use the file_exists() function to determine whether a file or directory name exists before you attempt to delete it

Upload Files Form (Upload.html) Filename: Internet programming49

Upload Files Action (Upload_files.php) 0) { echo "Return Code: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; echo "Temp file: ". $_FILES["file"]["tmp_name"]. " "; if (file_exists("upload/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/". $_FILES["file"]["name"]); echo "Stored in: ". "upload/". $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> 50

$_FILES By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this: $_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload Internet programming51

Name of Book52 Summary The stream is used for accessing a resource, such as a file, that you can read from and write to A handle is a special type of variable that PHP uses to represent a resource such as a file The fopen() function opens a stream to a text file A file pointer is a special type of variable that refers to the currently selected line or character in a file

Name of Book53 Summary (continued) Use the fclose() function to ensure that the file doesn’t keep taking up space in your computer’s memory PHP supports two basic methods for writing data to text files: file_put_contents() and the fwrite() function Magic quotes automatically add backslashes to any single quote, double quote, or NULL character contained in data that a user submits to a PHP script

Name of Book54 Summary (continued) PHP includes various functions, such as the fgets() function, that allow you to use the file pointer to iterate through a text file To iterate through the entries in a directory, you open a handle to the directory with the opendir() function PHP includes various file and directory status functions, such as the file_exists() function, which determines whether a file or directory exists

Name of Book55 Summary (continued) The enctype attribute of the tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded The type="file" attribute of the tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error".