PHP file system details _ PHP Tutorial

Source: Internet
Author: User
Php file system details. File processing function 1. file operations. open a file: when a specified file is opened, the corresponding object is returned. If no specified file exists, the file may be automatically created. Resource file processing functions
1. file operations.
Open the file:
When a specified file is opened, the corresponding object is returned. if the specified file does not exist, the file may be automatically created.
Resource fopen (string filename, string mode [, int use_include_path] [, resource context]);
Filename can be a file name that contains the file path, or a URL provided by a protocol (open a remote file). to avoid the trouble of system switching, use '/' as the path separator.
Mode: sets the file opening methods, including:
R: Read-only mode. the file pointer is located in the file header.
R +: Read-only mode ---- read/write mode. the file pointer is located in the header file. Note that overwriting may occur.
W: Write-only mode. the file pointer is located in the file header. if the file exists, delete the content and rewrite it. otherwise, create the file on your own.
W +: Write-only mode ---- read/write files. the pointer to the read/write file points to the file header. if the file exists, delete the file and rewrite it. otherwise, create the file on your own.
X: write with caution ---- open the file in write mode, and write the file from the file header. if the file exists, false is returned to generate an E_WARNING-level error message.
X +: write with caution --- open the file in read/write mode. if the file exists, false is returned and an error message at the E_WARNING level is generated.
A: append. the file pointer points to the end of the file. if the file exists, append the file directly. otherwise, create the file on your own.
A +: append. the object pointer points to the end of the object. if the object exists, append or read the object directly. otherwise, create the object by yourself.
B: Binary mode. used to connect to other modes. (windows option)
T: used in combination with other modes. (option in windows)
Use the fopen () function with caution, because the file may be deleted accidentally. at the same time, different operating systems have different row ending habits (UNIX: \ n Windows: \ r \ n Macinitosh: \ r ). if the row Terminator is incorrect, a bunch of garbled characters may be output when the file is opened. the preceding steps can be avoided through "'T'" and "'B.
Read files:
String fgetc (resource handle); // returns a character in the file pointed to by handle. if EOF is encountered, false is returned;
String fgets (int handle [, int length]); // gets a line of characters from the position pointed to by the file pointer, and returns a string of up to length-1 bytes .. the file pointer must be valid and point to a file successfully opened by fopen () or fsockopen. length indicates the length of the data to be read. it ends when a line break, EOF, or length is specified. ignore length to read the end of the row.
String fgetss (resource handle [, int length] [, string allowable_tags]); // read a row and filter out html and php tags.
String fread (int handle, int length); // read data of any length from the file ., It can also be used to read binary files. Handle is the resource pointing to the file. length reads length bytes or stops execution when an EOF occurs.
Example:

The code is as follows:


$ Filename = "./files. text ";
$ Fp = fopen ($ finename, "rb ");
$ Encho fread ($ fp, 100 );
?>


Readfile (), file () and file_get_contents () functions.
Readfile (), file () and file_get_contents () functions.
Int readfile (string filename [, bool use_include_path, resource context]); // reads a file and writes it to the buffer zone. if successful, the number of bytes is returned. otherwise, false is returned. Filename file name. The use_include_path parameter controls whether File Search in include_path is supported. true indicates yes. You do not need to open or close a file when using the readfile function.
Array file (string filename [, bool use_include_path [, resource context]); // read the content of the entire file to the array. If the operation succeeds, an array is returned. each element in the array is a line corresponding to the file, including the line break. otherwise, false is returned;
String file_get_contents (string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]); // The context value is 5.0, NULL can be used to ignore the error. Offset and maxlen is 5.1. Offset is used to mark the start position of a file, and maxlen sets the length of the file to be read. This method is applicable to reading binary files. Is the preferred method to read the file content into a string. If supported by the operating system, the memory ing technology will be used to enhance the performance. If you open a URL with special characters (such as spaces), use urlencode () for URL encoding.

Note: When readfile (), file (), and file_get_contents () are reading the content in the entire folder, the fopen () and fclose () functions are not required, but one character is being read, A line of characters and any length of characters must be used.

2. write files:
Int fwrite (resource handle, string [, int length]); // execute the file write operation. it also has an alias fputs (). this method is used to write the string content to the handle of the file pointer. If you set the length, the operation stops after writing length bytes or writing string. True is returned if the write operation is successful. otherwise, false is returned.
Note: If the length parameter is given, the magic_quotes_runtime option in the php. ini file will be ignored, and the diagonal lines in the string will not be extracted. To distinguish between a binary file and a text file system, 'B' must be added to the mode parameter of the fopen () function when the file is opened '.
Int file_put_contents (string filename, string data [. int flags [, resource context]); // write a string to the file. if the string is successful, the number of bytes is returned. otherwise, false is returned. Flags: to lock the file (the options include file_use_include_path, file_append: append, lock_ex: locked independently ). A context resource.
Note: Although fwrite () can write files, it must support both fopen () and fclose () functions. File_put_contents () integrates the fopen (), fwrite (), and fclose () functions to write files separately.
3. close the file
If the file is opened, the function should be disabled. after the file operation is completed, the file should be closed; otherwise, an error may occur.
Bool fclose (resouce handle); // close the file to which the handle parameter points. if the handle parameter is successful, true is returned. otherwise, false is returned.

Lock file
When writing data to a text file, you must first lock the file to prevent other users from modifying the file content at the same time. Use the flock () function in php to lock files.
Bool flock (int handle, int operation); // The operation parameter controls the lock permission. Including: lock_sh: Get Share Lock (read program ). Lock_ex: get the unique token lock (write ). Lock_un: release the lock. Lock_nb: Prevents The flock () function from being blocked during the lock.

Directory processing functions
A directory is a special object. Since it is a file, if you operate it, you must first open it before you can browse it, and finally remember to close it.

1. open the Directory

Open the specified directory file. if the file is successfully opened, the directory handle is returned. Otherwise, false is returned. Unlike opening a file, if the directory does not exist, it does not automatically create a directory, but throws an error message. You can add the "@" symbol before the opendir () function to shield the output of error messages.
Resource opendir (string path [, resource context]); // path specifies the directory file to be opened. If the path is not a valid directory or the file system cannot be opened due to permission issues, the function returns false and generates an E_WARNING error message.

2. Browse directory


Use the handle returned by the opendir function and the scandir function for browsing.
Array scandir (string directory [, int sorting_ordering [, resource context]); // used to browse directories and files in a specified path. If the operation succeeds, an array containing the file name is returned. otherwise, false is returned. Directory specifies the directory to be browsed. if it is not a directory, false is returned and an error message at the E_WARNING level is generated. Sorting_order is used to set the sort order. by default, the sort order is ascending. If this parameter is set, it is sorted in descending order.
Note: The is_dir () function determines whether the specified file name is a directory. If the file name exists and is a directory, true is returned; otherwise, false is returned. If it is a relative directory, check its relative path according to the current working directory.

3. close the directory.

Void closedir (resource handle); // handle, the handle of the working directory to be closed.

Note: We have learned that if the opened directory does not exist, the system will not create a directory for us. Then we can create the desired directory on our own. You can apply the following functions:
Mkdir () function: Creates a directory. if the directory is created successfully, true is returned. otherwise, false is returned.
Rmdir () function: Delete a directory. The directory must be empty (the directory does not contain files or subdirectories) and must have operation permissions.
Unlink () function: delete an object. if the object is successfully deleted, true is returned. if the object fails, false is returned.

Principles of file upload and download 
       
Steps:
Step 1: control the Upload file configuration through the php. ini file.
Step 2: determine the uploaded file. The size and format of the uploaded file.
Step 3: perform file upload operations.

1. Control file upload:

Php controls the file to be uploaded by using php. ini, including: whether the file can be uploaded, the temporary directory of the file to be uploaded, the size of the file to be uploaded, the execution time of the command, and the memory space allocated by the command.
Locate the file uploads option in the php. ini file to complete the settings of the above options. The options are as follows:
File_uploads: if it is on, the server supports file upload. if it is off, it does not. This option is generally supported by default and does not need to be modified.
Upload_tem_dir: temporary directory of the uploaded file. Before the file is uploaded successfully, the file is saved in the temporary directory of the server. Most of them use the default system directory, but you can also set it yourself.
Upload_max_filesize: maximum size of files that can be uploaded by the server, in MB. The default value is 2 MB. if the value is exceeded, modify the value.
Max_execution_time: maximum time for executing a command in php, in seconds. This command must be modified when uploading a large file. Otherwise, the file will be uploaded within the permitted range of the server in time. However, if the maximum time allowed by the command is exceeded, the file cannot be uploaded.
Memory_limit: memory space allocated by a command in php, in MB. The size of the file also affects the upload of large files.

Note: The enctype and method attributes in the form when the file is uploaded to the application are controlled on the client, and the MAX_FILE_SIZE domain is hidden.
Enctype = "multipart/form-data": specifies the form encoding data method.
Method = "post": specifies the data transmission mode.
     : Controls the size of the uploaded file by hiding the domain, in bytes. The value cannot exceed the value set by the upload_max_filesize option in the php. ini configuration file. It cannot completely control the size of the uploaded file, but can only avoid unnecessary troubles.

2. determine the file to be uploaded

The global variable $ _ FILES and $ _ FILES are used to determine the uploaded FILES. they are an array that contains information about all uploaded FILES. The meaning of each element in the array is as follows:
$ _ FILES [filename] [name]: the name of the file stored on the file, such as text.txtand title.jpg.
$ _ FILES [filename] [size]: the size of the stored file, in bytes.
$ _ FILES [filename] [tem_name]: name of the file used to store the file in the temporary directory, because the file must be stored in the temporary directory as a temporary file before being uploaded.
$ _ FILES [filename] [type]: the MIME type used to store uploaded FILES. MIME specifies the types of various file formats. each MIME type is composed of the primary and child types separated. For example, the main type of "image/gif" is image, and the child type is GIF file. "Text/html" indicates the HTML file of the text.
$ _ FILES [filename] [error]: error code for storing file uploads: This project is added to PHP4.2.0. The returned values include:
0: indicates no error. The file is uploaded successfully.
1: indicates that the size of the uploaded file exceeds the limit of the upload_max_filesize option in the configuration file command.
2: The size of the uploaded file exceeds the value specified by the max_file_size option in the HTML form.
3: indicates that only part of the file is uploaded.
4: indicates that no files have been uploaded.
Example:

The code is as follows:


/* Determine whether an image is uploaded */
If (! Empty ($ _ FILES ['up _ picture '] [name]) {
/* Assign the image information to the variable */
$ Type = strtolower (strstr ($ _ FILES ['up _ picture '] [name], ".");
If ($ type! = '.Jpg '& $ type! = '.Gif ') echo "the format of the file you uploaded is incorrect ";
Else {
If ($ _ FILES ['up _ picture '] [size] <2000000 & $ _ FILES ['up _ picture'] [size]> 0 ){
Echo "Upload file name:". $ _ FILES ['up _ picture '] [name]."
";
Echo "Upload file type:". $ type ."
";
Echo "Upload file size:". $ _ FILES ['up _ picture '] [size]."
";
} Else echo "the image size does not meet the requirements. ";
}
}
?>



3. file upload.

Use the move_uploaded_file () function in php to upload files. However, before execution, to prevent potential attacks from illegally managing files that could not be interacted with by scripts, you can use the is_uploaded_file () function to determine whether the specified file was uploaded through http post, if yes, true is returned. This function prevents malicious users from spoofing scripts to access files that cannot be accessed.
Bool is_uploaded_file (string name); // used to determine whether the specified file is uploaded through http post. Filename must be a variable similar to $ _ FILES ['filename'] ['temp _ name, you cannot use the file name $ _ FILES ['filename'] ['name'] uploaded from the client.

Move_upload_file (string filename, string destination); // This function is used to upload files to the specified location on the server. If yes, true is returned. otherwise, false is returned. Filename specifies the temporary file name to be uploaded, that is, $ _ FILES ['tmp _ name']. the destination parameter specifies the new path and name to save after the file is uploaded. If the parameter is not valid for file upload, no operation is performed. This function returns false. If it is a legal Upload operation but cannot be moved for some reason, no operation will occur. if it returns false, a warning will be issued.

The code is as follows:


If (! Empty ($ _ FILES ['up _ picture '] ['name']) {
If ($ _ FILES ['up _ picture '] ['error']> 0 ){
Echo "upload error! ";
Switch ($ _ FILES ['up _ picture '] ['error']) {
Case 1:
Echo "uploading files exceeds the configuration file limit ";
Break;
Case 2:
Echo "uploading files exceeds the specified value of the form ";
Break;
Case 3:
Echo "Incomplete file uploads ";
Break;
Case 4:
Echo "no file uploaded ";
Break;
}
} Else {
If (! Is_dir ('./upfile/') mkdir ('./upfile /');
$ Path = './upfile/'. time (). $ _ FILES ['up _ picture '] ['name'];
If (is_uploaded_filed ($ _ FILES ['up _ picture '] ['tmp _ name']) {
If (! Move_uploaded_file ($ _ FILES ['up _ picture '] ['tmp _ name'], $ path )){
Echo "Upload failed! ";
} Else {
Echo "file ". time (). $ _ FILES ['up _ picture '] ['name']. "uploaded successfully. size :". $ _ FILES ['up _ picture '] ['size'];
}
} Else {
Echo "Upload file". $ _ FILES ['up _ picture '] ['name']. "illegal ";
}
}
}
?>



4. file download

This section describes how to download files through http, mainly using the header () function. The header () function is an HTTP function that sends the header of the HTML document to the browser and tells the browser how to handle the page.
Void header (string [, bool replace [, int http_respone_code]); // The string parameter specifies the sent header. The replace parameter controls whether to replace or add similar headers if multiple headers are sent at a time. If it is false, multiple headers of the same type are forcibly sent. the default value is true. The http_respone_code parameter forces the HTTP response code to be set to the specified value:
The download procedure is as follows:
A): specify the object MIME Type through "Content-Type.
B) description of the file through "Content-Disposition". The value "attachment; filename =" test.jpg "indicates that the file is a Fujian province and the name of the downloaded file is specified.
C): use "Content-Length" to set the size of the downloaded file.
D): read the file content through the readfile () function.
For example:

The code is as follows:


Header ('content-Type: image/jpg ');
Header ('content-Disposition: attachment; filename = "test.jpg "');
Header ('content-Length: '.filesize('test.jpg '));
Readfile('test.jpg ');



5. access remote files

Step 1: configure the php. ini file option allow_url_fopen to on. The parameter is enabled by default, allowing you to open remote files specified by http and ftp. If allow_url_fopen is set to off, remote files cannot be opened.
Step 2: Use the fopen () function to read the file content. Create the resources you want based on the content and save them to your local device.
        
Ps: For more file operations and directory operations in the php. ini configuration file, see the official php guide.

Example 1. File operation. Open File: when a specified file is opened, the corresponding object is returned. If no specified file exists, the file may be automatically created. Resource...

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.