File and directory management. Direct work with files Php functions for working with files and folders


Last update: 11/1/2015

Move a file

To move a file, use the rename() function:

If we have a subdirectory subdir in the directory of the hello.txt file, then the file will be moved to it. If the file was successfully moved, the function will return true .

Copying a file

To copy a file, use the copy() function. It takes the name of the file being copied, and the name of the copy of the file. And if the copying was successful, returns true:

Deleting a file

To delete a file, use the unlink function, which takes the file name and returns true if the file was successfully deleted:

Creating a directory

To create a directory, use the mkdir() function:

If(mkdir("newdir")) echo "The directory has been created"; else echo "Error creating directory";

In this case, mkdir creates a new directory "newdir" in the current directory. If creation is successful, the function returns true , otherwise false

To create a new folder in the root directory, you can use the expression mkdir("/newdir") .

Removing a directory

To remove a directory, use the rmdir() function. Its use is similar to mkdir():

If(rmdir("newdir")) echo "Directory deleted"; else echo "Error deleting directory";

Directory Operations

To get the absolute path to the current directory, use the getcwd() function, which returns the path as a string:

$path = getcwd(); echo $path; // C:\localhost

The opendir() function opens a specific directory to read file and directory information from it. If the directory is successfully opened, the function returns a handle to the open directory. After finishing working with the directory, it must be closed using the closedir() function.

The readdir() function is used to read the name of a single file in an open directory.

Now let's combine these functions and display all files and subdirectories from the current directory on the page:

"; else echo "file: $file
"; ) closedir($dh); // close the directory ) ) ?>

Opens a file and associates it with a handle.
Syntax:

Int fopen(string $filename, string $mode, bool $use_include_path=false)

Opens a file named $filename in $mode and returns a handle to the open file. If the operation fails, the function returns false. The optional use_include_path specifies that if a relative filename is specified, the list of paths used by include() and require() statements should also look for it.
Typically this option is not used.
The $mode parameter can take the following values:
r

The file is opened read-only. If the file does not exist, the call logs an error. After successful opening, the file pointer is set to its first byte, i.e. to the beginning.
r+

The file is opened for reading and writing at the same time. The current position pointer is set to its first byte. If the file does not exist, returns false. If at the time of recording the file pointer is set somewhere in the middle of the file, then the data will be written directly on top of the existing data, rather than spreading it apart, increasing the file size if necessary.
w

Creates a new empty file. If at the time of the call there was already a file with the same name, then it is first destroyed. If the file name is incorrectly specified, the call fails.

Similar to r+, but if the file did not originally exist, creates it. After this, you can work with the file in both read and write mode. If the file existed before the call, its contents are deleted.
a

Opens an existing file in write mode, and at the same time shifts the current position pointer beyond the last byte of the file. As usual, the call is not successful if the file is missing.
a+

Opens a file in read-write mode, the file pointer is set to the end of the file, but the contents of the file are not destroyed. Differs from a in that if the file did not originally exist, it is created. This mode is useful if you need to add something to a file, but you do not know whether such a file has already been created.
But this is not yet a complete description of the $mode parameter. The fact is that at the end of any of the lines r,w,a,r+,w+ and a+
there may be one more optional character - b or t. If b is specified (or none at all),
then the file opens in binary read/write mode. If this is t, then the translation mode of the line feed character is set for the file, i.e. it is perceived as textual.

Creates a new temporary file with a unique name and opens it for reading and writing.
Syntax:

Int tmpfile()

All subsequent work must be done with the returned file descriptor because the file name is not available.
The space occupied by the temporary file is automatically freed when it is closed and when the program exits.

Opens a process file index (PHP 3, PHP 4, PHP 5)

Description:

Resource popen(string command, string mode)

Opens a thread to a process, executed by forking the command specified in command.

Returns a file pointer identical to that returned by fopen(), except that it is one-way (can only be read or written) and must be closed using pclose(). This pointer can be used with fgets(), fgetss() and fwrite().

If an error occurs, returns FALSE.

Note: If you are looking for two-way communication, use proc_open().

Example of using the popen() function

$handle = popen("/bin/ls", "r");
?>

If a command to execute cannot be found, a valid resource will be returned. This may look strange, but it makes sense; this gives you the ability to access any error message that the shell returns:

error_reporting(E_ALL);

Comment: When running in safe mode, you can only run anything within the safe_mode_exec_dir. Currently, the use of... while traveling is prohibited.

Attention

When running in safe mode, all words following the initial command are treated as a single argument. That is, echo y | echo x will work like echo "y | echo x".

Closes a file previously opened by fopen().

Syntax:

Int fclose(int $fp)

Returns false if the file could not be closed (for example, something happened to it or the connection with the remote host was lost).
Otherwise, returns true.

You should always close FTP and HTTP connections because otherwise
a “stray” file will lead to unnecessary downtime of the channel and excessive load on the server. In addition, by successfully closing the connection, you will be confident that all data was delivered without errors.

pclose()

Closes the process file pointer (PHP 3, PHP 4, PHP 5)

Description:

Int pclose(resource handle)

Closes the file pointer to a pipe opened with popen().

The file pointer must be valid and must be returned by a successful call to popen().

Returns the exit status of the terminating process.

Reads a specified number of characters from an open file.
Syntax:

String fread(int $f, int $numbytes)

Reads $numbytes characters from file $f and returns a string of those characters. After reading, the file pointer is advanced to the next position after the block read. If $numbytes is greater than can be read from the file, what can be read is returned. This technique can be used if you need to read the entire file into a line. To do this, simply set $numbytes to a very large number. But if you care about saving memory in the system, this is not recommended.

readfile()

Outputs file (PHP 3, PHP 4, PHP 5)

Description:

Int readfile(string filename[, bool use_include_path[, resource context]])

Reads a file and writes it to the output buffer.

Options:

filename - name of the file being read
use_include_path - optional parameter; if TRUE, the file will also be searched in include_path (php.ini directive).
context - streaming resource of the environment.

Returns the number of bytes read from the file. If an error occurs, will return FALSE unless the function was called as @readfile(), and will print an error message.

Example. Forced start of downloading a file

$file = "monkey.gif";

if (file_exists($file)) (
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
header("Content-Length: " . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>

The result of running the above code will be something like this:

fflush()

Flushing the output buffer to a file (PHP 4 >= 4.0.1, PHP 5)

Description:

Bool fflush (resource handle)

This function dumps buffered data into the file pointed to by handle.

Returns TRUE if successful, FALSE otherwise.

stream_set_write_buffer()

Sets the file buffer for this stream (PHP 4 >= 4.3.0, PHP 5)

Description:

Int stream_set_write_buffer(resource stream, int buffer)

Output to a file using fwrite() normally uses an 8K buffer. This means that if there are two processes wanting to output to the same output stream (file), each of those processes is suspended after every 8K of output to allow the other process to output. Stream_set_write_buffer() sets the buffering for writes to the given file-pointing stream. If buffer is set to 0, then the write operation is unbuffered. This ensures that all fwrite() processes complete before other processes have access to write to the same output stream.

The function returns 0 on success, or EOF if the I/O interrupt request was rejected.

The following example demonstrates the use of stream_set_write_buffer() to create an unbuffered stream

$fp = fopen($file, "w");
if ($fp) (
stream_set_write_buffer($fp, 0);
fwrite($fp, $output);
fclose($fp);
}
?>

set_file_buffer()

Function alias stream_set_write_buffer() (PHP 3 >= 3.0.8, PHP 4 >= 4.0.1, PHP 5)

Description: The function is an alias for the stream_set_write_buffer() function.

highlight_file()

Syntax:






Source Display


if(!$script) (
echo "
ERROR: Please provide a script name
";
) else (

echo "

File listing: $PATH_INFO

n
n";
if(!@highlight_file($script))
echo "File output error";
) else (
echo "

";
}
}

echo "



Write to file.
Syntax:

Int fwrite(int $f, string $str)

Writes the entire contents of string $str to file $f. This function pairs with fread(), acting
"in the opposite direction."

When working with text files (that is, when the t character is specified in file open mode)
all n are automatically converted to the line separator accepted by your operating system.

Reads one line from the file, ending with a newline character n.
Syntax:

String fgets(int $f, int $length)

This character is also read and included in the result. If a line in the file is more than $length-1 bytes, then only its $length-1 characters are returned. The function is useful if you have opened a file and want to “go through” all its lines. However, even in this case (and it will be faster) to use the File() function.
It is also worth noting that this function (like the fread() function) in the case of text mode on Windows takes care of converting rn pairs into a single n character.

Complete analogue of fwrite().

Syntax:

Int fputs(int $f, string $str)

fgetcsv()

A function for working with one of the file formats in which Excel can save data.
Syntax:

List fgetcsv(int $f, int $length, char $delim=",")

The function reads a line from the file specified by $f and splits it at $delim. The $delim parameter must be a one-character string, otherwise only the first character of the string is taken into account. The function returns the resulting list or false if there are no more lines. The $length parameter specifies the maximum length of the string, just as it does in fgets().
Empty lines in the file are not ignored, but are returned as a list of one element - the empty string.
Example:

$f=fopen("file.csv","r") or die("Error");
for($i=0; $data=fgetcsv($f, 1000, ";"); $i++) (
$num = count($data);
if($num==1 && $data==="") continue;
echo "

Line number $i ($num fields):

";
for($c=0; $c<$num; $c++)
print "[$c]: $data[$c]
";
}
fclose($f);

file_get_contents()

Get file contents as one line (PHP 4 >= 4.3.0, PHP 5)

Description:

String file_get_contents(string filename
[, bool use_include_path [, resource context [, int offset [, int maxlen]]]])

This function is identical to the file() function, with the only difference being that the contents of the file are returned in a string, starting at the specified offset and up to maxlen bytes. If it fails, file_get_contents() will return FALSE.

Using the file_get_contents() function is most preferable when you need to get the entire contents of a file, since the function uses a "memory mapping" algorithm (if supported by the operating system) to improve performance.

Note: If you open a URI containing special characters such as a space, you need to encode the URI using urlencode().

List of changes

Version Description
5.0.0 Added context support.
5.1.0 Added offset and maxlen arguments.

Notes

Comment

Attention

file_put_contents()

Write a string to a file (PHP 5)

Description:

Int file_put_contents(string filename, mixed data [, int flags [, resource context]])

The function is identical to calling fopen(), fwrite() and fclose() in sequence. The return value of the function is the number of bytes written to the file.

The flags parameter can take the value FILE_USE_INCLUDE_PATH and/or FILE_APPEND. Use FILE_USE_INCLUDE_PATH with caution.

You can also pass a (one-dimensional) array as the data parameter. This would be equivalent to calling file_put_contents($filename, join("", $array)).

As of PHP 5.1.0, you can also pass a stream resource as the data argument. As a result, the remaining buffer of this stream will be copied to the specified file. This is similar to using stream_copy_to_stream().

Comment: This function is safe to process data in binary form.

For this feature, you can use the URL as the file name if the "fopen wrappers" option has been enabled.

Reads the contents of a file and puts it into an array (PHP 3, PHP 4, PHP 5)

Description:

Array file (string filename [, int use_include_path [, resource context]])

This function is identical to the readfile() functions, with the difference that file() returns the contents of the read file as an array. Each element of the returned array contains a corresponding string with line terminator characters. If there is an error, the file() function returns FALSE.

You can specify the optional use_include_path parameter equal to "1" if you want the file to also be searched in the directories specified by the include_path directive.

// Get the contents of the file as an array. In this example we use
// access via HTTP protocol to receive HTML code from a remote server.
$lines = file("http://www.example.com/");

// Let's traverse the array and output the line numbers and their contents as HTML code.
foreach ($lines as $line_num => $line) (
echo "Line # ($line_num): " . htmlspecialchars($line) ."
\n";
}

// Second example. Let's get the content of the web page as one line.
// See also the description of the file_get_contents() function.
$html = implode("", file("http://www.example.com/"));
?>

For this feature, you can use the URL as the file name if the "fopen wrappers" option has been enabled. See the fopen() function for more information on defining a file name, and see Appendix for a list of supported URL protocols. M.

Comment: Each line in the resulting array will be terminated by end-of-line characters, so if you need to get rid of these characters, you will have to use the rtrim() function.

Comment Note: If you are having trouble recognizing PHP line endings when reading files on a Macintosh-compatible computer, or when reading files created on a Macintosh-compatible computer, you must enable the auto_detect_line_endings option.

Comment: Since PHP 4.3.0, you can use the file_get_contents() function to get the contents of a file as a string.

As of PHP 4.3.0, the file() function handles binary data correctly.

Comment: Context support was added in PHP 5.0.0.

Attention

When using SSL, Microsoft IIS violates the protocol by closing the connection without sending the close_notify indicator. PHP will report this as an "SSL: Fatal Protocol Error" the moment you reach the end of the data. To get around this, you should set error_reporting to a level that excludes E_WARNING. PHP versions 4.3.7 and older can detect that there is a problematic IIS on the server side and does not display a warning. If you use fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing this warning.

fpassthru()

Prints all remaining data from the file pointer (PHP 3, PHP 4, PHP 5)

Description:

Int fpassthru (resource handle)

Reads the specified file pointer from the current position to EOF (end of file) and writes the result to the output buffer.

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed to output.

The file pointer must be valid and point to a file successfully opened by fopen() or fsockopen().

You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

If you want to simply dump the contents of a file into the output buffer without first modifying it or starting at a specific offset, you may want to use readfile(), which will save you the unnecessary fopen() call.

Note: When using fpassthru() on a binary file in Windows systems, you must ensure that you open the file in binary mode by adding b to the file open mode used in fopen().

Using fpassthru() with binaries

// open the file in binary mode
$name = ".\public\dev\img\ok.png";
$fp = fopen($name, "rb");

// send the required headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// drop the image and stop script execution
fpassthru($fp);
exit;

End of file indicator.
Syntax:

Int feof(int $f)

Returns true if the end of the file is reached (that is, if the file pointer is set beyond the end of the file).

$f=fopen("myfile.txt","r");
while(!feof($f))
( $str=fgets($f);
// Process the next line $str

}
fclose($f);

Sets the file pointer to a specific position.
Syntax:

Int fseek(int $f, int $offset, int $whence=SEEK_SET)

Sets the file pointer to a byte at offset $offset (from the beginning of the file, from the end of the file, or from the current position, depending on the $whence parameter).
This may not work if the handle $f is associated not with a regular local file, but with an HTTP or FTP connection.

The $whence parameter specifies from where the $offset offset is counted. In PHP, there are three constants for this, equal to 0, 1 and 2, respectively:

sets the position starting from the beginning of the file;

counts the position relative to the current position;

counts the position relative to the end of the file;

If the last two constants are used, the $offset parameter may well be negative (and when SEEK_END is used, it will certainly be negative).
If successful, this function returns 0, and -1 if unsuccessful.

Returns the position of the file pointer.
Syntax:

Int ftell(int $f)

rewind()

Resets the file pointer cursor (PHP 3, PHP 4, PHP 5)

Description:

Bool rewind(resource handle)

Resets the handle file pointer cursor to the beginning of the file stream.

The file pointer must be accessible and refer to the file successfully opened using fopen().

Comment: If you open a file in append mode ("a"), any data you write will be appended to the end of the file, regardless of the cursor position.

file_exists

Checks the existence of the called file.
Syntax:

Bool file_exists(string filename)

Returns true if a file named filename exists at the time of the call. This feature should be used with caution.
For example, the following code is no good from a security point of view:

If(!file_exists($fname))
$f=fopen($fname,"w");
else
$f=fopen($fname,"r");

The fact is that some time passes between calling file_exists() and opening the file in w mode, during which another process can intervene and replace the file we are using. This problem comes to the fore when writing a counter script.
The function does not work with remote files; the file must be in a file system accessible to the server.
The results of the function are cached, see the clearstatcache() function.

filetype

Returns the file type.
Syntax:

String filetype(string filename)

Returns a string that describes the file type named filename. If such file does not exist, returns false.
Once called, the string will contain one of the following values:

file - regular file;
dir - directory;
link - symbolic link;
fifo - fifo channel;
block - block-oriented device;
char - character-oriented device;
unknown - unknown file type;

Checking the existence of a regular file.
Syntax:

Bool is_file(string filename)

Returns true if filename is a regular file.

Checking the existence of a directory.
Syntax:

Bool is_dir(string filename)

Returns true if directory filename exists.

Bool is_link(string filename)

Returns true if filename is a symbolic link.
The function does not work on Windows.

is_readable

Checks the existence of a readable file.
Syntax:

Bool is_readable(string filename)

Returns true if the file can be opened for reading.
Typically PHP accesses the file with the privileges of the user running the web server (often "nobody").
Safety considerations must be taken into account.

is_writeable

Checks the existence of a writable file.
Syntax:

Bool is_writeable(string filename)

Returns true if the file is writable. Typically PHP accesses the file with the privileges of the user running the web server (often "nobody"). Safety considerations must be taken into account.

is_executable

Checking the existence of the file being launched.
Syntax:

Bool is_executable(string filename)

Returns true if filename is executable.

is_uploaded_file

Checking the existence of a file uploaded using the HTTP POST method.

Syntax:

Bool is_uploaded_file(string filename)

Returns true if file named filename was uploaded to the server via HTTP POST.

This is often useful to ensure that users are not maliciously trying to force the script to work on files they shouldn't work on.

The function collects together all the information produced by the operating system for the specified file and returns it as an array.

Syntax:

Array stat(string $filename)

This array always contains the following elements with the specified keys:

0 - device;
1 - Node number inode;
2 - file protection attributes;
3 - the number of synonyms ("hard" links) of the file;
4 - owner uid;
5 - group gid identifier;
6 - device type;
7 - file size in bytes;
8 - last access time in seconds since January 1, 1970;
9 - time of the last modification of the file contents;
10 - time of last change of file attributes;
11 - block size;
12 - number of occupied blocks;

This array contains information that is available on Unix systems. Under Windows, many fields may be empty.

If $filename specifies not a file name, but the name of a symbolic link, then information about the file to which this link refers (and not about the link) will still be returned.

fileinode()

Get file inode number (PHP 3, PHP 4, PHP 5)

Description:

Int fileinode(string filename)

The function returns the inode number of the file or FALSE if an error occurs.

Comment

fileowner()

Get file owner ID (PHP 3, PHP 4, PHP 5)

Description:

Int fileowner(string filename)

The function returns the numeric ID of the owner of the specified file, or FALSE if an error occurs. To get the owner's name as a string, use the posix_getpwuid() function.

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers.

fileperms()

Get information about file permissions (PHP 3, PHP 4, PHP 5)

Description:

Int fileperms(string filename)

The function returns information about the permissions of the specified file or FALSE if an error occurs.

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers. For a list of packers supported by the stat() family of functions, see Appendix. M.

Displaying permissions in octal notation

echo substr(sprintf("%o", fileperms("/tmp")), -4);
echo substr(sprintf("%o", fileperms("/etc/passwd")), -4);
?>

This will output:

1777
0644

Displaying complete information about rights

$perms = fileperms("/etc/passwd");

if (($perms & 0xC000) == 0xC000) (
// Socket
$info = "s";
) elseif (($perms & 0xA000) == 0xA000) (
// Symbolic link
$info = "l";
) elseif (($perms & 0x8000) == 0x8000) (
// Ordinary
$info = "-";
) elseif (($perms & 0x6000) == 0x6000) (
// Special block
$info = "b";
) elseif (($perms & 0x4000) == 0x4000) (
// Directory
$info = "d";
) elseif (($perms & 0x2000) == 0x2000) (
// Special character
$info = "c";
) elseif (($perms & 0x1000) == 0x1000) (
// FIFO stream
$info = "p";
) else (
// Unknown
$info = "u";
}

// Owner
$info .= (($perms & 0x0100) ? "r" : "-");
$info .= (($perms & 0x0080) ? "w" : "-");
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? "s" : "x") :
(($perms & 0x0800) ? "S" : "-"));

// Group
$info .= (($perms & 0x0020) ? "r" : "-");
$info .= (($perms & 0x0010) ? "w" : "-");
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? "s" : "x") :
(($perms & 0x0400) ? "S" : "-"));

// World
$info .= (($perms & 0x0004) ? "r" : "-");
$info .= (($perms & 0x0002) ? "w" : "-");
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? "t" : "x") :
(($perms & 0x0200) ? "T" : "-"));

echo $info;
?>

Result:

R--r--r--

fnmatch()

Does the file name match the pattern (PHP 4 >= 4.3.0, PHP 5)

Description:

Bool fnmatch (string pattern, string string [, int flags])

fnmatch() checks whether the passed string parameter matches the specified shell wildcard pattern.

This function is useful when working with filenames, although it can also be used on a regular string. The average user is familiar with shell substitutions, at least in their simplest form of "?" substitutions. and "*", so using fnmatch() instead of ereg() or preg_match() to search the front end of the site can be much more convenient for users not familiar with regular expressions.

Checks whether the color matches the shell wildcard pattern.

if (fnmatch("*gry", $color)) (
echo "some form of gray ...";
}
?>

This feature is currently not available on Windows and other non-POSIX-compliant systems.

Gets information about a file using the open file pointer (PHP 4, PHP 5)

Description:

Array fstat (resource handle)

Collects statistical information about an open file using the file handle handle. This function is similar to stat(), except that it operates on the open file pointer rather than the file name.

Returns an array with statistical information for the file; The array format is described in detail on the stat() function description page.

Example of using the fstat() function

// open the file
$fp = fopen("/etc/passwd", "r");

// collect statistics
$fstat = fstat($fp);

// close the file
fclose($fp);

// display only the associative part
print_r(array_slice($fstat, 13));

Array
=> 771
=> 488704
=> 33188
=> 1
=> 0
=> 0
=> 0
=> 1114
=> 1061067181
=> 1056136526
=> 1056136526
=> 4096
=> 8
)

Comment

is_writable()

Determines whether a file is writable (PHP 4, PHP 5)

Description:

Bool is_writable(string filename)

Returns TRUE if file filename exists and is writable. The filename argument can be the name of a directory, allowing you to check whether directories are writable.

Don't forget that PHP can access the file as the user running the web server (usually "nobody"). Safe Mode restrictions are not taken into account.

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this function can also be used with some url packers

Gets information about a file or symbolic link (PHP 3 >= 3.0.4, PHP 4, PHP 5)

Description:

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers.

fileatime

Returns the time the file was last accessed.

Syntax:

Int fileatime(string filename)

If the file is not found, returns false.

The file's last access time attribute changes each time the file's data is read. Since this greatly reduces performance when working intensively with files and directories, changing this attribute is often blocked in operating systems, and then the function is useless.

filetime

Returns the time the file was last modified, or false if the file does not exist.

Syntax:

Int filemtime(string $filename)

filectime

Returns the creation time of the file.

Syntax:

Int filectime(string $filename)

filesize

Returns the size of the file in bytes, or false if the file does not exist.

Syntax:

Int filesize(string $filename)

Sets the modification time.

Syntax:

Int touch(string $filename [, int $timestamp])

Sets the modification time of the specified file $filename to $timestamp (in seconds since January 1, 1970).

If the second parameter is not specified, then the current time is assumed. In case of error, returns false.

If a file with the specified name does not exist, it is created empty.

Changes the access mode of a file or directory (PHP3, PHP4, PHP5)

Description:



// octal, the right way
?>

The value of the mode parameter consists of three octal numbers that determine the access level for the owner of the file, for the group to which the owner belongs, and for other users, respectively. The number that defines the user level can be calculated by summing the values ​​that define the rights:

1 - execution access,
2 - write access,
4 - read access.

You can learn more about the rights system in Unix systems using the commands "man 1 chmod" and "man 2 chmod".

//Write and read access for owner, no access for others




chmod("/somedir/somefile", 0755);


?>

Returns TRUE on success or FALSE on error.

Note: The current user is the user under whom PHP is running. It is possible that this user will be different from the user you use to access your command shell or FTP account.

Note: When Safe Mode is enabled, PHP checks to see if the file or directory you are working on has the same UID as the script being executed. Additionally, you cannot set SUID, SGID, or sticky bits.

Source: http://www.php.ru/manual/function.chmod.html

file_exists()

Check for the existence of a specified file or directory (PHP 3, PHP 4, PHP 5)

Description:

Bool file_exists (string filename)

Returns TRUE if the file or directory with the name specified in the filename parameter exists; returns FALSE otherwise.

On Windows platforms, to check for the presence of files on network shares, use names like //computername/share/filename or \\computername\share\filename.

Checking file existence

$filename = "/path/to/foo.txt";

if (file_exists($filename)) (
echo "The file $filename exists";
) else (
echo "The file $filename does not exist";
}
?>

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers.

filegroup()

Get file group ID (PHP 3, PHP 4, PHP 5)

Description:

Int filegroup (string filename)

The function returns the file group identifier as a number. To get the group name as a string, use the posix_getgrgid() function. If an error occurs, the function returns FALSE and an E_WARNING error message is generated.

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers.

basename

Extracts the file name from the path.
Syntax:

String basename(string $path)

Extracts the base name from $path
Examples:

Echo basename("/home/somebody/somefile.txt"); // outputs "somefile.txt"
echo basename("/"); // outputs nothing
echo basename("/."); // prints "."
echo basename("/./"); // also outputs "."
echo basename("/home/somebody/somefile.php",".php"); // prints "somefile"

The basename() function does not check for the existence of a file. It simply takes the part of the string after the rightmost slash and returns it.

This function handles both forward and backslashes correctly under Windows.

Highlights the directory name.
Syntax:

String dirname(string $path)

Returns the directory name extracted from $path. The function is quite “reasonable” and can highlight non-trivial situations, which are described in the examples:

Echo dirname("/home/file.txt"); // prints "/home"
echo dirname("../file.txt"); // prints ".."
echo dirname("/file.txt"); // prints "/" under Unix, "" under Windows
echo dirname("/"); // the same
echo dirname("file.txt"); // prints "."

If dirname() is given just a file name, it will return ".", meaning "current directory".

Generates a unique file name in a specific directory.
Syntax:

String tempnam(string $dir, string $prefix)

Generates a file name in the $dir directory with a $prefix in the name, so that a file created under this name in the future will be unique. To do this, a random number is appended to the $prefix string.
For example, calling tempnam("/tmp","temp") might return /tmp/temp3a6b243c.
If such a name needs to be created in the current directory, pass $dir="."

realpath

Converts a relative path to an absolute path.
Syntax:

String realpath(string $path)

Converts the relative path $path to absolute, i.e. starting from the root.
Example:

Echo realpath("../t.php"); // for example /home/t.php
echo realpath("."); // displays the name of the current directory

The file specified in the $path parameter must exist, otherwise the function will return false.

(PHP 3, PHP 4, PHP 5)

rename -- Renames a file or directory
Description

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

Tries to rename oldname to newname.
Returns TRUE on success or FALSE on error.
Example of using the rename() function

?>

Note: In PHP versions earlier than 4.3.3, the rename() function could not rename files located on a different partition on *nix-based OSes.
Note: As of PHP 5.0.0, the rename() function can also be used with some URL wrappers.

Note: The wrapper used in oldname MUST match the wrapper used in newname.
Note: The context attribute has been added since PHP 5.0.0.

Finds file paths matching a pattern (PHP 4 >= 4.3.0, PHP 5)

Description:

Array glob (string pattern [, int flags])

The glob() function searches for all paths matching pattern according to the rules used in libc's glob() function, which are similar to the rules used by most common shells. No tilde expansion or parameter substitution is performed.

Returns an array containing matching files/directories or FALSE on error.

Valid flags:

GLOB_MARK - Adds a slash to each item returned
GLOB_NOSORT - Returns files as they appear in the directory (without sorting)
GLOB_NOCHECK - Returns a search pattern if no files were found using it.
GLOB_NOESCAPE - Backslashes do not escape metacharacters
GLOB_BRACE - Expands (a,b,c) to match "a", "b" or "c"
GLOB_ONLYDIR - Returns only directories matching the pattern

Comment: In versions earlier than PHP 4.3.3, GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.

A convenient way to use glob() to replace opendir() and its friends.

foreach (glob("*.txt") as $filename) (
echo "$filename size " . filesize($filename) . "\n";
}
?>

The result will be something like this:

Funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

pathinfo()

Returns file path information (PHP 4 >= 4.0.3, PHP5)

Description:

Array pathinfo(string path [, int options])

pathinfo() returns an associative array that contains information about path. The returned array consists of the following elements: dirname, basename and extension.

You can specify which elements will be returned using the optional options parameter. It consists of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION and PATHINFO_FILENAME (introduced in PHP 5.2.0). By default, all elements are returned.

Example of using the pathinfo() function

$path_parts = pathinfo("/www/htdocs/index.html");

echo $path_parts["dirname"], "\n";
echo $path_parts["basename"], "\n";
echo $path_parts["extension"], "\n";
?>

Result:

/www/htdocs
index.html
html

Copies the file.
Syntax:

Bool copy(string $src, string $dst)

Copies a file named $src to a file named $dst. In this case, if the $dst file existed at the time of the call, it is overwritten.
The function returns true if the copying was successful, and false if the copying failed.
The function does not rename a file if its new name is located on a different file system (on a different mount on Unix or on a different drive on Windows).

Deleting a file.
Syntax:

Bool unlink(string $filename)

Deletes the file named $filename. If unsuccessful, returns false, otherwise true.
It should be noted that the file is deleted only if the number of “hard” links to it becomes equal to 0.
True, this scheme is specific to Unix systems.

Reads a file and splits it line by line.
Syntax:

List file(string $filename)

Reads the entire file named $filename and returns a list array, each element of which corresponds to a line in the file read.
The disadvantage of this function is that the end-of-line characters (usually n) are not stripped from the lines of the file, nor are they translated, as is done for text files.

move_uploaded_file()

Moves the downloaded file to a new location (PHP 4 >= 4.0.3, PHP 5)

Description:

Bool move_uploaded_file(string filename, string destination)

This function checks whether the file filename is uploaded to the server (transmitted via HTTP POST). If the file is actually uploaded to the server, it will be moved to the location specified in the destination argument.

If filename is not an uploaded file, no action is taken and move_uploaded_file() returns FALSE.

If filename is an uploaded file but cannot be moved for some reason, no action is taken and move_uploaded_file() returns FALSE. Additionally, a warning is displayed.

This check is especially important if there is a chance that any actions performed on the downloaded file could reveal its contents to the user or even other users of the system.

Note: move_uploaded_file() is not subject to normal safe mode UID restrictions. This is not a security breach because move_uploaded_file() only operates on files that are uploaded to the server via PHP. The move_uploaded_file() function takes both safe mode and open_basedir into account. However, restrictions are placed only on the destination parameter to allow downloaded files to be moved, since the filename parameter may conflict with these restrictions. move_uploaded_file() ensures the safety of this operation by only working on files that were uploaded via PHP.

Attention

If the destination file already exists, it will be overwritten.

ftruncate

Truncates the file.
Syntax:

Bool ftruncate(int $f, int $newsize)

This function truncates the open file $f to $newsize. Of course, the file must be opened in write-enabled mode.
For example, the following code clears the entire file:

Ftruncate($f,0);

highlight_file()

Output the contents of the file with color markings.

Syntax:

Boolean highlight_file(string filename);

The file name or path is specified in the argument. Syntax highlighting colors are defined in the PHP configuration file. Returns true or false on error.

For example, to force the Apache server, when receiving a request from a URL containing a value like "http://servername/source/path/to/file.php", to display a listing of the file "http://servername/source/path" /to/file.php", do the following. Add the following snippet to the httpd.conf file:

# Use the "ForceType" directive to specify
# that the value of source in the URL is not the directory, but the name of the PHP script

ForceType application/x-httpd-php

Create the following file in the root web directory named source:


Source Display

$script = getenv("PATH_TRANSLATED");
if(!$script) (
echo "
ERROR: Please provide a script name
";
) else (
if(ereg("(.php|.inc)$",$script)) (
echo "

File listing: $PATH_INFO

n
n";
if(!@highlight_file($script))
echo "File output error";
) else (
echo "

ERROR: Only PHP file listings are shown

";
}
}

echo "


Printed: ".date("Y/M/d H:i:s",time());


Immediately record all changes to a file.
Syntax:

Void fflush(int $f)

Causes PHP to immediately write to disk all changes previously made to the open file $f. What are these changes? The fact is that to improve performance, all writes to a file are buffered: for example, calling fputs($f, "This is a string!") does not directly write data to disk - they first go to an internal buffer (usually 8K in size). As soon as the buffer is full, its contents are sent to disk, and it itself is cleared, and everything repeats again. The benefit of buffering is especially felt in network operations, when it is simply stupid to send data in small portions.

set_file_buffer

Sets the buffer size.
Syntax:

Int set_file_buffer(int $f, int $size)

This function sets the buffer size mentioned above for the specified open file $f.
Most often it is used like this:

Set_file_buffer($f,0);

The following code disables buffering for the specified file, so that now all data written to the file is immediately sent to disk or the network.

Description:

Bool flock(resource handle, int operation [, int &wouldblock])

PHP supports a portable mechanism for locking entire files, which is a guideline (meaning that all programs accessing the file must use the same method of locking the file, otherwise the lock will not work).

Note: flock() is required on Windows.

flock() is applied to handle, which must be a pointer to an open file. The operation parameter can take the following values:

To set general locking (reading), set operation to LOCK_SH (or 1, in the case of PHP versions lower than 4.0.1).
- To set exclusive locking (write), set operation to LOCK_EX (or 2, in case of PHP version lower than 4.0.1).
- To unlock a file (after a general or exclusive lock), set operation to LOCK_UN (or 3, in the case of PHP versions lower than 4.0.1).
- If you don't want flock() to lock the file when locked, add LOCK_NB (or 4, if using a PHP version lower than 4.0.1) to the operation parameter.

flock() allows you to implement a simple read/write model that can be used on almost any platform (including most Unix-derived platforms, and even Windows). The optional third argument is set to TRUE if the lock is also blocking (error code EWOULDBLOCK). The lock is released using the same fclose() function (which is also automatically called when the script completes execution).

Returns TRUE on success or FALSE on error.

An example of using the flock() function

$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) ( // perform exclusive locking
fwrite($fp, "Writing something\n");
flock($fp, LOCK_UN); // unlock the file
) else (
echo "I can't lock the file!";
}
fclose($fp);
?>

Note: Because flock() requires a file pointer, you may need to use a special lock file to restrict access to the file you intend to clear by opening it in write mode (using "w" or " w+" as an argument to fopen()).

Attention

flock() will not work on NFS and many other network file systems. Consult your operating system's documentation for more information.

Some operating systems implement flock() at the process level. When using multi-threaded server APIs such as ISAPI, you cannot rely on flock() to protect your files from other PHP scripts that are running in a parallel thread on the same server!

flock() is not supported on older file systems like FAT and its derivatives, so will always return FALSE in that environment (this is especially true for Windows 98 users).

parse_ini_file()

Processes configuration file (PHP 4, PHP 5)

Description:

Array parse_ini_file(string filename[, bool process_sections])

parse_ini_file() loads the ini file specified in the filename argument and returns its settings as an associative array. By setting the last argument process_sections to TRUE, you get a multidimensional array that includes both the name of the individual settings and the sections. By default process_sections is FALSE

Notes:

This function has nothing to do with the php.ini file. By the time your script is executed, it has already been processed. This feature can be used to load your own application settings.
If the value in the ini file contains characters other than letters and numbers, it must be enclosed in double quotes (").
Since PHP 4.2.1, the behavior of this function is affected by safe mode and open_basedir.
Since PHP 5.0, this function also handles newlines in values.

There are reserved words that you cannot use as keys in ini files. These words are: null, yes, no, true and false.

The structure of the ini file is similar to the structure of php.ini.

Constants can also be parsed in the ini file, so if you declare a constant as a value for the ini file before calling parse_ini_file(), it will be parsed correctly. Only the values ​​are processed this way. For example:

Contents of sample.ini

; This is an example settings file
; Comments start with ";" as in php.ini


one = 1
five = 5
animal = BIRD


path = /usr/local/bin
URL = ""

An example of using the parse_ini_file() function

define("BIRD", "Dodo bird");

// Process without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Process with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

Result:

Array
=> 1
=> 5
=> Dodo bird
=> /usr/local/bin
=> http://www.example.com/~username
Array
=>Array
=> 1
=> 5
= Dodo bird
)

=>Array
=> /usr/local/bin
=> http://www.example.com/~username
)

Keys and section names consisting of numbers will be treated as integers in PHP, so numbers starting with 0 will be considered octal, and numbers starting with 0x will be hexadecimal.

disk_total_space()

Returns the size of a directory (PHP 4 >= 4.1.0, PHP 5)

Description:

Float disk_total_space(string directory)

The function returns the size in bytes of the specified disk partition.

Example of using disk_total_space()

// $df contains the size "/"
$df = disk_total_space("/");

// Under Windows:
disk_total_space("C:");
disk_total_space("D:");
?>

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

diskfreespace()

Alias ​​for the disk_free_space() function (PHP 3 >= 3.0.7, PHP 4, PHP 5)

Description: This function is an alias for the disk_free_space() function.

disk_free_space()

Get the size of available space in a directory (PHP 4 >= 4.1.0, PHP 5)

Description:

Float disk_free_space(string directory)

The function returns the amount of free space in bytes available for use on the specified disk partition.

An example of using the disk_free_space() function

$df = disk_free_space("/");
// $df contains the amount of free space in the "/" directory

// Under Windows:
disk_free_space("C:");
disk_free_space("D:");
?>

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

clearstatcache()

Clears file state cache (PHP 3, PHP 4, PHP 5)

Description:

Void clearstatcache(void)

When you use the stat(), lstat() functions, or any of the functions listed below, PHP caches the results of their execution to provide better performance. However, in some cases you may need to clear this cache. For example, when your script checks the status of the same file multiple times, which may be changed or deleted while the script is running.

Please note that PHP does not cache information about non-existent files. So if you call file_exists() on a file that doesn't exist, it will return FALSE until you create that file. If you create a file, it will return TRUE even if you then delete it.

Comment: The results of the below functions are cached by PHP, so if you don't want information about the file or directory you are working on to be cached, use the clearstatcache() function.

List of functions whose execution results are cached: stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime( ), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() and fileperms().

Creating a directory.
Syntax:

Bool mkdir(string $name, int $perms)

Creates a directory named $name with permissions perms. Permissions for directories are specified in the same way as for files. Most often, the $perms value is set to 0770 (the leading zero is required -
it tells PHP that this is an octal constant and not a decimal number).

Mkdir("my_directory",0755);
// creates a subdirectory in the current directorymkdir("/data");
// creates a data subdirectory in the root directory

Removing a directory.
Syntax:

Bool rmdir(string $name)

Removes the directory named $name.
The directory must be empty and its attributes must allow it.
If successful, the function returns true, otherwise - false.

Change the current directory.
Syntax:

Int chdir(string $directory);

Changes the current PHP directory to directory. Returns FALSE if it cannot change, TRUE if the change has occurred. The $directory parameter can also specify a relative path, specified from the current directory.
Examples:

Chdir("/tmp/data"); // go to absolute path
chdir("./js"); // go to a subdirectory of the current directory
chdir(".."); // go to the parent directory
chdir("~/data"); // go to /home/user/data (for Unix)

Returns the full path of the current directory

Syntax:

String getcwd()

This function returns the current directory relative to which file operations are performed, i.e. returns the full path to the current directory, starting from the root (/).

If such a path cannot be traced, the call fails and returns false.

diskfreespace

Determines free space in a directory
Syntax:

Float diskfreespace(string directory);

This function returns, in bytes, the free space in the directory directory, that is, in the corresponding file system or disk partition.
Example:

$diskspace=diskfreespace("/");
// Thus, we have determined the free space in the root directory "/"

chroot()

Change root directory (PHP 4 >= 4.0.5, PHP 5)

Description:

Bool chroot (string directory)

Changes the root directory of the current process to the directory passed as a parameter. Returns TRUE on success or FALSE on error.

This feature is only available if your operating system supports it and you are using the CLI, CGI, or Embed SAPI calling methods.

Comment

scandir()

scandir - Gets a list of files and directories located at the specified path

Description

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

Returns an array containing the names of files and directories located along the path passed in the directory parameter.

List of parameters

directory - The directory to be scanned.
sorting_order - By default, sorting is done in alphabetical order in ascending order. If the optional sorting_order parameter is set to SCANDIR_SORT_DESCENDING, the sorting is done in alphabetical descending order. If it is set to SCANDIR_SORT_NONE, then sorting is not performed.
context - For a description of the context parameter, see the Streams section of this manual.

Return values

Returns an array of file names on success or FALSE on error. If directory is not a directory, FALSE is returned and an E_WARNING error message is generated.

Example #1 A simple example of using the scandir() function

$dir = "/tmp";
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

The result of running this example will be something like this:

Array
=> .
=> ..
=> bar.php
=> foo.txt
=>somedir
Array
=>somedir
=> foo.txt
=> bar.php
=> ..
=> .
)

Example #2 Alternative scandir() function for PHP 4

$dir = "/tmp";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) (
$files = $filename;
}

print_r($files);

print_r($files);

The result of running this example will be something like this:

Array
=> .
=> ..
=> bar.php
=> foo.txt
=>somedir
Array
=>somedir
=> foo.txt
=> bar.php
=> ..
=> .
)

Notes

For this feature, you can use the URL as the filename if the fopen wrappers option has been enabled.

Directory class (pseudo-object-oriented mechanism).

Syntax:

New dir(string directory);

A pseudo-object-oriented mechanism for obtaining a list of directory files. Opens a directory from directory.
After this, two properties of the object become available: a handle to the handle directory and a path string indicating which directory is currently in use. These properties are only available if the directory has been opened.
The handle property can be used in conjunction with other directory functions such as readdir(), rewinddir() and closedir().

There are three methods available for the class: read, return to the beginning and close (read, rewind and close, respectively).

$d = dir("/etc");
echo "Handle: ".$d->handle."
n";
echo "Path: ".$d->path."
n";
while($entry=$d->read()) ( // Output sequentially
echo $entry."
n"; // name of each file,
) // available in the directory$d->close();

closedir

Close the directory handle.
Syntax:

Void closedir(int dir_handle);

Closes the directory stream identified by dir_handle. The stream must first be opened by the opendir() function.

Open directory handle.
Syntax:

Int opendir(string path);

Returns a handle to the open directory path, which is subsequently used in the closedir(), readdir(), and rewinddir() functions.

Get the name of the next file in a directory listing.
Syntax:

String readdir(int dir_handle);

Returns the name of the next file in a directory. The file names are returned as an unordered sequence.
Example:

$handle=opendir(".");
echo "Directory handle: $handlen";
echo "Files:n";
while ($file = readdir($handle)) (
echo "$filen";
}
closedir($handle);
?>

It should be noted that the function also returns "." And "..".

If these values ​​are not required, they can be excluded as follows:

$handle=opendir(".");
while($file=readdir($handle)) (
if($file != "." && $file != "..") (
echo "File name: $file
";
};
};
closedir($handle);
?>

rewinddir

Reinitialize the directory handle.
Syntax:

Void rewinddir(int dir_handle);

After calling this function, the readdir() function with the dir_handle argument will return the file names from the beginning in the directory listing.

Changes the owner group of a file (PHP3, PHP4, PHP5)

Description:

Bool chgrp (string filename, mixed group)

The function attempts to change the owner group of a file named filename to the group specified in the group parameter (as a name or number). Only the superuser can arbitrarily change the group of a file; a normal user can change the group of a file to any of the groups to which the user belongs.

Returns TRUE on success or FALSE on error.

Note: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment

Changes the access mode of a file or directory (PHP 3, PHP 4, PHP 5)

Description:

Bool chmod (string filename, int mode)

Attempts to change the access mode of a file or directory passed in the filename parameter to the mode passed in the mode parameter.

Note that the mode parameter value is not automatically converted to octal, so strings (such as "g+w") will not work as expected. To ensure that the mode has been set correctly, precede the value passed in the mode parameter with a zero (0):

chmod("/somedir/somefile", 755); // decimal, wrong way
chmod("/somedir/somefile", "u+rwx,go+rx"); // string, wrong method

?>

The value of the mode parameter consists of three octal numbers that determine the access level for the owner of the file, for the group to which the owner belongs, and for other users, respectively. The number that determines the user level can be calculated by summing the values ​​that determine the rights: 1 - execute access, 2 - write access, 4 - read access. You can learn more about the rights system in Unix systems using the commands "man 1 chmod" and "man 2 chmod".

// Write and read access for owner, no access for others
chmod("/somedir/somefile", 0600);

// Write and read access for owner, read access for others
chmod("/somedir/somefile", 0644);

// Full access for the owner, read and execute access for others
chmod("/somedir/somefile", 0755);

// Full access for the owner, read and execute access for the owner group
chmod("/somedir/somefile", 0750);
?>

Returns TRUE on success or FALSE on error.

Comment: The current user is the user under whom PHP is running. It is possible that this user will be different from the user you use to access your command shell or FTP account.

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment: When safe mode is enabled, PHP checks to see if the file or directory you are working on has the same UID as the script being executed. Additionally, you cannot set SUID, SGID, or sticky bits.

Changes the owner of a file (PHP 3, PHP 4, PHP 5)

Description:

Bool chown (string filename, mixed user)

Attempts to change the owner of a file named filename to the owner whose name is passed in the user parameter (as a number or string). Only the superuser can change the owner of a file.

Returns TRUE on success or FALSE on error.

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment: When the safe mode option is enabled, PHP checks if the files/directories you are about to work with have the same UID (owner) as the script being executed.

lchgrp()

Changes the owner group of a symbolic link

Description:

Bool lchgrp(string filename, mixed group)

Only the superuser can arbitrarily change the group of a symbolic link; other users can only change the group to the group of which that user is a member.

Returns TRUE on success or FALSE on error.

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment: When the safe mode option is enabled, PHP checks if the files/directories you are about to work with have the same UID (owner) as the script being executed.

lchown()

Description:

Bool lchown (string filename, mixed user)

Tries to change the owner of a symbolic link filename to user user (specified by name or number). Only the superuser can change the owner of a symbolic link.

Returns TRUE on success or FALSE on error.

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment: When the safe mode option is enabled, PHP checks if the files/directories you are about to work with have the same UID (owner) as the script being executed.

Changes the current umask (PHP 3, PHP 4, PHP 5)

Description:

int umask()

Sets PHP's umask() to mask & 0777 and returns the old umask. If PHP is used as a server module, the umask is restored after each request completes.

Calling umask() without arguments will return the current umask.

General information

Hard links allow you to have several completely equal names for one file, and access them equally quickly. Moreover, if one of these names is deleted, then the file itself will be deleted only if this name was the last one and the file has no other names.

You can register a new name for a file (that is, create a hard link for it) using the link() function.

Its syntax is completely identical to the symlink() function, and it works according to the same rules, except that it creates a hard link rather than a symbolic one.

Description:

Bool link(string target, string link)

Comment: This feature is not applicable to working with remote files because the file must be accessible through the server's file system.

Comment: This function is not implemented for Windows platforms.

linkinfo()

Description:

Int linkinfo(string path)

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. This function is used to determine whether a link (pointed to by path) actually exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE on error.

Example of using the linkinfo() function

echo linkinfo("/vmlinuz"); // 835
?>

Comment: This function is not implemented for Windows platforms.

General information

On Unix systems, it is quite common to have different names for the same file or directory. In this case, it is logical to call one of the names the main one, and all the others - its pseudonyms. In Unix terminology, such aliases are called symbolic links.

A symbolic link is simply a special kind of binary file that contains a link to the main file. When accessing such a file (for example, opening it for reading), the system “realizes” what object access is actually being requested and transparently provides it.

This means that we can use symbolic links just like regular files. However, sometimes you need to work with a link exactly as a link, and not as a file. There are special PHP functions for this.

Gets information about a file or symbolic link (PHP 3 >= 3.0.4, PHP 4, PHP 5)

Description:

Array lstat (string filename)

Collects statistics on a file or symbolic link named filename. This function is identical to the stat() function, except that if filename is a symbolic link, the status of the symbolic link is returned rather than the file it points to.

Refer to the man page of the stat() function for information about the structure of the array that lstat() returns.

Comment: The results of this function are cached. See clearstatcache() for more information.

As of PHP 5.0.0, this feature can also be used with some url packers.

readlink()

Returns the file pointed to by a symbolic link (PHP 3, PHP 4, PHP 5)

Description:

String readlink (string path)

readlink() does the same thing as the C readlink function - returning the contents of the symbolic link path or FALSE on error.

Example of using the readlink() function

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink("/vmlinuz");

Comment: This function is not implemented for Windows platforms.

symlink()

Description:

Bool symlink (string target, string link)

Returns TRUE on success or FALSE on error.

Comment: This function is not implemented for Windows platforms.

Working with files

The need for operations with files confronts the programmer very often. If your scripts do not use databases, then files are the only acceptable storage devices for the script. The use of files as repositories of script execution information allows them to be used in a wide variety of situations. Almost all counter scripts for something are written based on working with files. It is also possible to give a bunch of other examples, but it’s time to move directly from words to action.

I want to say right away that working with the file must be authorized. By default, PHP does not allow file manipulation for security reasons. To remove this ban in the CuteFTP FTP manager, check all the boxes in the file properties; other managers should have something similar.

file_exists

Before you perform operations on a file, you often need to make sure that the specified file even exists. This is what the file_exists function does. This function can only return two values, as you can imagine TRUE(if the specified file exists) and FALSE. Typically, using this function looks like this:

Please note that the function only works on local files, that is, if you want to check whether Yandex has acquired a robot.txt file, then your efforts will be in vain. But it is possible to check any file located on the local server, regardless of the directory of its location.

Here are some rules for describing the path to a file.

filesize

As the name suggests, the function determines the file size and returns it in bytes. Useful if you want to check a file to see if it contains information (as you might imagine, an empty file contains 0 bytes), and it is also possible to check the file size to see if it exceeds a certain limit.

file

This function already works directly with the file. It returns the contents of the specified file, and it does this in the form of an array, where each element is a line of the file. The function is useful when you need to store several different values ​​in one file that should not intersect. Then each value is stored on a separate line and read by the file function, which returns an array, so that the given variable is accessed by reading the value of the array element with the index corresponding to the line in the file.

It is also possible to reunite all elements of the returned array into a single variable. This is done using the implode array function.

fopen

If the previous function is self-contained and generally not related to other functions, then subsequent functions for working with files work in conjunction with fopen . This function opens the specified file and returns the file connection identifier, which is used for service purposes. This function is in no way associated with the contents of the file.

The fopen function has several modes for working with a file. They are indicated after the file name and are as follows:

    "r"
    The file is opened for reading its contents only.

    "r+"
    Opening a file for both reading and writing.

    "w"
    The file is opened for writing purposes.

    "w+"
    Open the file for reading and writing.

    "a"
    The file is opened for writing to the end of the file (append).

    "a+"
    Opens for further writing and reading.

fgets

Function for reading a file opened by the fopen function. But unlike file, this function returns only one line of the file each time it is executed, and it moves the internal file pointer to the next line, which it will read the next time the function is called. Therefore, if you need to read the entire file, you must use this function in a loop.

Note that the fgets function uses an additional length parameter, which specifies the maximum length of a file line to read. If the size of the string exceeds this number, then the function will return it in a “truncated” form of length bytes. By default, this parameter is set to 1024 bytes, or one kilobyte. Especially pay attention to this parameter if you use large files, since when reading such files, the PHP execution buffer may overflow (its size is indicated in the configuration file), which will lead to a freeze.

Note that the file to read is not the file name, but the file connection identifier returned by the fopen function (in our example, the value of the $file variable).

fputs

The function of writing information to a file, and it does this according to the principle of operation of the fgets function, that is, it starts writing from the position of the internal file pointer. In general, this function is in many ways similar to the above: it also uses the write data length parameter, which is also optional.

fclose

As you might have guessed, this function closes the specified file. Actually, upon completion of the script, PHP itself closes all open files, but it is still better to do this manually. As a function parameter, you must specify the file connection identifier.

To illustrate the combination of the above functions, we will give an example of creating a simple visit counter.

$file = fopen("counter.txt", "r");
$c = fgets($file, 150);
fclose($file);
$c++;
$file = fopen("counter.txt", "w");
fputs($file, $c);
fclose($file);
echo $c;
?>

Working with directories

Closely related to actions on files are operations on directories. The algorithm for working with them is similar to operations on files: first you need to open the directory, perform some actions and, finally, close it.

opendir

This function opens the specified directory and returns the service identifier for the directory connection. Directory paths should be specified as follows:

The dot means opening the current directory

. /files/

Opening a folder files located in the current directory

Opening a folder one level higher than the current one

readdir

The function reads the directory opened by opendir . For each pass, it returns the name of the file or folder located in the specified directory and moves the internal pointer to the next directory object. So to read the entire directory it must be used in a loop.

It should also be noted that this function returns folder service objects . And .. , which can be trimmed when output by the IF statement.

closedir

We close the directory, specifying the folder connection identifier as an argument.

Sometimes using directory functions makes life a lot easier. For example, in the Features section, you can see a list of features in alphabetical order. Can you imagine how much time it would take to manually write this entire list with links, and even in alphabetical order. And this is where the functions for working with directories helped me. Each function was placed in a separate file with a name corresponding to the name of the function, without any extensions.

So, every time you visit the page, you get a newly generated list of functions.

That's all. See you in the next lesson.

We are already with you. And now I decided to touch on the topic working with directories in PHP. In this article you will learn create directories in PHP, delete them and read files and subdirectories from them.

Let's start with the simplest: creating a directory in PHP:

mkdir("new_dir");
?>

After running this script, you will have an empty directory created " new_dir".

Deleting an empty directory is very simple. For this purpose it is used rmdir() function.

rmdir("new_dir");
?>

Now let's move on to working with directory contents via PHP. There are very simple rules that must be followed. All these rules are very logical, and you apply them when manually browsing the contents of directories:

  1. Open directory.
  2. Read contents.
  3. Close directory.

In order not to torment you with waiting, I will immediately give the code that displays the names of files and categories inside a given directory:

$dir = opendir("images");
while (($f = readdir($dir)) !== false)
echo $f."
";
closedir($dir);
?>

As a result, you will see a list of all files and directories inside the directory " images"You will also see two interesting names" . " And " .. ". The first means " current directory", A " .. " - parental.

Now details about the functions used in this example:

  • Function opendir(string $path)- opens a directory located along the path $path, and also returns the handle needed to work with this directory.
  • Function readdir(resource $dir)- reads the current element in the directory dir. The current element is specified by a pointer that is moved each time it is called. Therefore, it turns out that each time this function returns a new element from the directory. When all the elements are gone, then readdir() function returns false.
  • Function closedir(resource $dir)- closes the directory dir.

These are all the most important functions for working with directories in PHP. However, I would like to add one more very important detail regarding rmdir() functions, which deletes the directory. If you read carefully, I wrote that this function deletes " empty directory", that is, in which there is not a single file and directory (except " . " And " .. "). In other words, if there is at least one file in the directory, then rmdir() function will not work. You will learn how to solve this problem in the next article, so subscribe to updates so as not to miss its appearance.







2024 gtavrl.ru.