12

Click here to load reader

Chapter3C

Embed Size (px)

Citation preview

Page 1: Chapter3C

Unit 3: Files and Directories in PHP

3.1. Reading files/ Directories Files and directories have three levels of access: User, Group and Other. The three typical permissions for files and directories are:

a. Read (r)b. Write (w)c. Execute (x)

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) while the output stream writes data to a resource. In file operation, we do have the following steps or procedures:-

1. Open the file stream with the fopen() functionSyntax:- variable= open(“text file”, “mode”); where mode mean r, r+, w, w+ etc as shown in the next page.

2. Write data to or read data from the file stream• We use fread() function to read functions. We can also use fgets()

function to read files or data. It is written with two parameters like fgets($handle,$bytes)

– Reads up to $bytes of data, stops at newline or end of file (EOF)

• PHP supports two basic functions for writing data to text files: – file_put_contents() function writes or appends a text string to

a file. Its syntax for the file_put_contents() function is: file_put_contents (filename, string[, options]

– fwrite() function incrementally writes data to a text file. Its syntax for the fwrite() function is: fwrite($handle, data[, length]);

3. Close the file stream with the fclose() function:- used when finished working with a file stream to save space in memory Syntax:- fclose(file name that contains the opened files);$handle from the following example.

Example:-$handle = fopen('people.txt', 'r'); while (!feof($handle)) {

echo fgets($handle, 1024);echo '<br />';}

fclose($handle);

Files modes can be specified as one of the six options in this table.

1

Page 2: Chapter3C

Mode Purpose

r Opens the file for reading only. Places the file pointer at the beginning of the file.

r+ Opens the file for reading and writing. Places the file pointer at the beginning of the file.

w Opens the file for writing only. Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does not exist then it attempts to create a file.

w+ Opens the file for reading and writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file.

a Opens the file for writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.

a+ Opens the file for reading and writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.

Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP.

� Open a file using fopen() function.� Get the file's length using filesize() function.� Read the file's content using fread() function.� Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the web page.

<html><head><title>Reading a file using PHP</title></head><body><?php$filename = "/home/user/guest/tmp.txt";$file = fopen( $filename, "r" );if( $file == false ){ echo ( "Error in opening file" ); exit();}$filesize = filesize( $filename );$filetext = fread( $file, $filesize );

2

Page 3: Chapter3C

fclose( $file );echo ( "File size : $filesize bytes" );echo ( "<pre>$filetext</pre>" );?></body></html>

Note That:- There are two ‘shortcut’ functions that don’t require a file to be opened:• $lines = file($filename)

– Reads entire file into an array with each line a separate entry in the array.• $str = file_get_contents($filename)

– Reads entire file into a single string.

3.2. Writing a fileA new file can be written or text can be appended to an existing file using the PHP function as discus in the previous discussions. These functions require two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached. The following is the syntax to write files:-

fwrite(file we write on it, string what we write[,length of string])The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument. See the following example how open file, write in file and close files

<?php$filename = "/home/user/guest/newfile.txt";$file = fopen( $filename, "w" );if( $file == false ){ echo ( "Error in opening new file" ); exit();}fwrite( $file, "This is a simple test\n" );fclose( $file );?><html><head><title>Writing a file using PHP</title></head><body><?phpif( file_exist( $filename ) ){

3

Page 4: Chapter3C

$filesize = filesize( $filename ); $msg = "File created with name $filename "; $msg .= "containing $filesize bytes"; echo ($msg );}else{ echo ("File $filename does not exit" );}?></body></html>

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.

After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.Note that:-

The file_put_contents() function can also writes or appends a text string to a file, doesn’t need to use fopen or fclose. If no data was written to the file, the function returns a value of 0 which can determine if data was successfully written to the file. The FILE_APPEND constant appends data to any existing contents in the specified filename instead of overwriting it

Example:- This example shows costsharing payment system<html><body><h1>Coast sharing payment system</h1><?php if (isset($_GET['first_name']) && isset($_GET['last_name'])) {

$First = $_GET['first_name'];$Last = $_GET['last_name'];$New= $Last . ", " . "$First" . "\n";$x = "bowlers.txt";if (file_put_contents($x, $New, FILE_APPEND) > 0)

echo "<p>{$_GET['first_name']} {$_GET['last_name']} has been registered for the payment!</p>";

elseecho "<p>Registration error!</p>";

}else{

echo "<p>To sign up for the cost sharing system, enter your first and last name and click the Register button.</p>";

if(!empty($_GET['first_name']))echo $_GET['first_name'];

if(!$_GET['last_name'])echo $_GET['last_name'];}

4

Page 5: Chapter3C

?><form action="<?php $_PHP_SELF ?>" method="get" enctype="application/x-www-form-urlencoded"><p>First Name: <input type="text" name="first_name" size="30" /></p><p>Last Name: <input type="text" name="last_name" size="30" /></p><p><input type="submit" value="Register" /></p></form></body></html >

In general; To write files incrementally, use the fwrite() function fclose() closes a file. fgetc() reads a single character feof() determines if the end is true. fgets() reads a line of data file() reads entire file into an array

See the following examples Example 1:-

<?php $myFile = "welcome.txt";if (!($fh=fopen($myFile,'r'))) exit("Unable to open file.");while (!feof($fh)) { $x=fgetc($fh); echo $x;}fclose($fh);?>

Example 2<?php $myFile = "welcome.txt";$fh = fopen($myFile, 'r');$theData = fgets($fh);fclose($fh);echo $theData;?>

Example 3:<?php $lines = file('welcome.txt');foreach ($lines as $l_num => $line) {

5

Page 6: Chapter3C

echo "Line #{$l_num}:“ .$line.”<br/>”;}?>

Example 4:-<?php $myFile = "testFile.txt";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = "New Stuff 1\n";fwrite($fh, $stringData);$stringData = "New Stuff 2\n";fwrite($fh, $stringData);fclose($fh); ?>

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) where operations could be LOCK_EX, LOCK_NB, etc. The followings are possible file lock functions and their descriptions.

Reading an Entire File

6

Page 7: Chapter3C

Copying 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

Example:- if (file_exists(“a.txt”)) {

if(is_dir(“history”)) {if (copy(“a.txt”,“history\\b.txt”))

echo “<p>File copied successfully.</p>”;else

echo “<p>Unable to copy the file!</p>”; }

elseecho (“<p>The directory does not exist!</p>”);

} else

echo (“<p>The file does not exist!</p>”);

3.3. Create Directories Basic functions/methods that are used to open directories, read directories and close

directories are;- 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

7

Page 8: Chapter3C

There are also different functions which have different purposes. Some of them are listed below:-

Example 1:- This is used to demonstrate how gare directory contents of files are displayed.

<?php$Dir = "C:\\gare";$DirOpen = opendir($Dir);while ($CurFile = readdir($DirOpen)) {

echo $CurFile . "<br />";}closedir($DirOpen); ?>

Example 2:- The following example shows how the content of the current directory opened $handle = opendir('./');

while(false !== ($file=readdir($handle))){echo "$file<br />";}

closedir($handle);

To create directories:-

• Use the mkdir() function to create a new directory. To create a new directory pass just the name of the directory we want to create to the mkdir() function.

• Example

mkdir(“bowlers”);mkdir(“..\\tournament”);

8

Page 9: Chapter3C

mkdir(“C:\\PHP\\utilities”);• Warning will appear if directory already exists

Example:- <?php$Dir = "C:\\Wamp";if(is_dir($Dir)) {

echo "<table border='1‘ width='100%'>";echo "<tr><th>Filename</th><th>File Size</th>

<th>File Type</th></tr>";$DirEntries = scandir($Dir);foreach ($DirEntries as $Entry) {

echo "<tr><td>$Entry</td><td>" . filesize($Dir . "\\". $Entry) . "</td><td>" . filetype($Dir . "\\". $Entry) . "</td></tr>";

} echo "</table>";}else echo "<p>The directory does not exist.</p>";?>

3.4. Upload Files � Web applications allow visitors to upload files to and from their local computer. The files

that are uploaded and downloaded may be simple text files or more complex file types, such as images, documents, or spreadsheets

� Files are uploaded through an HTML form using the “post” method and enctype attribute with value of “multipart/form-data,” which instructs the browser to post multiple sections – one for regular form data and one for the file contents.

� The file input field creates a browser button for the user to navigate to the appropriate file to upload

<form method=”post” action=” ” enctype= multipart/form-data >

<input type="file" name="picture_file" />

</form>

� The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum number of bytes allowed in the uploaded file and it must appear before the file input field.

� When the form is posted, information for the uploaded file is stored in the $_FILES auto global array. The $_FILES[] array contains five elements:

a. // Contains the error code associated with the file $_FILES['picture_file']['error']

b. // Contains the temporary location of the file

$_FILES['picture_file']['tmp_name'] contents

c. // Contains the name of the original file$_FILES['picture_file']['name']

d. // Contains the size of the uploaded file in bytes9

Page 10: Chapter3C

$_FILES['picture_file']['size']

e. // Contains the type of the file

$_FILES['picture_file']['type']

Example:-The following HTM code below creates an uploaded form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

<html><body><h3>File Upload:</h3>Select a file to upload: <br /><form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data"><input type="file" name="file" size="50" /><br /><input type="submit" value="Upload File" /></form>

<?phpif( $_FILES['file']['name'] != "" ){ copy( $_FILES['file']['name'], "C:\wamp\www\Leture\Test.php" ) or die( "Could not copy file!");}else{ die("No file specified!");}?><html><head><title>Uploading Complete</title></head><body><h2>Uploaded File Info:</h2><ul><li>Sent file: <?php echo $_FILES['file']['name']; ?><li>File size: <?php echo $_FILES['file']['size']; ?> bytes<li>File type: <?php echo $_FILES['file']['type']; ?></ul></body></html></body></html>

3.5. Rename and Delete Files and Directories Use the rename() function to rename a file or directory with PHP

o This function returns a value of true if it is successful or false if it is not

10

Page 11: Chapter3C

o The syntax is: rename(old_name, new_name)

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

o Use the file_exists() function to determine whether a file or directory name exists before we attempt to delete it

3.6. File Inclusions In PHP , we can include the content of a PHP file into another PHP file before the server executes it. This is done by functions such as include() and require() function statements:-

� The include() Function:- include will only produce a warning (E_WARNING) and the script will continue

� The require() Function:- require will produce a fatal error (E_COMPILE_ERROR) and stop the script

There are also the include_once() and require_once() functions. These functions will not re-include the file if it has already been called.

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file is easier.Syntax:-

include 'filename';orrequire 'filename';

Example:- <?php include_once('header.php'); include_once($_GET['action'] . '.php'); include_once('footer.php'); ?>

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then include() function generates a warning but the script will continue execution.Example:- let we create a file menu.php with the following content.

<a href="http://www.tutorialspoint.com/index.htm">Home</a> - <a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - <a href="http://www.tutorialspoint.com/ajax">AJAX</a> -

<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />Now create as many pages as we like and include this file to create header. For example now test.php file can have following content.

<html>

11

Page 12: Chapter3C

<body><?php include("menu.php"); ?><p>This is an example to show how to include PHP file!</p></body>

</html>This will produce following result:- Home - ebXML - AJAX - PERL

The require() function on the other hand, takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

Note that:- There is no difference in require() and include() functions except handling error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

12