Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of File system in PHP

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you the example analysis of the file system in PHP, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

File processing function

1. File operation.

Open the file:

The corresponding object is returned when the specified file is opened, and if the specified file does not exist, the file may be created automatically.

Resource fopen (string filename,string mode [, int use_include_path] [, resource context])

Filename can be a file name that contains a file path, or a URL given by a protocol (open a remote file). In order to avoid the trouble caused by system switching,'/'is used as the path separator.

Mode: sets the way to open files. They are:

R: read-only mode with the file pointer at the head of the file.

Read-only mode-read / write mode, file pointer is located in the header file. Note that coverage may occur.

W: write-only mode, the file pointer is located in the file header. If the file exists, delete the content rewrite; otherwise, create the file yourself.

Write-only mode-read / write file, read / write file pointer to file header. If the file exists, delete the content rewrite; otherwise, create the file yourself.

X: write carefully-write mode to open the file, starting from the head of the file, such as. If the file exists, return false, resulting in an E_WARNING-level error message

Xwriting: write carefully-read-write mode to open files. If the file exists, return false, resulting in an E_WARNING-level error message

A: append, and the file pointer points to the end of the file. If the file exists, append it directly to the end of the file; otherwise, create the file yourself.

File pointer to the end of the file. If the file exists, append or read it directly at the end of the file; otherwise, create the file yourself.

B: binary mode. Used to link with other modes. (options under windows)

T: used to combine with other modes. (options under windows)

Please use the fopen () function carefully, as it is possible to delete the file if you are not careful. At the same time, different operating systems have different line ending habits (UNIX:\ n Windows:\ r\ n Macinitosh:\ r). If the line Terminator is used incorrectly, a pile of garbled code may be output when the file is opened. The above can be avoided by "t" and "b".

Read the file:

String fgetc (resource handle); / / returns a character in the file pointed to from handle. If EOF is encountered, return false

String fgets (int handle [, int length]); / / gets a line of characters from the location pointed to by the file pointer and returns a string up to length-1 bytes.. The file pointer must be valid and point to a file successfully opened by fopen () or fsockopen (). Length represents the length of the data read. 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]); / / reads a line and filters out the html,php tag.

String fread (int handle,int length); / / reads data of any length from a file. And can also be used to read binary files Handle is the resource pointing to the file, and length reads length bytes or stops execution when it encounters EOF.

Example:

The copy code is as follows:

The readfile (), file () and file_get_contents () functions.

The 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, and returns the number of bytes read if successful, otherwise returns false. Filename file name. The parameter use_include_path controls whether searching for files in include_path is supported, and true is supported. You do not need to open / close a file to use the readfile function.

Array file (string filename [, bool use_include_path [, resource context]]); / / reads the contents of the entire file into an array. If successful, an array is returned. Each element in the array is a corresponding line in the file, including the newline character; otherwise, false is returned.

String file_get_contents (string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]); / / context is added to 5.0and can be ignored with NULL. Content with an offset,maxlen of 5.1. Offset is used to mark the location of the beginning of the file, and maxlen sets the length of the file read. This method is suitable for reading binary files. Is the preferred way to read the contents of a file into a string. If the operating system supports it, memory mapping techniques are also used to enhance performance. If you open a URL with special characters (such as spaces), use urlencode () for URL encoding.

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 they must be used when reading a character, a line of characters, and characters of any length.

two。 Write to a file:

Int fwrite (resource handle,string [, int length]); / / performs write operations to the file, which 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 are written or string writes are completed. True is returned if the write is successful, false is returned otherwise.

Note: if the length parameter is given, the magic_quotes_runtime option in the php.ini file will be ignored and the slash in the string will not be removed. To distinguish between a binary file and a text file system, add'b'to the mode parameter of the fopen () function when opening the file.

Int file_put_contents (string filename,string data [.int flags [, resource context]]); / / writes a string to the file, returns the number of bytes if successful, otherwise returns false. Flags: implement locking on files (options are file_use_include_path,file_append: append, lock_ex: exclusive locking). Context a context resource.

Note: although fwrite () has the ability to write to a file, it must be supported by the fopen () and fclose () functions. File_put_contents () integrates fopen (), fwrite (), fclose () functions, and can write files separately.

3. Close the file

If the file is open, it should have the function of closing. After the operation on the file is over, you should close the file, otherwise it may cause errors.

Bool fclose (resouce handle); / / closes the file pointed to by the parameter handle, and returns true if successful, false otherwise.

Lock the file

When writing data to a text file, you need to lock the file first to prevent other users from modifying the contents of the file at the same time. In php, the file is locked through the flock () function.

Bool flock (int handle, int operation); / / Parameter operation controls lock permissions. Including: lock_sh: get the shared lock (reader). Lock_ex: get an exclusive lock (write). Lock_un: release the lock. Lock_nb: prevents the flock () function from blocking when locked.

Catalog processing function

A directory is a special file. Since it is a file, if you operate on it, you must also open it before you can browse, and finally remember to close it.

1. Open the directory

Opens the specified directory file, and if successful, returns a handle to the directory. Otherwise, false is returned. Unlike opening a file, if the directory does not exist, it does not automatically create the directory, but throws an error message. You can mask the output of error messages by preceded by the "@" symbol in the opendir () function.

Resource opendir (string path [, resource context]); / / path specifies the directory file to open. If path does not specify a valid directory, or if the file system error cannot be opened due to permission issues, then the function will return false with an E_WARNING-level error message.

two。 Browse the catalog

The browsing operation is realized by using the handle returned by the opendir function and the scandir function.

Array scandir (string directory [, int sorting_ordering [, resource context]]); / / is used to browse directories and files under the specified path. The array containing the file name is returned if successful, otherwise false is returned. Directory specifies the directory to browse, and if it is not a directory, it returns false and generates an E_WARNING-level error message. Sorting_order sets the sort order, which defaults to ascending alphabetical order. If you take this parameter with it, it becomes a descending sort.

Note: the is_dir () function determines whether the specified file name is a directory. Returns true if the file name exists and is a directory, false otherwise. 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 to the working directory to close.

Note: we have learned that if the open directory does not exist, the system will not help us create the directory. Then we can create the directory we want. The following functions can be applied:

Mkdir () function: create a new directory, return true if successful, otherwise false.

The rmdir () function deletes the directory. The directory must be empty (there are no files or subdirectories in the directory) and must have permission to operate.

Unlink () function: deletes the file, returns true for success, and returns false for failure.

The principle of uploading and downloading files

Step content:

Step 1: control the upload of files and configure them through php.ini files.

Step 2: judge the uploaded file. The size and format of the uploaded file.

Step 3: perform the operation method of uploading files.

1. Control the upload of files:

Php controls uploading files through php.ini, including whether uploading is supported, the temporary directory of uploaded files, the size of uploaded files, the execution time of instructions and the memory space allocated by instructions.

Navigate to the file uploads option in the php.ini file to complete the settings for the above options. The meaning of the option is as follows:

File_uploads: if it is on, the server supports file upload, but if it is off, it does not. It is generally supported by default, and this option does not need to be modified.

Upload_tem_dir: the temporary directory where files are uploaded. Before the file is uploaded successfully, the file is saved in the temporary directory of the server first. Most use the system default directory, but you can also set it yourself.

Upload_max_filesize: the maximum number of files allowed to be uploaded by the server, in MB. The system defaults to 2MB, and if it exceeds it, its value must be modified.

The maximum time, in seconds, that an instruction can be executed in max_execution_time:php. The directive must be modified when uploading super-large files, otherwise uploading files in time is within the range allowed by the server, but it still cannot be uploaded beyond the maximum time that the instruction can execute.

The amount of memory allocated by an instruction in memory_limit:php, in MB. Its size will also affect the upload of very large files.

Note: control the enctype and method attributes in the form form when uploading files in the client, as well as the hidden field MAX_FILE_SIZE.

Enctype= "multipart/form-data": specifies how the form encodes data.

Method= "post": specifies how the data is transferred.

Controls the size of the uploaded file in bytes by hiding the domain. This value cannot exceed the value set by the upload_max_filesize option in the php.ini configuration file. It can not completely control the size of the uploaded file, can only avoid some unnecessary trouble.

two。 Judge the uploaded file

The global variable $_ FILES,$_FILES is an array that contains information about all uploaded files. Each element in the array has the following meanings:

$_ 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 file stored in bytes.

$_ files [filename] [tem_name]: stores the file name used by the file in the temporary directory, because the file is first stored in the temporary directory as a temporary file when uploading.

$_ files [filename] [type]: the MIME type in which the uploaded file is stored. MIME specifies the types of various file formats, and each MIME type consists of primary types and subtypes separated by "/". For example, the main type of "image/gif" is the image, and the subtype is the file in GIF format. "text/html" represents the HTML file of the text.

$_ files [filename] [error]: stores the error code for file upload: this project is a new addition to the PHP4.2.0 version. Its return values are divided into five types:

0: indicates that there are no errors. File uploaded successfully.

1: indicates that the size of the uploaded file exceeds the limit of the configuration file directive upload_max_filesize option.

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: no files have been uploaded.

Example:

The copy code is as follows:

3. File upload.

The move_uploaded_file () function is used in php to upload files. However, before execution, in order to prevent potential attacks from illegally managing files that cannot be exchanged through scripts, you can first use the is_uploaded_file () function to determine whether the specified file is uploaded through HTTP POST, and if so, return true. Through this function, you can ensure that malicious users cannot trick scripts into accessing files that cannot be accessed.

Bool is_uploaded_file (string name); / / is used to determine whether the specified file is uploaded through HTTP POST. Filename must be similar to a variable of $_ FILES ['filename'] [' temp_name'] and 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. True is returned if successful, otherwise false is returned. Filename specifies the temporary file name of the uploaded file, namely $_ FILES ['tmp_name'], and the parameter destination specifies the new path and name to be saved after the file is uploaded. If the parameter is not a legal upload file, no action will occur, and the function will return false. If it is a legitimate upload operation, but cannot be moved for some reason, no action will occur and a warning will be issued when false is returned.

The copy code is as follows:

4. File download

Here is introduced through the http way to download files, mainly using the header () function. The header () function belongs to the HTTP function, which sends the header of the HTML document to the browser as HTTP and tells the browser exactly what to do with the page.

Void header (string string [, bool replace [, int http_respone_code]]); / / the parameter string specifies the header to be sent. The parameter replace controls whether to replace or add similar headers if more than one header is sent at a time. In the case of false, multiple headers of the same type are forced 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 steps to download 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 province, and specifies the name of the download file.

C): set the size of the download file through "Content-Length".

D): read the contents of the file through the readfile () function.

For example:

The copy 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 on by default, which allows you to open remote files specified by http and ftp. If allow_url_fopen is set to off, opening remote files is not allowed.

Step 2: use the fopen () function to read the contents of the file. Create the resources you want based on the content and save them locally.

The above is all the contents of the article "sample Analysis of File Systems in PHP". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report