PHP programming - File Functions
Frank Yap

File function examples are shown in this section.
 
Resources
 
Lab Exercises
Exercise 1: File path functions

basename() - Returns the trailing name component.
If the name component ends in suffix this will also be cut off.

string basename ( string $path [, string $suffix ] )

echo "1) ".basename("/etc/sudoers.d")."<br>"; 
echo "2) ".basename("/etc/sudoers.d", ".d")."<br>"; 
echo "3) ".basename("/etc/passwd")."<br>"; 
echo "4) ".basename("/etc/")."<br>"; 
echo "5) ".basename(".")."<br>"; 
echo "6) ".basename("/")."<br>";
Output ---

1) sudoers.d
2) sudoers
3) passwd
4) etc
5) .
6)

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

dirname() - Returns the path of the parent directory.
If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.

echo "1) " . dirname("/etc/passwd") . "<br>";   // 1) /etc 
echo "2) " . dirname("/etc/") . "<br>"; // 2) / (or \ on Windows) 
echo "3) " . dirname(".") . "<br>"; // 3) .
Output ---

1) /etc
2) /
3) .

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

pathinfo() - Returns information about a file path.
If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php'); 
 
echo $path_parts['dirname'], "<br>"; 
echo $path_parts['basename'], "<br>"; 
echo $path_parts['extension'], "<br>"; 
echo $path_parts['filename'], "<br>"; // since PHP 5.2.0
Output ---

/www/htdocs/inc
lib.inc.php
php
lib.inc

pathinfo() example showing difference between null and no extension

$path_parts = pathinfo('/path/emptyextension.');    // empty extension 
var_dump($path_parts['extension']); 
 
$path_parts = pathinfo('/path/noextension'); // no extension 
if (isset ($path_parts['extension'])) { // avoid warning display 
var_dump($path_parts['extension']); 
}
Output ---

string(0) ""

If there is no extension, var_dump() will output a notice followed by NULL.
Notice: Undefined index: extension in C:\xampp\htdocs\phplab\phpLab9.php on line 215
NULL
 
Exercise 2: File I/O functions

 
copy() - Copies files.
Makes a copy of the file source to dest.
If you wish to move a file, use the rename() function.

bool copy ( string $source , string $dest [, resource $context ] )

$file = 'example.txt'; 
$newfile = 'example.txt.bak'; 
 
if (!copy($file, $newfile)) { 
echo "failed to copy $file... 
"; 
}


unlink() - Deletes a file.

bool unlink ( string $filename [, resource $context ] )

unlink('example.txt.bak');


fopen() - Opens file or URL.
Returns a file pointer resource (handle) on success, or FALSE on error.
For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )


A list of possible modes for fopen() using mode
mode Description
'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 and 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 and 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. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.


Examples

$handle = fopen("/home/rasmus/file.txt", "r"); 
$handle = fopen("/home/rasmus/file.gif", "wb"); 
$handle = fopen("http://www.example.com/", "r"); 
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
 

fread() - fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:
. length bytes have been read
. EOF (end of file) is reached
. a packet becomes available or the socket timeout occurs (for network streams)
. if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

string fread ( resource $handle , int $length )


A simple fread() example

// get contents of a file into a string 
$filename = "/usr/local/something.txt"; 
$handle = fopen($filename, "r"); 
$contents = fread($handle, filesize($filename)); 
fclose($handle);

 
Binary fread() example

$filename = "c:\files\somepic.gif"; 
$handle = fopen($filename, "rb"); 
$contents = fread($handle, filesize($filename)); 
fclose($handle);

 
fwrite() - fwrite() writes the contents of string to the file stream pointed to by handle.
fwrite() returns the number of bytes written, or FALSE on error.
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

int fwrite ( resource $handle , string $string [, int $length ] )


Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

function fwrite_stream($fp, $string) { 
for ($written = 0; $written < strlen($string); $written += $fwrite) { 
$fwrite = fwrite($fp, substr($string, $written)); 
if ($fwrite === false) { 
return $written; 


return $written; 
}

If writing twice to the file pointer, then the data will be appended to the end of the file content:

$fp = fopen('data.txt', 'w'); 
fwrite($fp, '1'); 
fwrite($fp, '23'); 
fclose($fp); 
 
// the content of 'data.txt' is now 123 and not 23!

 
A simple fwrite() example

$filename = 'test.txt'; 
$somecontent = "Add this to the file 
"; 
 
// Let's make sure the file exists and is writable first. 
if (is_writable($filename)) { 
 
// In our example we're opening $filename in append mode. 
// The file pointer is at the bottom of the file hence 
// that's where $somecontent will go when we fwrite() it. 
if (!$handle = fopen($filename, 'a')) { 
echo "Cannot open file ($filename)"; 
exit; 

 
// Write $somecontent to our opened file. 
if (fwrite($handle, $somecontent) === FALSE) { 
echo "Cannot write to file ($filename)"; 
exit; 

 
echo "Success, wrote ($somecontent) to file ($filename)"; 
 
fclose($handle); 
 
} else { 
echo "The file $filename is not writable"; 
}

 
fclose() - Closes an open file pointer.

$handle = fopen('somefile.txt', 'r'); 
 
fclose($handle);

 
fflush() - This function forces a write of all buffered output to the resource pointed to by the file handle.

$filename = 'bar.txt'; 
 
$file = fopen($filename, 'r+'); 
rewind($file); 
fwrite($file, 'Foo'); 
fflush($file); 
ftruncate($file, ftell($file)); 
fclose($file);

file() - Reads entire file into an array.
Each element of the array corresponds to a line in the file, with the newline still attached.
Upon failure, file() returns FALSE.

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

The optional parameter flags can be one, or more, of the following constants:

    FILE_USE_INCLUDE_PATH 
        Search for the file in the include_path. 
    FILE_IGNORE_NEW_LINES 
        Do not add newline at the end of each array element 
    FILE_SKIP_EMPTY_LINES 
        Skip empty lines 
// Get a file into an array.  In this example we'll go through HTTP to get 
// the HTML source of a URL. 
$lines = file('http://www.example.com/'); 
 
// Loop through our array, show HTML source as HTML source; and line numbers too. 
foreach ($lines as $line_num => $line) { 
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br /> 
"; 

 
// Another example, let's get a web page into a string. See also file_get_contents(). 
$html = implode('', file('http://www.example.com/')); 
 
// Using the optional flags parameter since PHP 5 
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 
String files

file_get_contents() - Reads entire file into a string.
This function is identical to calling fopen(), fread() and fclose() successively to read data to a string.
The function returns the read data or FALSE on failure.
The === operator should be used for testing the return value of this function.
http://php.net/manual/en/function.file-get-contents.php


file_put_contents() - Write a string to a file.
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
This function returns the number of bytes that were written to the file, or FALSE on failure.
The === operator should be used for testing the return value of this function.
http://php.net/manual/en/function.file-put-contents.php


Exercise 3: File search functions

glob() - The glob() function searches for all the pathnames matching pattern.

array glob ( string $pattern [, int $flags = 0 ] )

The optional parameter flags can be one, or more, of the following constants:

    GLOB_MARK - Adds a slash to each directory returned 
    GLOB_NOSORT - Return files as they appear in the directory (no sorting) 
    GLOB_NOCHECK - Return the search pattern if no files matching it were found 
    GLOB_NOESCAPE - Backslashes do not quote metacharacters 
    GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' 
    GLOB_ONLYDIR - Return only directory entries which match the pattern 
    GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored. 
$imgDir = "resources/images"; 
$str = "$imgDir/{*.jpg,*.jpeg,*.gif,*.png,*.JPG,*.JPEG,*.GIF,*.PNG}"; 
 
$pictures = glob($str, GLOB_BRACE); 
$files = count($pictures); 
 
$begin = 0; 
$n = $files; 
$list = ""; 
for ($i = $begin; $i < $n; $i++) { 
if ($i == 0) 
$list = $list . $pictures[$i]; 
else 
$list = $list . "," . $pictures[$i]; 
}
 
Homework Exercise

Start XAMPP Apache server.

Take an image file of size at least 100K bytes.
Make a copy of the file with a different name by using the file functions. Do not use the copy() function.
Use fopen(), fread(), fwrite(), and fclose() functions.
Read file in chunks no larger than 10K bytes.

After copied verify that the copying was correct by comparing the images and examining the total bytes of the two files.

Submit the code. Do not submit image files.