Detailed explanation of PHP file system_PHP tutorial

WBOY
Release: 2016-07-21 15:16:00
Original
694 people have browsed it

文件处理函数
1.文件操作.
  打开文件:
    打开指定的文件时会返回相应的对象,若不存在指定的文件,那麽可能会自动创建这个document.
Resource fopen(string filename, string mode [,int use_include_path][,resource context]);
Filename can be a file name containing a file path, or it can be a URL given by a certain protocol (to open a remote file ). In order to avoid the trouble caused by system switching, '/' is used as the path separator.
Mode: Set the way to open the file, respectively:
r: Read-only mode, the file pointer is located at the head of the file.
r+: Read-only mode - read/write mode, the file pointer is located at the head of the file. Note that overwriting may occur.
w: Write-only mode, the file pointer is located at the head of the file. If the file exists, delete it Rewrite the content; otherwise, create the file by yourself.
    w+: Write-only mode----read and write files, the read/write file pointer points to the head of the file. If the file exists, delete the content and rewrite; otherwise, create the file by yourself
Write mode opens the file. If the file exists, return false and generate an E_WARNING level error message
a: Append, the file pointer points to the end of the file. If the file exists, append directly to the end of the file; otherwise, create the file by yourself.
a+: Append, the file pointer points to the end of the file. If the file exists, append or read directly at the end of the file; otherwise, create the file yourself.
b: Binary mode. Used to link with other modes. ( Option under windows)
t: Used to combine with other modes. (Option under windows)
Please use the fopen() function with caution, because the file may be deleted accidentally. At the same time, different The operating systems have different line ending habits (UNIX:n Windows:rn Macinitosh:r). If the line terminator is used incorrectly, a bunch of garbled characters may be output when the file is opened. The above can be passed "'t'", "'b'" to avoid.

Read file:
String fgetc(resource handle);//Return a character from the file pointed to by handle. If EOF is encountered, then Return false;
String fgets(int handle[,int length]);//Get a line of characters from the location pointed to by the file pointer, and return a string of up to length-1 bytes. The file pointer must be valid, And points to a file successfully opened by fopen() or fsockopen(). length indicates the length of the data read. It ends when a newline, EOF, or specified length is encountered. Ignoring length will read to the end of the line.
 string fgetss(resource handle[,int length][,string allowable_tags]);//Read a line and filter out html and php tags.
 string fread(int handle,int length);//Read from the file Data of any length. , can also be used to read binary files. handle is a resource pointing to the file, length reads length bytes or stops execution when EOF is encountered.
Example:

Copy code 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]); //Read a file and write it to the buffer. If successful, return the number of bytes read, otherwise return false. filename file name. The parameter use_include_path controls whether to support searching for files in include_path, and true means it is supported. There is no need to open/close the file using the readfile function.
 array file(string filename [,bool use_include_path[,resource context]]);//Read the contents of the entire file into the array. If successful, an array is returned. Each element in the array is a corresponding line in the file, including newlines; otherwise, false is returned;
string file_get_contents(string filename[,bool use_include_path[,resource context[,int offset[,int maxlen]]]]);//context is new content in 5.0 and can be ignored with NULL. offset, maxlen is the content of 5.1. offset is used to mark the starting position of the file, and maxlen sets the length of the file read. This method is suitable for reading binary files. Is the preferred method for reading the contents of a file into a string. If supported by the operating system, memory mapping technology is also used to enhance performance. If you open a URL with special characters (such as spaces), use urlencode() to encode the URL.

Note: readfile(), file() and file_get_contents() do not need to use the fopen() and fclose() functions when reading the contents of the entire folder, but when reading one character, one line characters and any length of characters.

2. Write to file:
 int fwrite(resource handle,string[,int length]);//Perform file writing operation, it also has an alias fputs (). This method is used to write the contents of string to the file pointer handle. If length is set, the operation stops after length bytes have been written or the string has been written. Returns true if the write is successful, otherwise returns false.
Note: If the length parameter is given, the magic_quotes_runtime option in the php.ini file will be ignored, and the slashes in the string will not be removed. To distinguish between binary files and text file systems, 'b' must be added to the mode parameter of the fopen() function when opening the file.
  int file_put_contents(string filename,string data[.int flags[,resource context]]);//Write a string into the file, and return the number of bytes if successful, otherwise return false. flags: implement locking of files (options include file_use_include_path, file_append: append, lock_ex: exclusive lock). context a context resource.
Note: Although fwrite() has the function of writing files, it must be supported by the fopen() and fclose() functions. file_put_contents() integrates the functions of fopen(), fwrite(), and fclose(), and can complete file writing independently.
3. Close the file
Once the file is open, it should have a close function. After the operation on the file is completed, the file should be closed, otherwise it may cause errors.
bool fclose(resouce handle);//Close the file pointed to by parameter handle, return true if successful, otherwise return false.

Lock file
When writing data to a text file, you need to lock the file first to prevent other users from modifying the content of the file at the same time. File locking is implemented in PHP through flock() function.
 bool flock(int handle,int operation);//The parameter operation controls the locking permission. Including: lock_sh: obtain shared lock (reader). lock_ex: Obtain exclusive lock (write). lock_un: Release the lock. lock_nb: Prevent flock() function from blocking when locking.

Directory processing function
  Directory is a special kind of file. Since it is a file, if you want to operate it, you must open it first, then you can browse it, and finally remember to close it.

1. Open the directory

Open the specified directory file. If successful, return the directory handle. Otherwise return false. Unlike opening a file, if the directory does not exist, it will not automatically create the directory, but will throw an error message. By adding the "@" symbol before the opendir() function, you can block the output of error messages.
Resource opendir(string path[,resource context]);//path specifies the directory file to be opened. If the path specified is not a valid directory, or the file system error cannot be opened due to permission issues, then this function will return false and generate an E_WARNING level error message.

2. Browse the directory


Use the handle returned by the opendir function and the scandir function to implement the browsing operation.
 array scandir(string directory[,int sorting_ordering[,resource context]]);//Used to browse directories and files under the specified path. Returns an array containing the file names if successful, otherwise returns false. directory specifies the directory to be browsed. If it is not a directory, false will be returned and an E_WARNING level error message will be generated. sorting_order sets the sorting order, the default is alphabetical ascending order. If this parameter is provided, it will be sorted in descending order.
Remarks: The is_dir() function determines whether the specified file name is a directory.Returns true if the filename exists and is a directory, false otherwise. If it is a relative directory, its relative path is checked against the current working directory.

3. Close the directory.

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

Note: As we have learned before, if the opened directory does not exist, the system will not create the directory for us. Then we can create the desired directory ourselves. The following functions can be applied:
mkdir() function: Create a new directory and return true if successful, otherwise false.
 RMdir() function: delete a directory. The directory must be empty (no files or subdirectories in the directory) and must have operating permissions.
unlink() function: deletes files, returns true if successful, false if failed.

Principle of file upload and download
  
Step content:
Step 1: Control the uploaded file and configure it through the php.ini file.
Step 2: Judge the uploaded file. Upload file size, format, etc.
Step 3: Perform the operation method of uploading files.

1. Control uploaded files:

PHP controls uploaded files through php.ini, including: whether to support uploading, the temporary directory of uploaded files, and uploaded files The size, instruction execution time and memory space allocated by the instruction.
Locate the file uploads option in the php.ini file and complete the settings for the above options. The meaning of the options is as follows:
file_uploads: If it is on, it means that the server supports file upload. If it is off, it does not support it. Generally, it is supported by default and this option does not need to be modified.
Upload_tem_dir: Temporary directory for uploaded files. Before the file upload is successful, the file is first saved in the server's temporary directory. Most use the system default directory, but you can also set it yourself.
Upload_max_filesize: The maximum size of files allowed to be uploaded by the server, in MB. The system default is 2MB. If it exceeds, the value must be modified.
max_execution_time: The maximum time that a command in php can be executed, in seconds. This command must be modified when uploading very large files, otherwise the timely upload of files is within the range allowed by the server, but if it exceeds the maximum time that the command can be executed, uploading will still not be possible.
Memory_limit: The memory space allocated by a command in php, in MB. Its size also affects the upload of very large files.

Remarks: When controlling the application of uploading files in the client, the enctype and method attributes in the form form, as well as the hidden field MAX_FILE_SIZE.
 enctype="multipart/form-data": Specify the form encoding data method .
Method="post": Specify the method of data transmission.
 : Control the size of the uploaded file through the hidden field, in bytes. This value cannot exceed the value set by the upload_max_filesize option in the php.ini configuration file. It cannot fully control the size of uploaded files, it can only avoid some unnecessary troubles.

2. Determine uploaded files

The global variable $_FILES is used to judge uploaded files. $_FILES is an array that contains information about all uploaded files. The meaning of each element in the array is as follows:
 $_FILES[filename][name]: stores the file name of the uploaded file, such as text.txt, title.jpg, etc.
 $_FILES[filename][size]: The size of the stored file, in bytes.
 $_FILES[filename][tem_name]: The file name used to store the file in the temporary directory, because when the file is uploaded, it must first be stored in the temporary directory as a temporary file.
 $_FILES[filename][type]: MIME type that stores uploaded files. MIME specifies the types of various file formats. Each MIME type is composed of a main type and a subtype separated by "/". For example: the main type of "image/gif" is image, and the subtype is GIF format file. "text/html" represents an HTML file of text.
 $_FILES[filename][error]: Stores the error code of file upload: This item is a new content in PHP4.2.0 version. There are 5 types of return values:
0: Indicates no error. File uploaded successfully.
1: Indicates that the size of the uploaded file exceeds the limit value of the upload_max_filesize option of the configuration file directive.
2: Indicates that 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 has been uploaded.
4: Indicates that no files have been uploaded.
Example:
Copy code The code is as follows:

/*Determine whether to upload the picture*/
if(!empty($_FILES['up_picture'][name])){
/*Change the picture Information is assigned to variables*/
$type=strtolower(strstr($_FILES['up_picture'][name],"."));
if($type != '.jpg' && $type ! = '.gif') echo "The file format you uploaded is wrong";
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 picture size is not Meet the requirements. ";
}
}
?>


3. File upload.

Apply the move_uploaded_file() function in PHP to upload files. But before execution, in order to prevent potential attacks from illegally managing files that cannot be interacted with through scripts, you can first use the is_uploaded_file() function to determine whether the specified file was uploaded through HTTP POST, and if so, return true. This function ensures that malicious users cannot trick scripts into accessing inaccessible files.
bool is_uploaded_file(string name);//Used to determine whether the specified file was uploaded through HTTP POST. filename must be a variable similar to $_FILES['filename']['temp_name']. The file name uploaded from the client cannot be used. $_FILES['filename']['name'].

 move_upload_file(string filename,string destination);//This function is used to upload files to the specified location in the server. Returns true if successful, false otherwise. filename specifies the temporary file name of the uploaded file, that is, $_FILES['tmp_name'], and the parameter destination specifies the new path and name of the file saved after uploading. If the parameter is not a legal uploaded file, no operation will occur and the function will return false. If it is a legal upload operation but cannot be moved for some reason, no operation will occur and a warning will be issued while returning false.
Copy code 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 "The uploaded file exceeds the value specified in the configuration file";
break;
case 2:
echo "The uploaded file exceeds the form Specified value";
break;
case 3:
echo "Incomplete uploaded file";
break;
case 4:
echo "No uploaded file";
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' ] ."Upload successful, size is: ".$_FILES['up_picture' ][ 'size' ] ;
}
}else{
echo "Upload file".$_FILES[ 'up_picture' ][ 'name' ]."Illegal";
}
}
}
?>


4. File Download

Here we introduce downloading files through http, mainly using the header() function. The header() function is an HTTP function. Its function is to send the header of the HTML document to the browser via HTTP and tell the browser how to process this page.
void header(string string[,bool replace[,int http_respone_code]]);//The parameter string specifies the header to be sent. The replace parameter controls whether similar headers are replaced or added if multiple headers are sent at once. If false, forces multiple headers of the same type to be sent. The default is true. The parameter http_respone_code forces the HTTP response code to be set to the specified value:
The download steps are as follows:
a): Specify the MIME type of the file through "Content-Type".
b): Describe the file through "Content-Disposition", the value "attachment;filename="test.jpg"" indicates that it is a Fujian, and also specifies the name of the downloaded file.
c): Set the download file size through "Content-Length".
d): Read the file content through the readfile() function.
For example:
Copy code 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 remote files specified by http and ftp to be opened. If allow_url_fopen is set to off, remote files are not allowed to 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 locally.
   
ps: For more extension methods of file operations and directory operations in the php.ini configuration file, please refer to the official PHP guide.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326004.htmlTechArticleFile processing function 1. File operation. Open file: When opening the specified file, the corresponding object will be returned. If not If the specified file exists, it may be automatically created. resource...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!