Home > php教程 > php手册 > body text

Detailed explanation of PHP file system_php basics

WBOY
Release: 2016-05-16 09:00:22
Original
1574 people have browsed it

File processing function
1. File operation.
Open file:
When the specified file is opened, the corresponding object will be returned. If the specified file does not exist, it may be automatically created. this file.
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 (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 The content is rewritten; otherwise, the file is created by itself.
w: Write-only mode - read and write the file, the read/write file pointer points to the head of the file. If the file exists, the content is deleted and rewritten; otherwise, the file is created by itself
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:\r\n Macinitosh:\r). If you use the line terminator incorrectly, a bunch of garbled characters may be output when the file is opened. The above can be solved by " 't'","'b'" to avoid.
Read file:
String fgetc(resource handle);//Return a character in the file pointed to by handle. If EOF is encountered, 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 point 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 lines End.
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 data of any length from a file., 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);
?>
div>
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.

Remarks: 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 the file:
int fwrite(resource handle,string[,int length]);//Perform the 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. If successful, return the number of bytes, 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
If 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. If successful, return true, 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 operation parameter 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
A 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 in conjunction with 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.

Principles 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, upload The size of the file, the instruction execution time, and the 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: The temporary directory for uploading 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 will be 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 uploading of very large files.

Remarks: When controlling the application of uploaded 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. Judge 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])){
/*Assign the picture information to the variable*/
$type=strtolower (strstr($_FILES['up_picture'][name],"."));
if($type != '.jpg' && $type != '.gif') echo "The file format you uploaded Wrong";
else{
if($_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 does not meet the requirements.";
}
}
?>


3. File upload.

Use 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 "上传错误!";
switch($_FILES['up_picture']['error']){
case 1:
echo "上传文件超出配置文件规定值";
break;
case 2:
echo "上传文件超出表单规定值";
break;
case 3:
echo "上传文件不全";
break;
case 4:
echo "没有上传文件";
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 "上传失败!";
}else{
echo "文件".time().$_FILES['up_picture' ][ 'name' ] ."上传成功,大小为:".$_FILES['up_picture' ][ 'size' ] ;
}
}else{
echo "上传文件".$_FILES['up_picture' ][ 'name' ]."不合法";
}
}
}
?>


4.文件下载

这裡介绍通过http方式下载文件,主要用到header()函数。header()函数属于HTTP函数,其作用是以HTTP将HTML文档的表头送到浏览器,并告诉浏览器具体怎麽处理这个页面。
void header(string string[,bool replace[,int http_respone_code]]);//参数string 指定发送的标头。参数replace控制如果一次发送多个标头,对于相似的标头是替换还是添加。如果是false,则强制发送多个同类型的标头,默认为true。参数http_respone_code强制将HTTP响应代码设置为指定值:
下载步骤如下:
    a):通过"Content-Type" 指定文件的MIME类型。
    b):通过"Content-Disposition" 对文件进行描述,值"attachment;filename="test.jpg"" 说明是一个福建,同时指定下载文件的名称。
    c):通过"Content-Length" 设置下载文件的大小。
d):通过readfile()函数读取文件内容。
例如:
复制代码 代码如下:

header('Content-Type:image/jpg');
header(' Content-Disposition:attachment;filename="test.jpg" ');
header('Content-Length:'.filesize('test.jpg') );
readfile('test.jpg');


5.访问远程文件

  步骤1:配置 php.ini 文件选项 allow_url_fopen设置为on。参数默认是开啓的,允许打开http和ftp指定的远程文件。如果 allow_url_fopen设置为off,则不允许打开远程文件。
  步骤2:使用fopen()函数读取文件内容。根据内容创建你想要的资源,保存到本地。
        
ps:更多php.ini配置文件中的文件操作 和 目录操作的扩展方法请参考官方php指南。
Related labels:
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!