Files PHP

These functions manipulate or return information about files. Many of them are wrappers for the commands you execute in a UNIX or Windows command shell. When the functions in this section call for a filename or a directory, you may name a file in the same directory as the script itself. You may also use a full or relative path. The . and .. directories are valid in both UNIX and Windows. You may also specify drive letters on a Windows machine. Backslashes can delimit directories and filenames when running under Windows, but forward slashes are interpreted correctly, so you stick with them.

boolean chdir(string directory)
When a PHP script begins to execute, its default path is the path to the script itself. That is, if the fully qualified path to the script were /users/leon/ public_html/somescript.php, then all relative paths would work off /users/leon/public_html/. You may change this default path with the chdir function. It returns TRUE if the change was made, FALSE if the script was unable to change
directories.

<?
if(chdir("/tmp"))
{
print("current directory is /tmp");
}
else
{
print("unable to change to /tmp");
}
?>

boolean chgrp(string filename, string group)
The chgrp function invokes the UNIX idea of changing the group to which a file belongs. If successful, TRUE is returned. If the group cannot be changed, FALSE is returned. Under Windows this function always returns TRUE and leaves the file unchanged. Two similar functions are chmod and chown. If you want to find the group to which a file is currently assigned, use the filegroup function.You may wish to refer to the UNIX man page for the shell command of the same name.

<?
if(chgrp("log.txt", "editors"))
{
print("log.txt changed to editors group");
}
else
{
print("log.txt not changed to editors group");
}
?>

boolean chmod(string filename, integer mode)
The chmod function sets the UNIX permissions for the given file based on the mode supplied. The mode is interpreted like the UNIX shell command, except that it is not converted to octal. Unless prefixed with a 0, mode is treated as a decimal number.

Under UNIX, three octal numbers specify access privileges for owner, group, and others, respectively. The modes may be added in order to combine privileges. For example, to make a file readable and executable. You also may wish to refer to the man page for chmod on your UNIX system.

Under Windows, chmod has limited use. The modes described in Tableare defined by Microsoft. They may be combined with the bitwise-or (|), but in practice only write permission has any meaning. All files in Windows are readable and the file extension determines whether the file will execute.

File-Modes

Windows-File-Modes

This function is part of a group of three functions that change similar information about files. The other two are chgrp and chown. The fileperms function will tell you the file's current modes.

<?
/*
** allow everyone to read and write to file
** when running PHP under UNIX
*/
if(chmod("data.txt", 0666))
{
print("mode change successful");
}
else
{
print("mode change unsuccessful");
}
?>

boolean chown(string filename, string user)
The owner of the named file is changed by the chown function. If successful, TRUE is returned. Otherwise the function returns FALSE. Under Windows this function does nothing and always returns TRUE. This function is similar to chgrp and chmod. If you need to know the current owner of a file, use the fileowner function.

<?
/*
** change owner to leon
*/
if(chown("data.txt","leon"))
{
print("owner changed");
}
else
{
print("couldn't change owner");
}
?>

closedir(integer directory_handle)

The closedir function closes a directory after it has been opened with the opendir function. PHP will close a directory connection for you when the script ends, so use of this function is not strictly necessary.

closedir(integer directory_handle)

boolean copy(string source, string destination)
The copy function copies a file specified by the source argument into the file specified by the destination argument. This results in two separate and identical files. A similar function is link, which is described below.

<?
if(copy("data.txt", "/tmp/data.txt"))
{
print("data.txt copied to /tmp");
}
else
{
print("data.txt could not be copied");
}
?>

float diskfreespace(string path)
The diskfreespace function returns the number of free bytes for the given path.

<?
print(diskfreespace("/")); print(" bytes free");
?>

Object dir(string directory)
The dir function creates a directory object to be used as an alternative to the group of functions that includes opendir and closedir. The returned object has two properties: handle and path. The handle property can be used with other directory functions such as readdir as if it were created with opendir. The path property is the string used to create the directory object. The object has three methods: read, rewind, and close. These behave exactly like readdir, rewinddir, and closedir.

boolean fclose(integer file_handle)
The fclose function closes an open file. When a file is opened, you are given an integer that represents a file handle. This file handle is used to close the file when you are finished using it. The functions used to open files are: fopen and fsockopen. To close a pipe, use pclose.

<?
// open file for reading
$myFile = fopen("data.txt","r");
// make sure the open was successful
if(!($myFile))
{
print("file could not be opened");
exit;
}
while(!feof($myFile))
{
// read a line from the file
$myLine = fgets($myFile, 255);
print("$myLine <BR>n");
}
// close the file
fclose($myFile);
?>

boolean feof(integer file_handle)
As you read from a file, PHP keeps a pointer to the last place in the file you read. The feof function returns TRUE if you are at the end of the file. It is most often used in the conditional part of a while loop where a file is being read from start to finish. See the description of fclose, above, for an example of use. If you need to know the exact position you are reading from, use the ftell function.

string fgetc(integer file_handle)
The fgetc function returns a single character from a file. It expects a file handle as returned by fopen, fsockopen, or popen. Some other functions for reading from a file are: fgetcsv, fgets, fgetss, fread, gzgetc.

<?
// open file and print each character
if($myFile = fopen("data.txt", "r"))
{
while(!feof($myFile))
{
$myCharacter = fgetc($myFile);
print($myCharacter);
}
fclose($myFile);
}
?>

array fgetcsv(integer file_handle, integer length, stringseparator)
The fgetcsv function is used for reading comma-separated data from a file. It requires a valid file handle as returned by fopen, fsockopen, or popen. It also requires a maximum line length. The optional separator argument specifies the character to separate fields. If left out, a comma is used. Fields may be surrounded by double quotes, which allows embedding of commas and line breaks in fields.

fgetcsv
array fgetcsv(integer file_handle, integer length, stringseparator)

array fgetcsv(integer file_handle, integer length, stringseparator)

string fgets(integer file_handle, integer length)
The fgets function returns a string it reads from a file specified by the file handle, which must have been created with fopen, fsockopen, or popen. It will attempt to read as many characters as specified by the length argument less one. A linebreak character is treated as a stopping point as is the end of the file. It will be included in the returned string. Some other functions for reading from a file are: fgetc, fgetcsv, fgetss, fread,gzgets.

<?
// open file and print each line
if($myFile = fopen("data.txt", "r"))
{
while(!feof($myFile))
$myLine = fgets($myFile, 255);
print($myLine);
}
fclose($myFile);
}
?>

string fgetss(integer file_handle, integer length, string ignore)
The fgetss function is in all respects identical to fgets except that it attempts to strip any HTML or PHP code before returning a string. The optional ignore argument specifies tags that are allowed to pass through unchanged. Note that if you wish to ignore a tag, you need only specify theopening form. Some other functions for reading from a file are: fgetc, fgetcsv, fgetss, fread, gzgets. If you wish to preserve HTML butprevent it from being interpreted, you can use the htmlentities function.

<?
// open file and print each line,
//stripping HTML except for anchor tags
if($myFile = fopen("index.html", "r"))
{
while(!feof($myFile))
{
$myLine = fgetss($myFile, 1024, "<A>);
print($myLine);
}
fclose($myFile);
}
?>

array file(string filename)
The file function returns an entire file as an array. Each line of the file is a separate element of the array, starting at zero. If it would be more convenient to work with the file as one string, use the implode function, as I have in the following example. If you are planning on sending a file directly to the browser, use readfile instead.

<?
// open file
$myFile = file("data.txt");
//fold array elements into one string
$myFile = implode($myFile, "");
//print entire file
print($myFile);
?>

boolean file_exists(string filename)
The file_exists function returns TRUE if the specified file exists and FALSE if it does not. This function is a nice way to avoid errors with the other file functions. The example below tests that a file exists before trying to send it to the browser.

<?
$filename = "data.txt";
//if the file exists, print it
if(file_exists($filename))
{
readfile($filename);
}
else
{
print("'$filename' does not exist");
}
?>

integer fileatime(string filename)
The fileatime function returns the last access time for a file in standard timestamp format, the number of seconds since January 1, 1970. False is returned if there is an error. A file is considered accessed if it is created, written, or read. Unlike some other filerelated functions, fileatime operates identically on Windows and UNIX. Two other functions for getting timestamps associated with files are filectime and
filemtime.

<?
$LastAccess = fileatime("data.txt");
print("Last access was ");
print(date("l F d, Y", $LastAccess));
?>

integer filectime(string filename)
When running on UNIX, the filectime function returns the last time a file was changed in standard timestamp format, the number of seconds since January 1, 1970. A file is considered changed if it is created or written to or its permissions have been changed. When running on Windows, filectime returns the time the file was created. If an error occurs, FALSE is returned.

Two other functions for getting timestamps associated with files are fileatime and filemtime.

<?
$LastChange = filectime("data.txt");
print("Last change was ");
print(date("l F d, Y", $LastChange));
?>

integer filegroup(string filename)
The filegroup function returns the group identifier for the given file, or FALSE when there is an error. This function always returns FALSE under Windows. Other functions that return information about a file are file-inode, fileowner, and fileperms. To change a file's group, use chgrp.

<?
print(filegroup("data.txt"));
?>

integer fileinode(string filename)
The fileinode function returns the inode of the given file, or FALSE on error. This function always returns FALSE under Windows. Similar functions are filegroup,
fileowner, and fileperms.
<?
print(fileinode(data.txt));
?>

integer filemtime(string filename)

The filemtime function returns the last time a file was modified in standard timestamp format, the number of seconds since January 1, 1970. FALSE is returned if there is an error. A file is considered modified when it is created or its contents change. Operation of this function is identical under any operating system. There are two other functions related to timestamps on files: fileatime and filectime.

<?
$LastMod = filemtime("data.txt");
print("Last modification was ");
print(date("l F d, Y", $LastMod));
?>

integer fileowner(string filename)
The fileowner function returns the user identifier of the owner, or false if there is an error. This function always returns FALSE under Windows. If you need to change the owner of a file, use the chown function. Similar functions for getting information about a file are filegroup, fileinode and fileperms.

<?
print(fileowner("data.txt"));
?>

integer fileperms(string filename)
The fileperms function returns the permission number for the given file, or false when there is an error. If you are using UNIX, you may wish to refer to the man page for the stat system function. You may be surprised to find that printing this number in octal, as is customary, produces six digits. The first three give you information about the file that don't actually refer to read/write/execute permissions. You may wish to filter that information out, as I have in the example, by performing a logical AND operation. If you need to change the mode of a file, use the chmod function.

<?
printf("%o", (fileperms("data.txt") & 0777));
?>

integer filesize(string filename)
The filesize function returns the size of the given file in bytes.

<?
print(filesize("data.txt"));
?>

string filetype(string filename)

The filetype function returns the type of the given file as a descriptive string. Possible values are block, char, dir, fifo, file, link, and unknown. This function is an interface to C's stat function, whose man page may be helpful in understanding the different file types.

<?
print(filetype("data.txt"));
?>

boolean flock(integer file_handle, integer mode)
Use the flock function to temporarily restrict access to a file. PHP uses its own system for locking, which works across multiple platforms. However, all processes must be using the same locking system, so the file will be locked for PHP scripts, but likely not locked for other processes.

The file_handle argument must be an integer returned by fopen. The mode argument determines whether you obtain a lock that allows others to read the file (1), you obtain a lock that doesn't allow others to read the file (2), or you release a lock (3). When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. If you prefer, you may turn off blocking using modes 5 and 6.

flock Modes
flock Modes

<?
$fp = fopen("log.txt", "a");
//get lock
flock($fp, 2);
//add a line to the log
fputs($fp, date("h:i A l F dS, Yn"));
//release lock
flock($fp, 3);
fclose($fp);
//dump log
print("<PRE>");
readfile("log.txt");
print("</PRE>n");
?>

integer fopen(string filename, string mode)
The fopen function opens a file for reading or writing. The function expects the name of a file and a mode. It returns an integer, which is called a file handle. Internally, PHP uses this integer to reference a block of information about the open file. The file handle is used by other file-related functions, such as fputs and fgets.

Ordinarily, the filename argument is a path to a file. It can be fully qualified, or relative to the path of the script. If the filename begins with http:// or ftp://, the file will be opened using HTTP or FTP protocol over the Internet.

File Read/Write Modes
File Read/Write Modes
The mode argument determines whether the file is to be read from, written to, or added to. Modes with a plus sign (+) are update modes that allow both reading and writing. If the letter b appears as the last part of the mode, the file is assumed to be a binary file, which means no special meaning will be given to end-of-line characters. Table 8.6 lists all the modes.

While it is an error to open a file for writing when an HTTP URL is specified, this is not the case with FTP. You may upload an FTP file by using write mode. However, this functionality is limited. You can create remote files, but you may not overwrite existing files. With either HTTP or FTP connections, you may only read from start to finish from a file. You may not use fseek or similar functions.

Sometimes files on HTTP and FTP servers are protected by usernames and passwords. You can specify a username and a password exactly as popular Web browsers allow you to do. After the network protocol and before theserver name you may insert a username, a colon, a password, and an at-symbol (@).Three other ways to open a file are the fsockopen, gzopen, popen functions.

<?
print("<H1>HTTP</H1>n");
//open a file using http protocol
//Use username and password
if(!($myFile = fopen))
{
print("file could not be opened");
exit;
}
while(!feof($myFile))
{
// read a line from the file
$myLine = fgetss($myFile, 255);
print("$myLine <BR>n");
}
// close the file
fclose($myFile);
print("<H1>FTP</H1>n");
print("<HR>n");
// open a file using ftp protocol
if(!($myFile = fopen("ftp://ftp.php.net/welcome.msg", "r")))
{
print("file could not be opened");
exit;
}
while(!feof($myFile))
{
// read a line from the file
$myLine = fgetss($myFile, 255);
print("$myLine <BR>n");
}
// close the file
fclose($myFile);
print("<H1>Local</H1>n");
print("<HR>n");
// open a local file
if(!($myFile = fopen("data.txt", "r")))
{
print("file could not be opened");
exit;
}
while(!feof($myFile))
{
// read a line from the file
$myLine = fgetss($myFile, 255);
print("$myLine <BR>n");
}
// close the file
fclose($myFile);
?>

boolean fpassthru(integer file_handle)
The fpassthru function prints the contents of the file to the browser. Data from the current file position to the end are sent, so you can read a few lines and output the rest. The file is closed after being sent. If an error occurs, fpassthru returns false. The gzpassthru function offers the same functionality for compressed files.

<?
/*
** Get a Web page, change the title tag
*/
// open a file using http protocol
if(!($myFile = fopen))
{
print("file could not be opened");
exit;
}
$KeepSearching = TRUE;
while(!feof($myFile) AND $KeepSearching)
{
// read a line from the file
$myLine = fgets($myFile, 1024);
//watch for body tag
if(eregi("<body", $myLine))
{
//no chance to find a title tag
//after a body tag
$KeepSearching = FALSE;
}
//try adding some text after the title tag
$myLine = eregi_replace("<title>",
"<title>(fpassthru example)", $myLine);
//send line to browser
print("$myLine");
}
// send the rest of file to browser
fpassthru($myFile);
?>

integer fputs(int file_handle, string output)
The fputs function writes data to an open file. It expects a file handle as returned by fopen, fsockopen, or popen. The number of bytes written is returned, or -1 when an error occurs. The gzputs function performs the same task on compressed files.

<?
// open file for writing
$myFile = fopen("data.txt","w");
// make sure the open was successful
if(!($myFile))
{
print("file could not be opened");
exit;
}
for($index=0; $index<10; $index++)
{
// write a line to the file
fputs($myFile, "line $indexn");
}
// close the file
fclose($myFile);
?>

string fread(integer file_handle, integer length)
The fread function is a binary-safe version of the fgets function. That means it does not pay attention to end-of-line characters. It will always return the number of bytes specified by the length argument, unless it reaches the end of the file. This function is necessary if you wish to read from binary files, such as jpeg image files.

<?
/*
** Check that a file is a GIF89
*/
$filename = "php.gif";
$fp = fopen($filename, "r");
//get first 128 bytes
$data = fread($fp, 128);
//close file
fclose($fp);
//check for GIF89
if(substr($data, 0, 5) == "GIF89")
{
print("$filename is a GIF89 file.n");
}
else
{
print("$filename isn't a GIF89 file.n");
}
?>

integer fseek(integer file_handle, integer offset)
To change PHP's internal file pointer, use fseek. It expects a valid file handle as created by fopen. It also expects an offset, the number of bytes past the beginning of the file. If an error occurs, fseek returns negative one (-1); otherwise it returns zero (0). Take note that this is different from most other PHP functions.

Seeking past the end of the file is not an error; however, using fseek on a file opened by fopen if it was used with http:// or ftp:// is forbidden. If you need to know where the file pointer points, use the ftell function.

<?
// open a file
if($myFile = fopen("data.txt", "r"))
{
// jump 32 bytes into the file
fseek($myFile, 32);
// dump the rest of the file
fpassthru($myFile);
}
else
{
print("file could not be opened");
}
?>

array fstat(integer file_handle)
The fstat function gets information from C's stat function about an open file and returns it in an associative array. The elements of the array are atime, blksize, blocks, ctime, dev, gid, ino, mode, mtime, nlink, rdev, size, uid. This function returns the same information returned by stat and lstat.

integer ftell(integer file_handle)
Given a valid file handle, ftell returns the offset of PHP's internal file pointer. If you wish to move the file pointer, use the fseek function.

<?
// open a file
if($myFile = fopen("data.txt", "r"))
{
//read characters until we find a space
$c = "";
while(!(feof($myFile)) AND ($c != " "))
{
$c = fgetc($myFile);
}
print("File pointer at " . ftell($myFile) . " bytes");
}
else
{
print("file could not be opened");
}
?>

integer ftruncate(integer file_handle, integer size)

The ftruncate function truncates a file to a specified size, expressed in number of bytes.

integer fwrite(integer file_handle, string data, integer length)
The fwrite function writes a string to a file. It is similar to fputs, except that it is binary-safe. The file_handle argument must be an integer returned by fopen, fsockopen, or popen. The length argument is optional, but if present will cause the magic quotes functionality to be suspended. This means backslashes inserted into the string by PHP to escape quotes will not be stripped before writing.

<?
// open file for writing
$myFile = fopen("data.txt","w");
// make sure the open was successful
if(!($myFile))
{
print("file could not be opened");
exit;
}
for($index=0; $index<10; $index++)
{
// write a line to the file
fputs($myFile, "line $indexn");
}
// close the file
fclose($myFile);
?>

array get_meta_tags(string filename, boolean use_include_path)
The get_meta_tags function opens a file and scans for HTML meta tags. The function assumes it is a well-formed HTML file that uses native line breaks. An array indexed by the name attribute of the meta tag is returned. If the name contains any characters illegal in identifiers, they will be replaced with underscores.

The optional use_include_path will cause get_meta_tags to look for the file in the include path instead of the current directory. The include path is set in php.ini and normally is used by the include function.Like many of the file functions, get_meta_tags allows specifying a URL instead of a path on the local filesystem.

get_meta_tags
get_meta_tags

get_meta_tags

include(string filename)
The include function causes the PHP parser to open the given file and execute it. The file is treated as a normal PHP script. That is, text is sent directly to the browser unless PHP tags are used. You may use a variable to specify the file, and if the call to include is inside a loop, it will be reevaluated each time.

You may also specify files by URL by starting them with http:// or ftp://. PHP will fetch the file via the stated protocol and execute it as if it were in the local filesystem.

boolean is_dir(string filename)
The is_dir function returns TRUE if the given filename is a directory; otherwise it returns FALSE. Similar functions are is_file and is_link.

<?
$filename = "data.txt";
if(is_dir($filename))
{
print("$filename is a directory");
}
else
{
print("$filename is not a directory");
}
?>

boolean is_executable(string filename)
The is_executable function returns true if a file exists and is executable; otherwise it returns false. On UNIX this is determined by the file's permissions. On Windows this is determined by the file extension. Two related functions are is_readable and is_writeable.

<?
$filename = "data.txt";
if(is_executable($filename))
{
print("$filename is executable");
}
else
{
print("$filename is executable");
}
?>

boolean is_file(string filename)
The is_file function returns true if the given filename is neither a directory nor a symbolic link; otherwise it returns false. Similar functions are is_dir and is_link.

@CPO # above:?
$filename = "data.txt";
if(is_file($filename))
{
print("$filename is a file");
}
else
{
print("$filename is not a file");
}
?>

boolean is_link(string filename)

The is_link function returns true if the given filename is a symbolic link; otherwise it returns false. Similar functions are is_dir and is_file.

<?
$filename = "data.txt";
if(is_link($filename))
{
print("$filename is a link");
}
else
{
print("$filename is not a link");
}
?>

boolean is_readable(string filename)
The is_readable function returns true if a file exists and is readable; otherwise it returns false. On UNIX this is determined by the file's permissions. On Windows, true is always returned if the file exists. This function is similar to is_executable and is_writeable.

<?
$filename = "data.txt";
if(is_readable($filename))
{
print("$filename is readable");
}
else
{
print("$filename is not readable");
}
?>

boolean is_writeable(string filename)

The is_writeable function returns true if a file exists and is writeable; otherwise it returns false. Similar functions are is_executable and is_readable.

<?
$filename = "data.txt";
if(is_writeable($filename))
{
print("$filename is writeable");
}
else
{
print("$filename is not writeable");
}
?>

boolean link(string source, string destination)
The link function creates a hard link. A hard link may not point to a directory, may not point outside its own filesystem, and is indistinguishable from the file to which it links. See the man page for link or ln for a full description. The link function expects a source file and a destination file. On Windows this function does nothing and returns nothing. You can create a symbolic link with the symlink function.

<?
link("/www/htdocs/index.php", "/www/htdocs/index2.php");
?>

integer linkinfo(string filename)
The linkinfo function calls the C function lstat for the given filename and returns the st_dev field lstat generates. This may be used to verify the existence of a link. It returns false on error. You can read more about lstat on the man page, or in the help file for Microsoft Visual C++.

<?
print(linkinfo("data.txt"));
?>

array lstat(string filename)
The lstat function executes C's stat function and returns an array. The array contains 13 elements, numbered starting with zero. If the filename argument points to a symbolic link, the array will reflect the link, not the file to which the link points. To get information about the files to which the link points, use the stat function.

lstat
array lstat(string filename)

get_meta_tags

boolean mkdir(string directory, integer mode)
The mkdir function creates a new directory with the supplied name. Permissions will be set based on the mode argument, which follows the same rules as chmod. On Windows the mode argument is ignored. You can use the rmdir function to remove a directory.

<?
if(mkdir("myDir", 0777))
{
print("directory created");
}
else
{
print("directory cannot be created");
}
?>

integer opendir(string directory)
The opendir function requires a directory name and returns a directory handle. This handle may be used by readdir, rewinddir, and closedir. The dir function described above provides an alternative to this group of functions.

<?
// print the current directory in a table
print("<TABLE BORDER="1">n");
// create header row
print("<TR>n");
print("<TH>Filename</TH>n");
print("<TH>File Size</TH>n");
print("</TR>n");
// open directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory))
{
print("<TR>");
print("<TD>$entryName</TD>");
print("<TD ALIGN="right">");
print(filesize($entryName));
print("</TD>");
print("</TR>n");
}
// close directory
closedir($myDirectory);
print("</TABLE>n");
?>

integer pclose(integer file_handle)
The pclose function closes a file stream opened by popen. The return value of the process called in the call to popen is returned.

integer popen(string command, string mode)

The popen function opens a pipe to an executing command that may be read from or written to as if it were a file. A file handle is returned that is appropriate for use with functions such as fgets. Pipes work in one direction only, which means you can't use update modes with popen.

When you open a pipe, you are executing a program in the local filesystem. As with the other functions that execute a command (exec, passthru, and system), you should consider both the high cost of starting a new process and the security risk if user input is included in the command argument. If you must pass user-supplied data to a command, pass the information through the escapeshellcmd function first.

popen
popen

string readdir(integer directory_handle)

The readdir function returns the name of the next file from a directory handle created by opendir, or FALSE when no entries remain. You can place readdir in the conditional expression of a while loop to get every entry in a directory. Keep in mind that . and .. are always present and will be returned. See closedir for an example of use.

integer readfile(string filename)
The file given is read and sent directly to the browser by the readfile function, and the number of bytes read is returned. If an error occurs, false is returned. If the filename begins with http:// or ftp://, the file will be fetched using HTTP or FTP, respectively. Otherwise the file is opened in the local filesystem. If you need to send a compressed file to the browser, use readgzfile. If you'd rather read a file into a variable, use the file function.

<?
print("Here is some data BR>n");
readfile("data.txt");
?>

string readlink(string filename)
The readlink function returns the path to which a symbolic link points. It returns false on error. Another function that gets information about a link is linkinfo.

<?
print(readlink("data.txt"));
?>

boolean rename(string old_name, string new_name)
The rename function changes the name of a file specified by the old_name argument to the name specified in the new_name argument. The new and old names may contain complete paths, which allows you to use rename to move files.

<?
//move data.txt from local directory
//to the temp directory
rename("./data.txt", "/tmp/data.dat");
?>

boolean rewind(integer file_handle)
The rewind function moves PHP's internal file pointer back to the beginning of the file. This is the same as using fseek to move to position zero.
pre> /*
** print a file, then print the first line again
*/
// open a local file
$myFile = fopen("data.txt", "r");
while(!feof($myFile))
{
// read a line from the file
$myLine = fgetss($myFile, 255);
print("$myLine <BR>n");
}
rewind($myFile);
$myLine = fgetss($myFile, 255);
print("$myLine <BR>n");
// close the file
fclose($myFile);
?>

boolean rewinddir(integer handle)
The rewinddir function resets PHP's internal pointer to the beginning of a directory listing. It returns TRUE unless an error occurs, in which case it returns FALSE. The handle is an integer returned by opendir.

<?
/*
** print the current directory in a table
*/
print("<TABLE BORDER="1">n");
// open directory
$myDirectory = opendir(".");
print("<TR>n");
print("<TH>Filename</TH>n");
// get each entry
while($entryName = readdir($myDirectory))
{
print("<TD>$entryName</TD>n");
}
print("</TR>n");
// Go back to beginning
rewinddir($myDirectory);
print("<TR>n");
print("<TH>Size</TH>n");
// get each entry
while($entryName = readdir($myDirectory))
{
print("<TD ALIGN="right">");
print(filesize($entryName));
print("</TD>n");
}
print("</TR>n");
// close directory
closedir($myDirectory);
print("</TABLE>n");
?>

boolean rmdir(string directory)

Use the rmdir function to remove a directory. The directory must be empty. To remove a file, use unlink.

<?
if(rmdir("/tmp/leon"))
{
print("Directory removed");
}
else
{
print("Directory not removed"):
}
?>

set_file_buffer(integer file_handle, integer size)
Use set_file_buffer to set the size of the write buffer on a file stream. It requires a valid file handle as created by fopen, fsockopen, or popen. The size argument is a number of bytes, and if you set a buffer size of zero, no buffering will be used. You must call set_file_buffer before making any reads or writes to the file stream. By default, file streams start with 8K buffers.

<?
// open file for writing
$myFile = fopen("data.txt","w");
// make sure the open was successful
if(!($myFile))
{
print("file could not be opened");
exit;
}
//use 1K buffer
print(set_file_buffer($myFile, 1024));
for($index=0; $index<10; $index++)
{
// write a line to the file
fwrite($myFile, "line $indexn");
}
// close the file
fclose($myFile);
?>

array stat(string filename)
The stat function executes C's stat function and returns an array. The array contains 13 elements, numbered starting at zero. If the filename argument points to a symbolic link, the array will reflect the file to which the link points. To get information about the linkitself, use the lstat function.

<?
/*
** print stat information based on OS
*/
// get stat information
$statInfo = stat("data.txt");
if(eregi("windows", $OS))
{
// print useful information for Windows
printf("Drive: %c <BR>n", ($statInfo[0]+65));
printf("Mode: %o <BR>n", $statInfo[2]);
print("Links: $statInfo[3] <BR>n");
print("Size: $statInfo[7] bytes<BR>n");
printf("Last Accessed: %s <BR>n",
date("H:i:s F d, Y", $statInfo[8]));
printf("Last Modified: %s <BR>n",
date("H:i:s F d, Y", $statInfo[9]));
printf("Created: %s <BR>n",
date("H:i:s F d, Y", $statInfo[10]));
}
else
{
// print UNIX version
print("Device: $statInfo[0] <BR>n");
print("INode: $statInfo[1] <BR>n");
printf("Mode: %o <BR>n", $statInfo[2]);
print("Links: $statInfo[3] <BR>n");
print("UID: $statInfo[4] <BR>n");
print("GID: $statInfo[5] <BR>n");
print("Device Type: $statInfo[6] <BR>n");
print("Size: $statInfo[7] bytes<BR>n");
printf("Last Accessed: %s <BR>n",
date("H:i:s F d, Y", $statInfo[8]));
printf("Last Modified: %s <BR>n",
date("H:i:s F d, Y", $statInfo[9]));
printf("Last Changed: %s <BR>n",
date("H:i:s F d, Y", $statInfo[10]));
print("Block Size: $statInfo[11] <BR>n");
print("Blocks: $statInfo[12] <BR>n");
}
?>7_-Array-Elements-Returned-by-the-stat-Function
Array-Elements-Returned-by-the-stat-Function

boolean symlink(string source, string destination)
The symlink function creates a symbolic link to the source argument with the name in the destination argument. To create a hard link, use the link function.

<?
//link moredata.txt to existing file data.txt
if(symlink("data.txt", "moredata.txt"))
{
print("Symbolic link created");
}
else
{
print("Symbolic link not created");
}
?>

integer tmpfile()
The tmpfile function opens a new temporary file and returns its file handle. This handle may be used in the same way as one returned by fopen using anupdate mode. When you close the file, or your script ends, the file will beremoved. This function is a wrapper for the C function of the same name. If for some reason a temporary file cannot be created, FALSE is returned.

<?
//open a temporary file
$fp = tmpfile();
//write 10K of random data
//to simulate some process
for($i=0; $i<10240; $i++)
{
//randomly choose a letter
//from a range of printables
fputs($fp, chr(rand(ord(' '), ord('z'))));
}
//return to start of file
rewind($fp);
//dump and close file,
//therefore deleting it
fpassthru($fp);
?>

boolean touch(string filename, integer time)
The touch function attempts to set the time the file was last modified to thegiven time, expressed in seconds since January 1, 1970. If the time argument is omitted, the current time is used. If the file does not exist, it willbe created with zero length. This function is often used to create empty files.To find out when a file was last modified, use filemtime.

<?
touch("data.txt");
?>

integer umask(integer umask)
The umask function returns the default permissions given files when they are created. If the optional umask argument is given, it sets the umask to a logical-and (&) performed on the given integer and 0777. Under Windows this function does nothing and returns false. To find out the permissions set on a particular file, use fileperms.

<?
printf("umask is %o", umask(0444));
?>

boolean unlink(string filename)
The unlink function removes a file permanently. To remove a directory, use rmdir.

<?
if(unlink("data2.txt"))
{
print("data2.txt deleted");
}
else
{
print("data2.txt could not be deleted");
}
?>

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics