search
HomeBackend DevelopmentPHP TutorialCorrect way to read files with PHP

Correct way to read files with PHP

Nov 29, 2016 am 11:02 AM
Linuxphp

Learn how to use PHP’s various file functions. Review basic file functions such as fopen, fclose, and feof; learn about read functions such as fgets, fgetss, and fscanf. And found functions that process entire files in one or two lines of code.

Let’s count how many ways there are

One of the joys of working with a modern programming language like PHP is the sheer number of options available. PHP easily wins Perl's motto "There's more than one way to do it" (not just one way to do it), especially when it comes to file handling. But with so many options available, which one is the best tool for the job? Of course, the actual answer depends on your goals for parsing the file, so it's worth taking the time to explore all options.


The traditional fopen method

The fopen method is probably the most familiar to former C and C++ programmers, because if you've used those languages, they're more or less tools you've had at your disposal for years. For either of these methods, the file is opened by the standard method of using fopen (the function used to read data), and then closed using fclose, as shown in Listing 1.

Listing 1. Use fgets to open and read files                        
$file_handle = fopen("myfile", "r");
while (!feof($file_handle)) {
 $line = fgets($file_handle);
 echo $line;
}
fclose($file_handle);

While most programmers with years of programming experience are familiar with these functions, let me break them down. Effectively follow these steps:
Open the file. $file_handle stores a reference to the file itself.
Check if you have reached the end of the file.
Continue reading the file until the end of the file is reached, printing each line as it is read.
Close the file.

With these steps in mind, I will review every file function used here.

fopen

fopen function will create a connection to a file. The reason I say "create a connection" is because in addition to opening a file, fopen can also open a URL: $fh = fopen("http://127.0.0.1/", "r");

This line of code will create a connection to the above page and allow you to start reading it as if it were a local file.

Note: The "r" used in fopen will instruct the file to be opened read-only. Since writing data to a file is outside the scope of this article, I won't list all other options. However, if reading from a binary file for cross-platform compatibility, "r" should be changed to "rb". You'll see an example of this later.

feof

feof command will detect if you have reached the end of the file and return True or False. The loop in Listing 1 continues until you reach the end of the file "myfile". Note: feof will also return False if a URL is being read and the socket times out because there is no more data to read.

fclose

Skipping forward to the end of Listing 1, fclose will do the opposite of fopen: it will close the connection to a file or URL. After executing this function, you will no longer be able to read any information from the file or socket.

fgets

Jump back a few lines in Listing 1 and you get to the heart of file processing: actually reading the file. The fgets function is the weapon of choice for the first example. It will extract a row of data from the file and return it as a string. After that, you can print or otherwise manipulate the data. The example in Listing 1 will print the entire file fine.

If you decide to limit the size of the processing data chunks, you can add a parameter to fgets to limit the maximum row length. For example, use the following code to limit the line length to 80 characters: $string = fgets($file_handle, 81);

Recall the "Note: The examples for this function already use slightly different parameters than fopen. When working with binary data, always remember to include the b option to fopen. If you skip this point, Microsoft® Windows® systems may not handle the file correctly because they handle new lines differently. If you're dealing with a Linux® system (or some other UNIX® variant), this may not seem to matter. But even if you're not developing for Windows, doing so will result in good cross-platform maintainability and is a good practice to follow.

The above code will read 4,096 bytes (4 KB) of data. Note: No matter how many bytes are specified, fread will never read more than 8,192 bytes (8 KB).

Assuming the file size is no more than 8 KB, the following code should be able to read the entire file into a string. $fh = fopen("myfile", "rb");
$data = fread($fh, filesize("myfile"));
fclose($fh);

If the file length is greater than this value, you can only Use a loop to read the rest in.

fscanf

Back to string processing, fscanf also follows the traditional C file library function. If you're not familiar with it, fscanf reads field data from a file into variables. list ($field1, $field2, $field3) = fscanf($fh, "%s %s %s");

The format string used by this function is described in many places (such as PHP.net), Therefore, we won’t go into details here. Suffice to say, string formatting is extremely flexible. It is worth noting that all fields are placed in the return value of the function. (In C, they are all passed as arguments.)

fgetss

fgetss functions differ from traditional file functions and give you a better understanding of the power of PHP. This function functions like the fgets function, but will strip any HTML or PHP tags found, leaving only plain text. View the HTML file shown below.

List 2. Sample HTML file                                                                                                           If you understand what "Cause there ain't no one for to give you no pain"
                means then you listen to too much of the band America


   
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool