PHP I : Files & Directories

Follow this lesson in Ullman Chapter 11. The scripts are located in the 11 directory.

 

resource fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

 

OS File Permissions

See my Linux Fundamentals page on Permissions for a discussion of setting and viewing permissions on Linux/Unix computers.

 

File Permissions Settings in PHP

Use phpinfo() to check two things:

Is PHP running in Safe Mode?

Is the open_basedir directive set?

 

Writing to Files

Create a file pointer ($fp, or any name you choose), and use it to open, write to and close a file:

$fp = fopen(‘filename‘, ‘mode‘);
fwrite ($fp, ‘data to write‘);
fclose ($fp);

 

r
Open for reading only.
Place the file pointer at the beginning of the file.
r+
Open for reading and writing.
Place the file pointer at the beginning of the file.
w
Open for writing only.
Place the file pointer at the beginning of the file.
Truncate the file to zero length.
If the file does not exist, attempt to create it.
w+
Open for reading and writing.
Place the file pointer at the beginning of the file.
Truncate the file to zero length.
If the file does not exist, attempt to create it.
a
Open for writing only.
Place the file pointer at the end of the file.
If the file does not exist, attempt to create it.
a+
Open for reading and writing.
Place the file pointer at the end of the file.
If the file does not exist, attempt to create it.
x
Create and open for writing only.
Place the file pointer at the beginning of the file.
If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.
If the file does not exist, attempt to create it.
x+
Create and open for reading and writing.
Place the file pointer at the beginning of the file.
If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.
If the file does not exist, attempt to create it.
t
Add to any of the above.
Use in Windows only to “fix” line endings.
b
Add to any of the above (except t).
Use to force binary mode, i.e. ignore line ending differences.

 

Unix based systems use \n as the line ending character.

Windows based systems use \r\n as the line ending.

In Windows, use the text-mode translation flag (‘t’) to transparently translate \n to \r\n.

In either platform, use ‘b’ to force binary mode, which will not change your file.

To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

 

Also see file_put_contents() at
http://us2.php.net/manual/en/function.file-put-contents.php

 

Checking For Writeability

if (is_writeable(‘../somefile‘)) {
 //perform a file open here
} else {
 print “File is not writeable.”;
}

 

Locking Files

//Open the file first, then to write
//to it, use this:
flock ($fp, LOCK_EX);
// Write the data. Use \r\n on Windows.
fwrite ($fp, “$data\n”);
flock ($fp, LOCK_UN);
// Close the file.
fclose ($fp);

flock() doesn’t work on NTFS or FAT file systems.

 

Reading from Files

//This gets the file contents as an indexed array:
$my_data = file (‘../somefile‘);

//This gets the file contents as a single string:
$my_data = file_get_contents (‘../somefile‘);

 

Uploading Files

1. In the <form> tag, you must add the code:

enctype=”multipart/form-data”

so the browser knows you may ask it to pass a file.

2. You must add the hidden input:

<input type=”hidden” name=”MAX_FILE_SIZE” value=”3000″ />

3. You just add a form input:

<input type=”file” name=”my_file” />

You can use any element name you want instead of my_file; just remember to use that name consistently to access the data later.

Upon submission, the file is passed from the browser to the server in the $_FILES array, which has five elements:

name – the name of the file on the sender’s computer

type – MIME type

size – in bytes

tmp_name – the download temporary file name on the server

error – the error code

Then, you capture the temporary upload file and move it to its intended destination:

move_uploaded_file($_FILES[‘my_file‘][‘tmp_name’], ‘destination/folder/filename‘);

This is best done with error-checking:

// The acid test: can we move the uploaded file?
if (move_uploaded_file ($_FILES[‘my_file’][‘tmp_name’], “../uploads/{$_FILES[‘my_file’][‘name’]}”)) {

print ‘<p>Your file has been uploaded.</p>’;

} else { // We have a problem!

Definitely see Ullman page 319 for a complete example!

 

Also see unlink() to delete files, and copy() to move/copy files.

 

Navigation and Directory Listing: PHP 4

// Specify a directory name
$directory = ‘.’;

//Open the directory
$dp = opendir ($directory);

// List the directories first.
while ($item = readdir ($dp)) {
if((is_dir($item)) AND (substr($item,0,1) != ‘.’)){
print “$item\n”;
}
}

// Reset the pointer
rewinddir ($dp);

// List the files.
while ($item = readdir($dp)) {
if ( (is_file($item)) AND (substr ($item,0,1) != ‘.’)) {

// Get the file size.
$fs = filesize ($item);

// Get the file’s modification date.
$lm = date (‘F j, Y’, filemtime ($item));

// Print the information.
print “$item\n $fs bytes\n $lm\n”;

} // Close the if
} // Close the while

// Close the directory
closedir ($dp);

See Ullman pp. 324 ff. for an example including table formatting. It’s quite good.

 

Navigation and Directory Listing: PHP 5

// Specify a directory name
$directory = ‘.’;

$files = scandir($directory);

// List the directories first.
foreach ($files as $item) {
if((is_dir($item)) AND (substr($item,0,1) != ‘.’)){
print “$item\n”;
}
}

// Reset the pointer
rewinddir ($dp);

// List the files.
foreach ($files as $item) {
if ( (is_file($item)) AND (substr ($item,0,1) != ‘.’)) {

// Get the file size.
// Note the human_readable function!
$fs = human_readable (filesize ($item));

// Get the file’s modification date.
$lm = date (‘F j, Y’, filemtime ($item));

// Print the information.
print “$item\n $fs bytes\n $lm\n”;
}
}

See also fileperms(), fileatime() and fileowner().

 

Creating Directories

mkdir(‘directory_name‘, permissions);

mkdir(‘mysecrets’, 0777);

 

Reading Files Incrementally

// Open the file.
$fp = fopen (‘../user/passwords.txt’, ‘rb’);

// Loop through the file.
while ( $line = fgetcsv ($fp, 100, “\t”)) {

// Do something to each line, such as a test
if ( ($line[0] == $_POST[‘username’]) AND ($line[1] == crypt ($_POST[‘password’], $line[1]) ) ) {

// In this case, we’ve found a
// correct username/password combination.
$loggedin = TRUE;

// Stop looping through the file.
break;

} // End if

} // End while

fclose ($fp); // Close the file

 

To do out of class:

Review Chapter 11 of Ullman.