search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP file system (recommended)

  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]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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools