Eight common file operations in PHP programming

Source: Internet
Author: User

File and directory operations
PHP is very convenient to process files and directories on the local server, but sometimes the permission and path problems may occur.
1. open the file
Resource fopen (string filename, string mode [, bool use_include_path [, resource zcontext])
$ Handle = fopen (filename, mode) // open the file and return a handle representing the resource of the file
The file name can be in relative or absolute or network protocol mode. The open mode can be r \ r + \ w + \ a + \ x + \ B.
If the 'B' flag is not specified when operating the binary file, some strange problems may occur, including bad image files and strange problems about \ r \ n characters.
For portability considerations, we strongly recommend that you always use the 'B' flag when opening a file with fopen.
There are several ways to open files:
$ 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, which must enable the allow_url_fopen option in the php. ini file
/// // Code ////////// //////////////////////////////
$ Filename1 = "userinfo.txt"; // The file exists in the directory or in include_path.
$ Filename2 = "test.txt"; // the file does not exist in the directory or in include_path.
$ Resource1 = fopen ($ filename1, "rb ");
@ $ Resource2 = fopen ($ filename2, "rb"); // This operation returns an error because the file does not exist in the directory and is not used or because de_path is used to find the path containing the file, use the error blocker @ to force the browser not to output error messages
If ($ resource1)
Echo "opening file {$ filename1} succeeded ";
If (! @ Fopen ($ filename2, "r "))
Echo "opening file {$ filename2} failed ";
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------
The userinfo.txt file is successfully opened.

---------------------------------------------------------------------
2. After using the file, you must explicitly tell PHP that the file has been used, so that the operating system can ensure that all the content of the file is correctly refreshed from the buffer to the hard disk.
Use fclose () to close the file,
Bool fclose (resource handle) // close an opened file pointer
3. Read files. The mode parameter of the fopen function can be read. PHP provides several functions to read data from files.
String fgets (int handle [, int length]) reads a row from the file pointer. If you try fgets in a binary file, unpredictable results are generated.
If the length is not specified, 1 k of data is read by default, and stops when a line break (including in the returned value), EOF, or length-1 bytes have been read.
String fgetss (resource handle [, int length [, string allowable_tags]) read a row from the file pointer and filter out the HTML Tag
Fgetc () reads a single character
Fread () reads arbitrary binary data
/// // Code ////////// //////////////////////////////
$ Handle = fopen ("test.jpg", "rb ");
$ C;
While (! Feof ($ handle )){
$ Contents. = @ fread ($ handle, 8192); // read it cyclically and merge it into a large file.
}
Fclose ($ handle );
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------

---------------------------------------------------------------------
4. Determine the File Reading status
Each file handle has a file pointer, or a cursor indicating 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 be used to determine whether the object has reached the end (the function returns TRUE after the end)
Filesize () function returns the size of the file 5. Write the file
Fwrite () function execution file write
/// // Code ////////// //////////////////////////////
$ Filename = 'test.txt ';
$ Somec;
// First, make sure that the file exists and is writable.
If (is_writable ($ filename )){
// In this example, we will use the Add mode to open $ filename,
// Therefore, the file pointer will start with the file,
// That is where $ somecontent will be written when we use fwrite.
If (! $ Handle = fopen ($ filename, 'A ')){
Echo "the file $ filename cannot be opened ";
Exit;
}
// Write $ somecontent to the open file.
If (fwrite ($ handle, $ somecontent) === FALSE ){
Echo "cannot be written to file $ filename ";
Exit;
}
Echo "successfully writes $ somecontent to the file $ filename ";
Fclose ($ handle );
} Else {
}
Echo "File $ filename cannot be written ";
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------
The text is successfully added to the file and written to the file test.txt.
---------------------------------------------------------------------
For binary data, the third parameter must be specified, which contains the number of data bytes written to the disk.
$ Result = @ fwrite ($ fp, $ binary_data, mb_strlen ($ binary_data, '8bit '));
6. File permissions and other information
Is_readable () // checks whether the object is readable.
Is_writeable () // determines whether a file can be written.
Is_writable () // determines whether a file can be written.
Fileperms () // determine the File Permission (UNIX-Style File Permission test function)
File_exists () // whether the file exists
Fileowner () // determines the user to which the file belongs
Filegroup () // determine the group to which the file belongs
7. Delete and rename an object
Unlink () // delete an object
Rename () // rename the file
8. Access the Directory
Forward slash (/) is recommended for directory access. It is compatible with windows and unix systems.
Basename () // returns the file name that does not contain the path information
Dirname () // return the directory part of the file name
Realpath () // accepts the relative path and returns the absolute path of the object.
Pathinfo () // extract the directory name, basic file name, and extension of the specified path
Opendir () // open the Directory and return the resource handle
Readdir () // read the directory item
Rewinddir () // returns the start of the read pointer
Closedir () // close the read handle
Chdir () // change the current working directory during the execution of the current script
Mkdir () // create a directory
Rmdir () delete directory
/// // Code ////////// //////////////////////////////
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------

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.