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.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
CHAPTER 3 MORE ON FORM HANDLING INCLUDING MULTIPLE FILES WRITING FUNCTIONS.
PHP and the Web: Session : 4. Predefined variables PHP provides a large number of predefined global variables to any script which it runs also called.
Objectives Using functions to organize PHP code
Lists Introduction to Computing Science and Programming I.
Chapter 6 Working with Files and Directories PHP Programming with MySQL.
IS 1181 IS 118 Introduction to Development Tools Chapter 5 Reusing Code.
Guide To UNIX Using Linux Third Edition
File/Directory manipulation. Opening a File To read from a file, must use a file handle. –by convention, all caps open a file (for reading): –open FILE,
Overview of JSP Technology. The need of JSP With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response.
CS0007: Introduction to Computer Programming File IO and Recursion.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Intermediate PHP (2) File Input/Output & User Defined Functions.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
Lab Assignment 7 | Web Forms and Manipulating Strings Interactive Features Added In this assignment you will continue the design and implementation of.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Lesson 7-Creating and Changing Directories. Overview Using directories to create order. Managing files in directories. Using pathnames to manage files.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Week 9 PHP Cookies and Session Introduction to JavaScript.
PHP INCLUDES FOR MODULARIZATION CIT 230 – WEB FRONT-END DEVELOPMENT.
PHP Controlling Program Flow Mohammed M. Hassoun 2012.
File Systems Long-term Information Storage Store large amounts of information Information must survive the termination of the process using it Multiple.
Interacting with a UNIX computer: Navigating through the directory tree.
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
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
UNIX Commands. Why UNIX Commands Are Noninteractive Command may take input from the output of another command (filters). May be scheduled to run at specific.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
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
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.
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.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
>> PHP: Insert Query & Form Processing. Insert Query Step 1: Define Form Variables Step 2: Make DB Connection Step 3: Error Handling Step 4: Define the.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
PHP Error Handling Section :I Source: 1.
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 and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
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])
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
NMD202 Web Scripting Week2. Web site
Learning basic Unix command It 325 operating system.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
15 – PHP(5) Informatics Department Parahyangan Catholic University.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
JavaScript and Ajax Week 10 Web site:
CSE 154 LECTURE 16: FILE I/O; FUNCTIONS. Query strings and parameters URL?name=value&name=value...
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Lecture 16: File I/O; Functions
Play Framework: Introduction
Arrays and files BIS1523 – Lecture 15.
Topics Introduction to File Input and Output
<?php require("header.htm"); ?>
Topics Introduction to File Input and Output
Topics Introduction to File Input and Output
Presentation transcript:

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 an array, from the local file system or a remote URL, by lines, bytes, or characters. The following sections explain all these variants in greater detail. Reading Local Files The easiest way to read the contents of a disk file in PHP is with the file_get_contents() function. This function accepts the name and path to a disk file, and reads the entire file into a string variable in one fell swoop. Here’s an example: <?php // read file into string $str = file_get_contents('example.txt') or die('ERROR: Cannot find file'); echo $str; ?>

Writing Files The flip side of reading data from files is writing data to them. And PHP comes with a couple of different ways to do this as well. The first is the file_put_contents() function, a close cousin of the file_get_contents() function you read about in the preceding section: this function accepts a filename and path, together with the data to be written to the file, and then writes the latter to the former. Here’s an example: <?php // write string to file $data = "A fish \n out of \n water\n"; file_put_contents('output.txt', $data) or die('ERROR: Cannot write file'); echo 'Data written to file'; ?>

If the file specified in the call to file_put_contents() already exists on disk, file_put_contents() will overwrite it by default. If, instead, you’d prefer to preserve the file’s contents and simply append new data to it, add the special FILE_APPEND flag to your file_put_contents() function call as a third argument. Here’s an example: <?php // write string to file $data = "A fish \n out of \n water\n"; file_put_contents('output.txt', $data, FILE_APPEND) or die('ERROR: Cannot write file'); echo 'Data written to file'; ?>

Processing Directories PHP also allows developers to work with directories on the file system, iterating through directory contents or moving forward and backward through directory trees. Iterating through a directory is a simple matter of calling PHP’s DirectoryIterator object, as in the following example, which uses the DirectoryIterator to read a directory and list each file within it: <?php // initialize iterator with name of // directory to process $dit = new DirectoryIterator('.'); // loop over directory // print names of files found while($dit->valid()) { if (!$dit->isDot()) { echo $dit->getFilename(). "\n"; } $dit->next(); } unset($dit); //To destroy the variable ?>

Here, a DirectoryIterator object is initialized with a directory name, and the object’s rewind() method is used to reset the internal pointer to the first entry in the directory. A while loop, which runs so long as a valid() entry exists, can then be used to iterate over the directory. Individual filenames are retrieved with the getFilename() method, while the isDot() method can be used to filter out the entries for the current (. ) and parent (.. ) directories. The next() method moves the internal pointer forward to the next entry. You can also accomplish the same task with a while loop and some of PHP’s directory manipulation functions... as in the following listing: <?php // create directory pointer $dp = opendir('.') or die ('ERROR: Cannot open directory'); // read directory contents // print filenames found while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { echo "$file \n"; }}// destroy directory pointer closedir($dp); ?>

Here, the opendir() function returns a pointer to the directory named in the function call. This pointer is then used by the readdir() function to iterate over the directory, returning a single entry each time it is invoked. It’s then easy to filter out the and directories, and print the names of the remaining entries. Once done, the closedir() function closes the file pointer. Creating Directories To create a new, empty directory, call the mkdir() function with the path and name of the directory to be created: <?php if (!file_exists('mydir')) { if (mkdir('mydir')) { echo 'Directory successfully created.'; } else { echo 'ERROR: Directory could not be created.'; }} else {echo 'ERROR: Directory already exists.';} ?>

Reading and Evaluating External Files To read and evaluate external files from within your PHP script, use PHP’s include() or require() function. A very common application of these functions is to include a standard header, footer, or copyright notice across all the pages of a Web site. Here’s an Example: This is the page body. Here, the script reads two external files, header.php and footer.php, and places the contents of these files at the location of the include() or require() call. It’s important to note that any PHP code to be evaluated within the files included in this manner must be enclosed within tags.

What is the difference between include() and require()? Answer: Fairly simple: a missing include() will generate a warning but allow script execution to continue, whereas a missing require() will generate a fatal error that halts script execution. Removing Files or Directories To remove a file, pass the filename and path to PHP’s unlink() function, as in the following example:

<?php // delete file if (file_exists('dummy.txt')) { if (unlink('dummy.txt')) { echo 'File successfully removed.'; } else { echo 'ERROR: File could not be removed.'; } } else { echo 'ERROR: File does not exist.'; } ?>

To remove an empty directory, PHP offers the rmdir() function, which does the reverse of the mkdir() function. If the directory isn’t empty, though, it’s necessary to first remove all its contents (including all subdirectories) and only then call the rmdir() function to remove the directory. You can do this manually, but a recursive function is usually more efficient—here’s an example, which demonstrates how to remove a directory and all its children: <?php // function definition // remove all files in a directory function removeDir($dir) { if (file_exists($dir)) { // create directory pointer $dp = opendir($dir) or die ('ERROR: Cannot open directory');

// read directory contents // delete files found // call itself recursively if directories found while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { if (is_file("$dir/$file")) { unlink("$dir/$file"); } else if (is_dir("$dir/$file")) { removeDir("$dir/$file"); }

// close directory pointer // remove now-empty directory closedir($dp); if (rmdir($dir)) { return true; } else { return false;}}} // delete directory and all children if (file_exists('mydir')) { if (removeDir('mydir')) { echo 'Directory successfully removed.'; } else { echo 'ERROR: Directory could not be removed.'; }} else { echo 'ERROR: Directory does not exist.';}?>

Thank You