Home Backend Development PHP Tutorial Detailed explanation of PHP file system (recommended)

Detailed explanation of PHP file system (recommended)

Jul 25, 2016 am 08:54 AM

  1. $filename="./files.text";
  2. $fp=fopen($finename,"rb");
  3. $encho fread($fp,100);
  4. ?>
Copy code

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

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 to 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 closing function. After the operation on the file is completed, the file should be closed, otherwise errors may occur. bool fclose(resouce handle); //Close the file pointed to by parameter handle. If successful, return true, otherwise return false.

Lock files 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 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 catalog

Use the handle returned by the opendir function and the scandir function to implement browsing operations. 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. Note: 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 php file upload and php file 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: Execute the operation method of uploading files.

1. Control uploaded files:

 PHP controls uploaded files through php.ini, including: whether uploading is supported, the temporary directory of the uploaded file, the size of the uploaded 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 options have the following meanings: 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 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 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 uploading 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": Specifies the form encoding data method. Method="post": Specifies the method of data transmission. ​​: Control the size of uploaded files through hidden fields, 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 the uploaded file

 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]: Stores the MIME type of 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. Its return value consists of 5 types:    0: Indicates no errors. 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:

  1. /*Determine whether to upload the picture*/
  2. if(!empty($_FILES['up_picture'][name])){
  3. /*Assign the picture information to the variable*/
  4. $type=strtolower(strstr($_FILES['up_picture'][name],"."));
  5. if($type != '.jpg' && $type != '.gif') echo "What you uploaded The file format is incorrect";
  6. else{
  7. if($_FILES['up_picture'][size]<2000000 && $_FILES['up_picture'][size]>0){
  8. echo "Upload file name: ".$ _FILES['up_picture'][name]."
    ";
  9. echo "Upload file type:".$type."
    ";
  10. echo "Upload file size:".$ _FILES['up_picture'][size]."
    ";
  11. }else echo "The picture size does not meet the requirements.";
  12. }
  13. }
  14. ?>
Copy code

1 2 next last page



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles