Eight common methods of file operation in PHP programming _php tips

Source: Internet
Author: User
Operation of files and directories
PHP is very handy for processing files and directories on the local server, but sometimes permissions and path-related issues occur
1. Open the file
Resource fopen (string filename, string mode [, bool Use_include_path [, Resource Zcontext]])
$handle = fopen (filename,mode)/Open file, return handle to resource representing this file
The file name can use a relative path or an absolute path, or you can use the network protocol mode, which is open with r\r+\w\w+\a\a+\x\x+\b
If you do not specify ' B ' tags when manipulating binaries, you may encounter some strange problems, including bad picture files and strange questions about the \ r \ n characters.
For portability reasons, it is strongly recommended that you always use the ' B ' flag when you open a file with fopen ().
Here are a few ways to open a file
$fp = @fopen (' Log.txt ', "RB");
$fp = @fopen ('.. /log.txt ', "RB");
$fp = @fopen ("http://www.runer.com.cn/default.htm", "RB");//You can also use protocols such as FTP and Ghoper, and you must enable the Allow_url_fopen option in php.ini files
Code section////////////////////////////////////////
$filename 1 = "userinfo.txt";//the file exists in the directory or include_path
$filename 2 = "test.txt";//directory or include_path does not exist in this file
$resource 1 = fopen ($filename 1, "RB");
@ $resource 2 = fopen ($filename 2, "RB");//Because this file does not exist in the directory and does not use or include_path to find the path where the containing file is located, this action will error, and using the error suppressor @ can force the browser not to output error messages
if ($resource 1)
echo "Open file {$filename 1} succeeded";
if (! @fopen ($filename 2, "R"))
echo "Open file {$filename 2} is unsuccessful";
//////////////////////////////////////////////////////////////////////////
---------------------Output----------------------------------------
Open File Userinfo.txt Successful

---------------------------------------------------------------------
2. After using the file, to explicitly tell PHP to use the file, let the operating system ensure that all the contents of the file are correctly flushed from the buffer to the hard disk
Use Fclose () to close the file,
BOOL Fclose (resource handle)//close an open file pointer
3. Read the file, the fopen function mode parameter allows reading, PHP provides several functions to read data from the file
string fgets (int handle [, int length]) reads a row from a file pointer, and attempting fgets on a binary file can produce unpredictable results
If no length is specified, the default reads 1K data, stops when a newline character is encountered (including in the return value), EOF, or the length-1 byte has been read
String FGETSS (resource handle [, int length [, string allowable_tags]]) reads a row from the file pointer and filters out the HTML markup
FGETC () reads a single character
Fread () read arbitrary binary data
Code section////////////////////////////////////////
$handle = fopen ("Test.jpg", "RB");
$c;
while (!feof ($handle)) {
$contents. = @fread ($handle, 8192);//loop Read and merge it into a large file
}
Fclose ($handle);
//////////////////////////////////////////////////////////////////////////
---------------------Output----------------------------------------

---------------------------------------------------------------------
4. Determine the state of the file read
Each file handle has a file pointer, or a cursor that indicates where the next operation will occur in the file, according to the mode parameter of the fopen function
The file pointer is initially at the beginning of the file (0), or at the end of the file
Feof () can determine whether the file is at the end (the function returns true after the end)
The FileSize () function returns the size of the file 5. Write to File
Fwrite () function performs file writes
Code section////////////////////////////////////////
$filename = ' test.txt ';
$somec;
First we want to make sure that the file exists and can be written.
if (is_writable ($filename)) {
In this example, we'll use the Add mode to open the $filename,
Therefore, the file pointer will be at the beginning of the file,
That's when we use Fwrite (), where $somecontent will be written.
if (! $handle = fopen ($filename, ' a ')) {
echo "Cannot open file $filename";
Exit
}
Write the $somecontent to the file we opened.
if (fwrite ($handle, $somecontent) = = FALSE) {
echo "cannot be written to the file $filename";
Exit
}
echo "successfully writes the $somecontent to the file $filename";
Fclose ($handle);
} else {
}
echo "File $filename not writable";
//////////////////////////////////////////////////////////////////////////
---------------------Output----------------------------------------
The text added to the file was successfully written to the file Test.txt
---------------------------------------------------------------------
For binary data, you must specify a third parameter that contains the number of bytes of data written to disk
$result = @fwrite ($fp, $binary _data,mb_strlen ($binary _data, ' 8bit '));
6. File permissions and other information
Is_readable ()//To determine whether the file is readable
Is_writeable ()//To determine whether the file can be written
Is_writable ()//To determine whether the file can be written
Fileperms ()//To determine file permissions (Unix-style file permissions test function)
File_exists ()//whether this file exists
Fileowner ()//To determine the user to whom the file belongs
Filegroup ()//To determine the group to which the file belongs
7. Delete and rename files
Unlink ()//delete file
Rename ()//rename file
8. Access to the directory
Directory Access recommended forward slash "/", compatible with Windows and UNIX systems
BaseName ()//returns a filename that does not include path information
DirName ()//Returns the directory portion of the file name
Realpath ()//Accept the relative path, return the absolute path of the file
PathInfo ()//Fetch directory name, base file name and extension for given path
Opendir ()//Open Directory, return resource handle
Readdir ()//Read directory entries
Rewinddir ()//Returns the read pointer to the beginning
Closedir ()//close Read handle
ChDir ()//change current working directory during current script execution
mkdir ()//Create Directory
RmDir () Delete directory
Code section////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
---------------------Output----------------------------------------

Filename:web:filetype:dir

Filename:study:filetype:dir

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.