53
Files: Opening and Closing Files The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. Files modes can be specified as one of the six options in this table. 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.

Php files

Embed Size (px)

DESCRIPTION

php files concept

Citation preview

Page 1: Php files

Files:

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.

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

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 notexist 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 notexist 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.

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.

Check End-of-file

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

Page 2: Php files

Note: You cannot read from files opened in w, a, and x mode!

if (feof($file)) echo "End of file";

Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:

<?php$file = fopen("welcome.txt", "r") or exit("Unable to open file!");//Output a line of the file until the end is reachedwhile(!feof($file))  {  echo fgets($file). "<br>";  }fclose($file);?>

Reading a File Character by Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.

Example

The example below reads a file character by character, until the end of file is reached:

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

Reading a file

Page 3: Php files

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 );

fclose( $file );

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

</body></html>

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires 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.

Page 4: Php files

The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

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

The filesystem functions are used to access and manipulate the filesystem PHP provides you all the posible functions you may need to manipulate a file.

Installation:

The error and logging functions are part of the PHP core. There is no installation needed to use these functions.

Runtime Configuration:

Page 5: Php files

The behaviour of these functions is affected by settings in php.ini.

Name Default Changeable Changelog

allow_url_fopen "1" PHP_INI_ALLPHP_INI_ALL in PHP <= 4.3.4. PHP_INI_SYSTEM in PHP < 6. Available since PHP 4.0.4.

allow_url_include "0" PHP_INI_ALLPHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0.

user_agent NULL PHP_INI_ALL Available since PHP 4.0.3.

default_socket_timeout "60" PHP_INI_ALL Available since PHP 4.3.0.

from "" PHP_INI_ALL  

auto_detect_line_endings "0" PHP_INI_ALL Available since PHP 4.3.0.

PHP Error and Logging Constants:

PHP: indicates the earliest version of PHP that supports the constant.

You can use any of the constant while configuring your php.ini file.

Constant Description PHP

GLOB_BRACE    

GLOB_ONLYDIR    

GLOB_MARK    

GLOB_NOSORT    

GLOB_NOCHECK    

GLOB_NOESCAPE    

PATHINFO_DIRNAME    

PATHINFO_BASENAME    

PATHINFO_EXTENSION    

PATHINFO_FILENAME   5.2.0

FILE_USE_INCLUDE_PATH Search for filename in include_path 5.0.0

FILE_APPEND Append content to existing file.  

Page 6: Php files

FILE_IGNORE_NEW_LINES Strip EOL characters 5.0.0

FILE_SKIP_EMPTY_LINES Skip empty lines 5.0.0

FILE_BINARY Binary mode 6.0.0

FILE_TEXT Text mode 6.0.0

List of Functions

PHP: indicates the earliest version of PHP that supports the function.

Function Description PHP

basename() Returns filename component of path 3

chgrp() Changes file group 3

chmod() Changes file mode 3

chown() Changes file owner 3

clearstatcache() Clears file status cache 3

copy() Copies file 3

delete() Deletes file  

dirname() Returns directory name component of path 3

disk_free_space() Returns available space in directory 4.0.7

disk_total_space() Returns the total size of a directory 4.0.7

diskfreespace() Alias of disk_free_space() 4.0.7

fclose() Closes an open file pointer 3

feof() Tests for end-of-file on a file pointer 3

fflush() Flushes the output to a file 4

fgetc() Gets character from file pointer 3

fgetcsv() Gets line from file pointer and parse for CSV fields 3

fgets() Gets line from file pointer 3

fgetss() Gets line from file pointer and strip HTML tags 3

file_exists() Checks whether a file or directory exists 3

Page 7: Php files

file_get_contents() Reads entire file into a string 4.3.0

file_put_contents() Write a string to a file 5

file() Reads entire file into an array 3

fileatime() Gets last access time of file 3

filectime() Gets inode change time of file 3

filegroup() Gets file group 3

fileinode() Gets file inode 3

filemtime() Gets file modification time 3

fileowner() Gets file owner 3

fileperms() Gets file permissions 3

filesize() Gets file size 3

filetype() Gets file type 3

flock() Portable advisory file locking 3

fnmatch() Match filename against a pattern 4.0.3

fopen() Opens file or URL 3

fpassthru() Output all remaining data on a file pointer 3

fputcsv() Format line as CSV and write to file pointer 5.1.0

fputs() Alias of fwrite() 3

fread() Binary-safe file read 3

fscanf() Parses input from a file according to a format 4.0.1

fseek() Seeks on a file pointer 3

fstat() Gets information about a file using an open file pointer 4

ftell() Tells file pointer read/write position 3

ftruncate() Truncates a file to a given length 4

fwrite() Binary-safe file write 3

glob() Find pathnames matching a pattern 4.0.3

is_dir() Tells whether the filename is a directory 3

is_executable() Tells whether the filename is executable 3

Page 8: Php files

is_file() Tells whether the filename is a regular file 3

is_link() Tells whether the filename is a symbolic link 3

is_readable() Tells whether the filename is readable 3

is_uploaded_file() Tells whether the file was uploaded via HTTP POST 4.0.3

is_writable() Tells whether the filename is writable 3

is_writeable() Alias of is_writable() 3

lchgrp() Changes group ownership of symlink 5.1.2

lchown() Changes user ownership of symlink 5.1.2

link() Create a hard link 3

linkinfo() Gets information about a link 3

lstat() Gives information about a file or symbolic link 3

mkdir() Makes directory 3

move_uploaded_file() Moves an uploaded file to a new location 4.0.3

parse_ini_file() Parse a configuration file 4

pathinfo() Returns information about a file path 4.0.3

pclose() Closes process file pointer 3

popen() Opens process file pointer 3

readfile() Outputs a file 3

readlink() Returns the target of a symbolic link 3

realpath() Returns canonicalized absolute pathname 4

rename() Renames a file or directory 3

rewind() Rewind the position of a file pointer 3

rmdir() Removes directory 3

set_file_buffer() Alias of stream_set_write_buffer() 3

stat() Gives information about a file 3

symlink() Creates a symbolic link 3

tempnam() Create file with unique file name 3

tmpfile() Creates a temporary file 3

Page 9: Php files

touch() Sets access and modification time of file 3

umask() Changes the current umask 3

unlink() Deletes a file 3

List of All File functions in php

Introduction

If you were having trouble in remembering all file related functions of PHP, then don't worry, I'm publishing here a full list of all of them, so that you can easily use any of them. File system related functions were divided into 9 extensions of php whose names are shown below.

List of File system related extensions

Click on links to directly Jump on page section.

1. Direct IO,2. Directories,3. Fileinfo,4. Filesystem,5. Inotify,6. Mimetype (No functions found),7. Proctile,8. Xattr,9. And xdiff.

Filesystem functions in php

Function Name Description Syntax Other information

basename

Given a string containing the path to a file or directory, this function will return the trailing name component.

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

chgrp Changes file groupchgrp ( string $filename , mixed $group )

group - A group name or number.

chmodAttempts to change the mode of the specified file to that given in $mode.

chmod ( string $filename , int $mode )

Returns TRUE on success or FALSE on failure.

Page 10: Php files

Function Name Description Syntax Other information

chown

Attempts to change the owner of the file $filename to $user user. Only the superuser may change the owner of a file.

chown ( string $filename , mixed $user )

filename - path to the file, user - A user name or number.

clearstatcache Clears file status cacheclearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )

clear_realpath_cache - Whether to clear the realpath cache or not.

copyMakes a copy of the file $source to $dest.

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

Returns TRUE on success or FALSE on failure.

delete

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

delete ( void )

dirname

Given a string containing the path of a file or directory, this function will return the parent directory's path.

dirname ( string $path )

disk_free_space

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

disk_free_space ( string $directory )

disk_total_space

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

disk_total_space ( string $directory )

Returns the total number of bytes as a float or FALSE on failure.

diskfreespaceThis function is an alias of: disk_free_space().

fclose The file pointed to by handle is closed.

fclose ( resource $handle ) handle - The file pointer must be valid, and must

Page 11: Php files

Function Name Description Syntax Other information

point to a file successfully opened by fopen() or fsockopen().

feofTests for end-of-file on a file pointer.

feof ( resource $handle )

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

fflush

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

fflush ( resource $handle )Returns TRUE on success or FALSE on failure.

fgetcGets a character from the given file pointer.

fgetc ( resource $handle )

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

fgetcsv

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] )

handle - A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

fgets Gets a line from file pointer.fgets ( resource $handle [, int $length ] )

length - If no length is specified, it will keep reading from the stream until it reaches the end of the line.

fgetss

Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads.

fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

allowable_tags - You can use the optional third parameter to specify tags which should not be stripped.

file_existsChecks whether a file or directory exists.

file_exists ( string $filename )

Page 12: Php files

Function Name Description Syntax Other information

file_get_contents Reads entire file into a string

file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

file_put_contents

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

fileReads an entire file into an array.

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

fileatimeGets the last access time of the given file.

fileatime ( string $filename )

filectimeGets the inode change time of a file.

filectime ( string $filename )

filegroup

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

filegroup ( string $filename )

fileinode Gets the file inode. fileinode ( string $filename )

Returns the inode number of the file, or FALSE on failure.

filemtime

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

filemtime ( string $filename )

Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

fileowner Gets the file owner. fileowner ( string $filename )

Returns the user ID of the owner of the file, or FALSE on failure. The user ID is

Page 13: Php files

Function Name Description Syntax Other information

returned in numerical format, use posix_getpwuid() to resolve it to a username.

filepermsGets permissions for the given file.

fileperms ( string $filename )

Returns the permissions on the file, or FALSE on failure.

filesize Gets the size for the given file. filesize ( string $filename )

filetypeReturns the type of the given file.

filetype ( string $filename )

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.

flock Portable advisory file lockingflock ( resource $handle , int $operation [, int &$wouldblock ] )

fnmatchMatch filename against a pattern

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

fopen Opens file or URL

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

fpassthruOutput all remaining data on a file pointer

fpassthru ( resource $handle )

fputcsvFormat line as CSV and write to file pointer

fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )

fputsThis function is an alias of: fwrite().

fread Binary-safe file readfread ( resource $handle , int $length )

fscanf Parses input from a file fscanf ( resource $handle ,

Page 14: Php files

Function Name Description Syntax Other information

according to a formatstring $format [, mixed &$... ] )

fseek Seeks on a file pointerfseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )

fstatGets information about a file using an open file pointer

fstat ( resource $handle )

handle - A file system pointer resource that is typically created using fopen().

ftellReturns the position of the file pointer referenced by handle.

ftell ( resource $handle )

ftruncateTruncates a file to a given length

ftruncate ( resource $handle , int $size )

fwrite Binary-safe file writefwrite ( resource $handle , string $string [, int $length ] )

globFind pathnames matching a pattern

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

is_dirTells whether the given filename is a directory.

is_dir ( string $filename )

is_executable Tells whether the filename is executable.

is_executable ( string $filename )

is_fileTells whether the given file is a regular file.

is_file ( string $filename )

is_linkTells whether the given file is a symbolic link.

is_link ( string $filename )

is_readableTells whether a file exists and is readable.

is_readable ( string $filename )

is_uploaded_file Tells whether the file was uploaded via HTTP POST

is_uploaded_file ( string $filename )

is_writable Tells whether the filename is is_writable ( string

Page 15: Php files

Function Name Description Syntax Other information

writable $filename )

is_writeable This function is an alias of: is_writable().

lchgrpChanges group ownership of symlink

lchgrp ( string $filename , mixed $group )

lchownChanges user ownership of symlink

lchown ( string $filename , mixed $user )

link link() creates a hard link. link ( string $target , string $link )

linkinfo Gets information about a link linkinfo ( string $path )

lstatGives information about a file or symbolic link

lstat ( string $filename )

mkdirAttempts to create the directory specified by pathname.

mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

move_uploaded_fileMoves an uploaded file to a new location

move_uploaded_file ( string $filename , string $destination )

parse_ini_file Parse a configuration file

parse_ini_file ( string $filename [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_string Parse a configuration string

parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

pathinfo pathinfo() returns an pathinfo ( string $path [,

Page 16: Php files

Function Name Description Syntax Other information

associative array containing information about path.

int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pcloseCloses a file pointer to a pipe opened by popen().

pclose ( resource $handle )

Returns the termination status of the process that was run. In case of an error then -1 is returned.

popen Opens process file pointerpopen ( string $command , string $mode )

readfile Outputs a file

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

readlinkReturns the target of a symbolic link

readlink ( string $path )

realpath_cache_getGet the contents of the realpath cache.

realpath_cache_get ( void )

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

realpath_cache_sizeGet the amount of memory used by the realpath cache.

realpath_cache_size ( void )

realpathReturns canonicalized absolute pathname

realpath ( string $path )

renameAttempts to rename oldname to newname.

rename ( string $oldname , string $newname [, resource $context ] )

rewind Sets the file position indicator rewind ( resource

Page 17: Php files

Function Name Description Syntax Other information

for handle to the beginning of the file stream.

$handle )

rmdir Removes directoryrmdir ( string $dirname [, resource $context ] )

set_file_bufferThis function is an alias of: stream_set_write_buffer().

stat Gives information about a file stat ( string $filename )

symlink Creates a symbolic linksymlink ( string $target , string $link )

tempnamCreate file with unique file name

tempnam ( string $dir , string $prefix )

Returns the new temporary filename, or FALSE on failure.

tmpfile

Creates a temporary fileCreates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

tmpfile ( void )

touch Sets access and modification time of file

touch ( string $filename [, int $time = time() [, int $atime ]] )

umask Changes the current umask umask ([ int $mask ] )

unlink Deletes a fileunlink ( string $filename [, resource $context ] )

Returns TRUE on success or FALSE on failure.

Direct IO functions in php

Function Name

Description Syntax Other Information

dio_close Closes the file description given by fd dio_close(resource $fd)fd - The file descriptor returned by dio_open()

dio_fcntl The dio_fcntl() function performs the operation specified by cmd on the file

dio_fcntl ( resource $fd , cmd - can be F_SETLK, F_SETLKW, F_GETLK,

Page 18: Php files

Function Name

Description Syntax Other Information

descriptor fd. Some commands require additional arguments args to be supplied.

int $cmd [, mixed $args ] ) F_DUPFD, F_SETFL

dio_opendio_open() opens a file and returns a new file descriptor for it.

dio_open ( string $filename , int $flags [, int $mode = 0 ] )

filename - Path of the file to open.

dio_readThe function dio_read() reads and returns len bytes from file with descriptor fd.

string dio_read ( resource $fd [, int $len = 1024 ] )

len - Number of Bytes to read.

dio_seekThe function dio_seek() is used to change the file position of the given file descriptor.

dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] )

pos - The new position, Whence -Specifies how the position pos should be interpreted.

dio_statdio_stat() returns information about the given file descriptor.

dio_stat ( resource $fd )fd - The file descriptor returned by dio_open().

dio_tcsetattrdio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

dio_tcsetattr ( resource $fd , array $options )

Currently available options are 'baud' , 'bits', 'stop', 'parity'.

dio_truncate dio_truncate() truncates a file to at most offset bytes in size.

The offset in bytes. Returns TRUE on success or FALSE on failure.

dio_writedio_write() writes up to len bytes from data to file fd.

int dio_write ( resource $fd , string $data [, int $len = 0 ] )

data - The written data.

Directory functions in PHP

Function Name

Description Syntax Other Information

chdirChanges PHP's current directory to new directory.

chdir ( string $directory )

directory - The new current directory

chroot Changes the root directory of the current process to

chroot ( string $directory )

directory - The path to change the root directory to.

Page 19: Php files

Function Name

Description Syntax Other Information

directory, and changes the current working directory to "/".

dirReturn an instance of the Directory class

-object-oriented mechanism (search google)

closedir

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

closedir ([ resource $dir_handle ] )

dir_handle - The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

getcwdGets the current working directory.

getcwd ( )Returns the current working directory on success, or FALSE on failure.

opendir

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

opendir ( string $path [, resource $context ] )

path - The directory path that is to be opened

readdir

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

readdir ([ resource $dir_handle ] )

Returns the filename on success or FALSE on failure.

rewinddirResets the directory stream indicated by dir_handle to the beginning of the directory.

rewinddir ([ resource $dir_handle ] )

scandirReturns an array of files and directories from the directory.

scandir ( string $directory [, int $sorting_order = 0 [, resource $context ]] )

sorting_order - By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to non-zero, then the sort order is alphabetical in descending order.

Fileinfo functions in PHP

Page 20: Php files

Function Name Description Syntax Other Information

finfo_buffer

This function is used to get information about binary data in a string.

finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

finfo - Fileinfo resource returned by finfo_open(), $string - Content of a file to be checked,

finfo_close

This function closes the resource opened by finfo_open().

finfo_close ( resource $finfo )

finfo - Fileinfo resource returned by finfo_open().

finfo_file

This function is used to get information about a file.

finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

file_name - Name of a file to be checked.

finfo_open

This function opens a magic database and returns its resource.

finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

finfo_set_flags

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

finfo_set_flags ( resource $finfo , int $options )

Returns TRUE on success or FALSE on failure.

mime_content_typeReturns the MIME content type for a file as determined by using information from

mime_content_type ( string $filename )

filename - Path to the tested file.

Page 21: Php files

Function Name Description Syntax Other Information

the magic.mime file.

Inotify functions in PHP

Function Name Description Syntax Other Information

inotify_add_watch

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname.

inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask )

inotify_instance - Resource returned by inotify_init()

inotify_initInitialize an inotify instance for use with inotify_add_watch()

inotify_init ( void )

inotify_queue_len

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

inotify_queue_len ( resource $inotify_instance )

inotify_readRead inotify events from an inotify instance.

inotify_read ( resource $inotify_instance )

inotify_rm_watchRemove an existing watch from an inotify instance

inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor )

watch_descriptor - Watch to remove from the instance

Proctile functions in PHP

Function Name

Description Syntax Other Information

setproctitleSets the process title of the current process.

setproctitle ( string $title )

title - The title to use as the process title.

setthreadtitle Sets the thread title.setthreadtitle ( string $title )

Returns TRUE on success or FALSE on failure.

Page 22: Php files

Function Name

Description Syntax Other Information

xattr functions of php

Function Name Description Syntax Other Information

xattr_getThis function gets the value of an extended attribute of a file.

xattr_get ( string $filename , string $name [, int $flags = 0 ] )

filename - The file from which we get the attribute, name - The name of the attribute.

xattr_listThis functions gets a list of names of extended attributes of a file.

xattr_list ( string $filename [, int $flags = 0 ] )

filename - The path of the file.

xattr_removeThis function removes an extended attribute of a file.

xattr_remove ( string $filename , string $name [, int $flags = 0 ] )

xattr_setThis function sets the value of an extended attribute of a file.

xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] )

value - The value of the attribute

xattr_supported

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

xattr_supported ( string $filename [, int $flags = 0 ] )

filename - The path of the tested file.

xdiff functions in PHP

Function Name Description Syntax Other Information

xdiff_file_bdiff_size

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

xdiff_file_bdiff_size ( string $file )

file - The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Page 23: Php files

Function Name Description Syntax Other Information

xdiff_file_bdiffMake binary diff of two files

xdiff_file_bdiff ( string $old_file , string $new_file , string $dest )

dest - Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

xdiff_file_bpatchPatch a file with a binary diff

xdiff_file_bpatch ( string $file , string $patch , string $dest )

dest - Path of the resulting file, patch - The binary patch file.

xdiff_file_diff_binary Alias of xdiff_file_bdiffxdiff_file_diff_binary ( string $old_file , string $new_file , string $dest )

xdiff_file_diffMake unified diff of two files

xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = false ]] )

xdiff_file_merge3 Merge 3 files into one

xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest )

dest - Path of the resulting file, containing merged changed from both new_file1 and new_file2.

xdiff_file_patch_binaryAlias of xdiff_file_bpatch

xdiff_file_patch_binary ( string $file , string $patch , string $dest )

xdiff_file_patchPatch a file with an unified diff

xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] )

xdiff_file_rabdiff

Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_rabdiff ( string $old_file , string $new_file , string $dest )

xdiff_string_bdiff_size Returns a size of a xdiff_string_bdiff_size patch - The binary patch

Page 24: Php files

Function Name Description Syntax Other Information

result file that would be created after applying binary $patch to the original file.

( string $patch )

created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

xdiff_string_bdiffMake binary diff of two strings

xdiff_string_bdiff ( string $old_data , string $new_data )

xdiff_string_bpatchPatch a string with a binary diff

xdiff_string_bpatch ( string $str , string $patch )

xdiff_string_diff_binaryAlias of xdiff_string_bdiff

xdiff_string_bdiff ( string $old_data , string $new_data )

xdiff_string_diffMake unified diff of two strings

xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = false ]] )

xdiff_string_merge3Merge 3 strings into one

xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] )

xdiff_string_patch_binaryAlias of xdiff_string_bpatch

xdiff_string_patch_binary ( string $str , string $patch )

xdiff_string_patchPatch a string with an unified diff

xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] )

xdiff_string_rabdiff

Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_bdiff ( string $old_data , string $new_data )

Page 25: Php files

John Donne famously said, “No man is an island,” and this maxim holds true for PHP

scripts as well. So far, all the examples you’ve seen have been self-contained, with theirsource data arriving either from user input or from variables hard-wired into the programbody. In reality, though, your PHP script will need to work with data retrieved from diskfiles, SQL resultsets, XML documents, and many other data sources.PHP comes with numerous built-in functions to access these data sources and thischapter will get you started on the road to discovering them, by focusing specifically onPHP’s file system functions. With 70+ functions available, there’s an abundance of options;this chapter will give you a crash course in the most important ones, with both examplesand practical projects of reading, writing, and manipulating disk files and directories.

Reading FilesPHP’s file manipulation API is extremely flexible: it lets you read files into a string or intoan array, from the local file system or a remote URL, by lines, bytes, or characters. Thefollowing sections explain all these variants in greater detail.

Reading Local FilesThe 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 readsthe 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;?>

An alternative method of reading data from a file is PHP’s file() function, whichaccepts the name and path to a file and reads the entire file into an array, with eachelement of the array representing one line of the file. To process the file, all you need do isiterate over the array using a foreach loop. Here’s an example, which reads a file into anarray and then displays it using such a loop:<?php// read file into array$arr = file('example.txt') or die('ERROR: Cannot find file');foreach ($arr as $line) {echo $line;}?>

Reading Remote FilesBoth file_get_contents() and file() also support reading data from URLs, usingeither the HTTP or FTP protocol. Here’s an example, which reads an HTML file off theWeb into an array:<?php// read file into array$arr = file('http://www.google.com') or die('ERROR: Cannot find file');foreach ($arr as $line) {echo $line;}?>

In case of slow network links, it’s sometimes more efficient to read a remote file in

Page 26: Php files

“chunks,” to maximize the efficiency of available network bandwidth. To do this, use thefgets() function to read a specific number of bytes from a file, as in the next example:<?php// read file into array (chunks)$str = '';$fp = fopen('http://www.google.com', 'r') or die('ERROR:Cannot open file');while (!feof($fp)) {$str .= fgets($fp,512);}fclose($fp);echo $str;?>This listing introduces four new functions, so let’s take a closer look at it. First, thefopen() function: it accepts the name of the source file and an argument indicatingwhether the file is to be opened in read ('r'), write ('w'), or append ('a') mode,and then creates a pointer to the file. Next, a while loop calls the fgets() functioncontinuously in a loop to read a specific number of bytes from the file and append thesebytes to a string variable; this loop continues until the feof() function returns true,indicating that the end of the file has been reached. Once the loop has completed, thefclose() function destroys the file pointer.NOTEIn order to read remote URLs, the PHP configuration variable 'allow_url_fopen'must be set to true in the PHP configuration file php.ini. If this variable is set to false, allattempts to read remote files will fail.

Reading Specific Segments of a FileA final twist involves reading only a specific block of lines from a line—something thatcan be accomplished with a combination of PHP’s fseek() and fgets() functions.Consider the next example, which sets up a user-defined function named readBlock()and accepts three arguments: the filename, the starting line number, and the number oflines to return from the starting point:<?php// function definition// read a block of lines from a filefunction readBlock($file, $start=1, $lines=null) {// open file$fp = fopen($file, 'r') or die('ERROR: Cannot find file');// initialize counters$linesScanned = 1;$linesRead = 0;$out = '';// loop until end of filewhile (!feof($fp)) {// get each line$line = fgets($fp);// if start position is reached// append line to output variableif ($linesScanned >= $start) {$out .= $line;$linesRead++;// if max number of lines is defined and reached// break out of loopif (!is_null($linesRead) && $linesRead == ($lines)) {break;}}$linesScanned++;}

Page 27: Php files

return $out;}echo readBlock('example.txt', 3, 4);?>Within readBlock(), a loop iterates through the file line by line, until the startingline number is reached (a line counter named $linesScanned keeps track of the currentline number, incrementing by 1 on each iteration of the loop). Once the starting line isreached, it (and all subsequent lines) are read into a string variable until the specifiedmaximum number of lines are processed or until the end of the file is reached.

Writing FilesThe flip side of reading data from files is writing data to them. And PHP comes with acouple 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 thepreceding section: this function accepts a filename and path, together with the data to bewritten 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 preservethe file’s contents and simply append new data to it, add the special FILE_APPEND flag toyour 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';?>An alternative way to write data to a file is to create a file pointer with fopen(), andthen write data to the pointer using PHP’s fwrite() function. Here’s an example of thistechnique:<?php// open and lock file// write string to file// unlock and close file$data = "A fish \n out of \n water\n";$fp = fopen('output.txt', 'w') or die('ERROR: Cannot open file');flock($fp, LOCK_EX) or die ('ERROR: Cannot lock file');fwrite($fp, $data) or die ('ERROR: Cannot write file');flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file');fclose($fp);echo 'Data written to file';?>Notice the flock() function from the preceding listing: this function “locks” a file before reading or writing it, so that it cannot be accessed by another process. Doing this reduces the possibility of data corruption that might occur if two processes attempt to write different data to the same file at the same instant. The second parameter to

Page 28: Php files

flock()specifies the type of lock: LOCK_EX creates an exclusive lock for writing, LOCK_SH creates a non-exclusive lock for reading, and LOCK_UN destroys the lock.

Q: Can I read and write binary files with PHP?

A: Yes. The file_get_contents(), file_put_contents(), and file() functions all read and write data in binary format by default; this lets you use PHP with binary files without worrying that your data will get corrupted.NOTEThe directory into which you’re trying to save the file must already exist, or else PHP will generate a fatal error. You can test if a directory exists with the file_exists()function.

his 6 -1 Reading and Writing Configuration FilesNow that you know how to read and write files, let’s try creating an application thatuses the functions described in the preceding section. Assume for a second that you’redeveloping a Weblog application, and you’d like your users to be able to configure certainaspects of this application’s behavior—for example, how many posts appear on the indexpage or the e-mail address that comments are sent to. In this case, you’d probably needto build a Web-based form that allows users to input these configuration values and savesthem to a file that your application can read as needed.This next listing generates just such a Web form, allowing users to enter values fordifferent configuration values and then saving this information to a disk file. When usersrevisit the form, the data previously saved to the file is read and used to prefill the form’sfields.Here’s the code (configure.php):<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><title>Project 6-1: Reading And Writing Configuration Files</title></head><body><h2>Project 6-1: Reading And Writing Configuration Files</h2><?php// define configuration filename and path$configFile = 'config.ini';// if form not yet submitted// display formif (!isset($_POST['submit'])) {// set up array with default parameters$data = array();$data['AdminEmailAddress'] = null;$data['DefAuthor'] = null;$data['NumPosts'] = null;$data['NumComments'] = null;$data['NotifyURL'] = null;// read current configuration values// use them to pre-fill the formif (file_exists($configFile)) {$lines = file($configFile);foreach ($lines as $line) {$arr = explode('=', $line);$i = count($arr) - 1;

(continued)$data[$arr[0]] = $arr[$i];}}?><form method="post" action="configure.php">

Page 29: Php files

Administrator email address: <br /><input type="text" size="50" name="data[AdminEmailAddress]" value="<?phpecho $data['AdminEmailAddress']; ?>"/><p>Default author name: <br /><input type="text" name="data[DefAuthor]" value="<?php echo$data['DefAuthor']; ?>"/><p>Number of posts on index page: <br /><input type="text" size="4" name="data[NumPosts]" value="<?php echo$data['NumPosts']; ?>"/><p>Number of anonymous comments: <br /><input type="text" size="4" name="data[NumComments]" value="<?php echo$data['NumComments']; ?>"/><p>URL for automatic notification of new posts: <br /><input type="text" size="50" name="data[NotifyURL]" value="<?php echo$data['NotifyURL']; ?>"/><p><input type="submit" name="submit" value="Submit" /></form><?php// if form submitted// process form input} else {// read submitted data$config = $_POST['data'];// validate submitted data as necessaryif ((trim($config['NumPosts']) != '' && (int)$config['NumPosts'] <= 0) ||(trim($config['NumComments']) != '' && (int)$config['NumComments'] <= 0)) {die('ERROR: Please enter a valid number');}// open and lock configuration file for writing$fp = fopen($configFile, 'w+') or die('ERROR: Cannot open configurationfile for writing');flock($fp, LOCK_EX) or die('ERROR: Cannot lock configuration file forwriting');// write each configuration value to the fileforeach ($config as $key => $value) {if (trim($value) != '') {fwrite($fp, "$key=$value\n") or die('ERROR: Cannot write [$key] toconfiguration file');}}// close and save fileflock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file');fclose($fp);echo 'Configuration data successfully written to file.';}?></body></html>

This example illustrates a common, and practical, use of PHP’s file functions: to readand write configuration files in the context of a Web application. Figure 6-1 illustrates theWeb form generated by this script.Once the form is submitted, the data entered into it arrives in the form of an associativearray, whose keys correspond to the configuration variables in use. This data is then validatedand a file pointer is opened to the configuration file, config.ini. A foreach loop then iteratesover the array, writing the keys and values to the file pointer in key=value format, with eachkey-value pair on a separate line. The file pointer is then closed, saving the data to disk.Figure 6-1 A Web form to enter configuration data

Page 30: Php files

(continued)Here’s an example of what config.ini would look like after submitting the form inFigure 6-1:[email protected]=Charles WNumPosts=8NumComments=4If a user revisits the Web form, the script first checks if a configuration file namedconfig.ini exists in the current directory. If it does, the lines of the file are read into anarray with PHP’s file() function; a foreach loop then processes this array, splittingeach line on the equality (=) symbol and turning the resulting key-value pairs into anassociative array. This array is then used to prefill the form fields, by assigning a value toeach input field’s 'value' attribute.Figure 6-2 illustrates one such Web form, prefilled with data read from theconfiguration file.Users are, of course, free to resubmit the form with new data; as explained previously,this submission will then be used to rewrite the configuration file with new values.Figure 6-2 A Web form prefilled with data from a configuration file

Processing DirectoriesPHP also allows developers to work with directories on the file system, iterating throughdirectory contents or moving forward and backward through directory trees. Iterating througha directory is a simple matter of calling PHP’s DirectoryIterator object, as in the followingexample, 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 foundwhile($dit->valid()) {if (!$dit->isDot()) {echo $dit->getFilename() . "\n";}$dit->next();}unset($dit);?>Here, a DirectoryIterator object is initialized with a directory name, and the object’srewind() method is used to reset the internal pointer to the first entry in the directory. Awhile loop, which runs so long as a valid() entry exists, can then be used to iterate overthe directory. Individual filenames are retrieved with the getFilename() method, whilethe 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’sdirectory manipulation functions . . . as in the following listing:<?php// create directory pointer$dp = opendir('.') or die ('ERROR: Cannot open directory');// read directory contents

Page 31: Php files

// print filenames foundwhile ($file = readdir($dp)) {if ($file != '.' && $file != '..') {echo "$file \n";}}// destroy directory pointerclosedir($dp);?>Here, the opendir() function returns a pointer to the directory named in the functioncall. 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.TIPAlso consider PHP’s scandir() function, which accepts a directory name and returnsan array containing a list of the files within that directory together with their sizes. It’sthen easy to process this array with a foreach loop.In some cases, you might need to process not just the first-level directory, but alsoits subdirectories and sub-subdirectories. A recursive function, which you learned aboutin Chapter 5, is usually the best tool for this purpose: consider the next listing, whichillustrates one such function in action:<?php// function definition// print names of files in a directory// and its child directoriesfunction printDir($dir, $depthStr='+') {if (file_exists($dir)) {// create directory pointer$dp = opendir($dir) or die ('ERROR: Cannot open directory');// read directory contents// print names of files found// call itself recursively if directories foundwhile ($file = readdir($dp)) {if ($file != '.' && $file != '..') {echo "$depthStr $dir/$file \n";if (is_dir("$dir/$file")) {printDir("$dir/$file", $depthStr.'+');}}}// close directory pointerclosedir($dp);}}// print contents of directory// and all childrenif (file_exists('.')) {echo '<pre>';printDir('.');echo '<pre>';}?>

The printDir() function in this listing might appear complex, but it’s actually quitesimple. It accepts two arguments: the name of the top-level directory to use, and a “depthstring,” which indicates, via indentation, the position of a particular file or directory in thehierarchy. Using this input, the function opens a pointer to the named directory and beginsprocessing it with readdir(), printing the name of each directory or file found. In the

Page 32: Php files

event that a directory is found, the depth string is incremented by an additional characterand the printDir() function is itself recursively called to process that subdirectory. Thisprocess continues until no further files or directories remain to be processed.Figure 6-3 has an example of the output of this listing.Figure 6-3 An indented directory listing

Performing Other File and Directory OperationsIn addition to the tools you’ve seen in previous sections, PHP comes with a whole rangeof file and directory manipulation functions, which allow you to check file attributes;copy, move, and delete files; and work with file paths and extensions. Table 6-1 lists someof the important functions in this category.Checking if a File or Directory ExistsIf you try reading or appending to a file that doesn’t exist, PHP will typically generate afatal error. Ditto for attempts to access or read/write from/to a directory that doesn’t exist.To avoid these error messages, always check that the file or directory you’re attempting toaccess already exists, with PHP’s file_exists() function. The next listing illustrates itin action:Function What It Doesfile_exists() Tests if a file or directory existsfilesize() Returns the size of a file in bytesrealpath() Returns the absolute path of a filepathinfo() Returns an array of information about a file and its pathstat() Provides information on file attributes and permissionsis_readable() Tests if a file is readableis_writable() Tests if a file is writableis_executable() Tests if a file is executableis_dir() Tests if a directory entry is a directoryis_file() Tests if a directory entry is a filecopy() Copies a filerename() Renames a fileunlink() Deletes a filemkdir() Creates a new directoryrmdir() Removes a directoryinclude() / require() Reads an external file into the current PHP scriptTable 6-1 Common PHP File and Directory Functions

<?php// check fileif (file_exists('somefile.txt')) {$str = file_get_contents('somefile.txt');} else {echo 'Named file does not exist. ';}// check directoryif (file_exists('somedir')) {$files = scandir('somedir');} else {echo 'Named directory does not exist.';}?>

Calculating File Size

Page 33: Php files

To calculate the size of a file in bytes, call the filesize() function with the filenameas argument:<?php// get file size// output: 'File is 1327 bytes.'if (file_exists('example.txt')) {echo 'File is ' . filesize('example.txt') . ' bytes.';} else {echo 'Named file does not exist. ';}?>

Finding the Absolute File PathTo retrieve the absolute file system path to a file, use the realpath() function, as in thenext listing:<?php// get file path// output: 'File path: /usr/local/apache/htdocs/// /php-book/ch06/listings/example.txt'if (file_exists('example.txt')) {echo 'File path: ' . realpath('example.txt');} else {echo 'Named file does not exist. ';}?>

Q: Are PHP’s file functions case-sensitive with respect to filenames?

A: It depends on the underlying file system. Windows is case-insensitive with respectto filenames, so PHP’s file functions are case-insensitive too. However, filenameson *NIX systems are case-sensitive, and so PHP’s file functions are case-sensitivetoo on these systems. Thus, given the file eXAMple.txt, the statement <?php file_exists('example.txt'); ?> might return false on a *NIX system but true on aWindows system.You can also use the pathinfo() function, which returns an array containing thefile’s path, name, and extension. Here’s an example:<?php// get file path info as arrayif (file_exists('example.txt')) {print_r(pathinfo('example.txt'));} else {echo 'Named file does not exist. ';}?>

Retrieving File AttributesYou can obtain detailed information on a particular file, including its ownership,permissions, and modification and access times, with PHP’s stat() function, whichreturns this information as an associative array. Here’s an example:<?php// get file informationif (file_exists('example.txt')) {print_r(stat('example.txt'));} else {echo 'Named file does not exist. ';}?>You can check if a file is readable, writable or executable with the is_readable(),is_writable(), and is_executable() functions. The following example illustratestheir usage:

Page 34: Php files

<?php// get file information// output: 'File is: readable writable'if (file_exists('example.txt')) {echo 'File is: ';// check for readable bitif (is_readable('example.txt')) {echo ' readable ';}// check for writable bitif (is_writable('example.txt')) {echo ' writable ';}// check for executable bitif (is_executable('example.txt')) {echo ' executable ';}} else {echo 'Named file does not exist. ';}?>The is_dir() function returns true if the argument passed to it is a directory, whilethe is_file() function returns true if the argument passed to it is a file. Here’s anexample:<?php// test if file or directoryif (file_exists('example.txt')) {if (is_file('example.txt')) {echo 'It\'s a file.';}if (is_dir('example.txt')) {echo 'It\'s a directory.';}} else {echo 'ERROR: File does not exist.';}?>

Creating DirectoriesTo create a new, empty directory, call the mkdir() function with the path and name of thedirectory to be created:<?phpif (!file_exists('mydir')) {if (mkdir('mydir')) {echo 'Directory successfully created.';} else {echo 'ERROR: Directory could not be created.';}} else {echo 'ERROR: Directory already exists.';}?>

Copying FilesYou can copy a file from one location to another by calling PHP’s copy() function withthe file’s source and destination paths as arguments. Here’s an example:<?php// copy fileif (file_exists('example.txt')) {if (copy('example.txt', 'example.new.txt')) {echo 'File successfully copied.';

Page 35: Php files

} else {echo 'ERROR: File could not be copied.';}} else {echo 'ERROR: File does not exist.';}?>It’s important to note that if the destination file already exists, the copy() functionwill overwrite it.Renaming Files or DirectoriesTo rename or move a file (or directory), call PHP’s rename() function with the old andnew path names as arguments. Here’s an example that renames a file and a directory,moving the file to a different location in the process:<?php// rename/move fileif (file_exists('example.txt')) {if (rename('example.txt', '../example.new.txt')) {echo 'File successfully renamed.';} else {echo 'ERROR: File could not be renamed.';}} else {echo 'ERROR: File does not exist.';}

// rename directoryif (file_exists('mydir')) {if (rename('mydir', 'myotherdir')) {echo 'Directory successfully renamed.';} else {echo 'ERROR: Directory could not be renamed.';}} else {echo 'ERROR: Directory does not exist.';}?>As with copy(), if the destination file already exists, the rename() function willoverwrite it.CAUTIONPHP will only allow you to copy, delete, rename, create, and otherwise manipulate a fileor directory if the user "owning" the PHP script has the privileges necessary to performthe task.

Removing Files or DirectoriesTo remove a file, pass the filename and path to PHP’s unlink() function, as in thefollowing example:<?php// delete fileif (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

Page 36: Php files

reverse of the mkdir() function. If the directory isn’t empty, though, it’s necessary tofirst 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 isusually more efficient—here’s an example, which demonstrates how to remove a directoryand all its children:<?php// function definition// remove all files in a directoryfunction 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 foundwhile ($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 directoryclosedir($dp);if (rmdir($dir)) {return true;} else {return false;}}}// delete directory and all childrenif (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.';}?>Here, the removeDir() function is a recursive function that accepts one inputargument: the name of the top-level directory to remove. The function begins by creatinga pointer to the directory with opendir() and then iterating over the directory’s contentswith a while loop—you’ve seen this technique in a previous section of this chapter.For each directory entry found, the is_file() and is_dir() methods are used todetermine if the entry is a file or a sub-directory; if the former, the unlink() function isused to delete the file and if the latter, the removeDir() function is called recursivelyto again process the subdirectory’s contents. This process continues until no files orsubdirectories are left; at this point, the top-level directory is empty and can be removedwith a quick rmdir().

Page 37: Php files

Reading and Evaluating External FilesTo 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 astandard header, footer, or copyright notice across all the pages of a Web site. Here’s anexample:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><title></title></head><body><?php require('header.php'); ?><p/>This is the page body.<p/><?php include('footer.php'); ?></body></html>Here, the script reads two external files, header.php and footer.php, and placesthe contents of these files at the location of the include() or require() call. It’simportant to note that any PHP code to be evaluated within the files included in thismanner must be enclosed within <?php ... ?> tags.

Q: What is the difference between include() and require()?

A: 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.