Php open file read all lines

Working with Files and Directories with PHP

These examples demonstrate how to work with files and directories in PHP including:

  • Reading, writing, and appending files
  • Getting file size
  • Checking if a file exists
  • Creating, checking, changing, and removing directories
  • Listing directory contents
  • Working with JSON
  • Searching directories for files
  • Reading and writing compressed files

File open modes

When opening a file, there are several different modes you can use. The most common ones are r and w for read and write. There are several more available though that will control whether you create a new file, open an existing file, and whether you start writing at the beginning or the end. These modes are used with fopen() in the rest of the examples.

  • r — read only
  • w — write only, force new file
  • a — write only with pointer at end
  • x — write only, create new file or error on existing
  • r+ — read/write, file pointer at beginning
  • w+ — read/write, force new file
  • a+ — read/write, file pointer at end
  • x+ — read/write, create new file or error on existing

Write to a file

When writing files you have two primary options that we will look at:

  • Writing bytes as needed with fwrite()
  • Writing the entire file contents at once with file_put_contents()

Write bytes

This example shows how to write to a file with some basic text. First, open with fopen() then You can keep writing to the file with fwrite() until you are done, and then call fclose() .

Write entire file at once

This is more convenient and perfect for smaller files that won’t exhaust the system RAM.

Read from a file

When reading a file you have the same two primary options that we will look at:

  • Reading bytes as needed with fread()
  • Reading the entire file in to a variable with file_get_contents()

Read bytes

This example will read N number of bytes in to a variable with fread() . In this case, it will read all the bytes based on the length of the file. You could just read one or two bytes at a time. It will return FALSE if it fails. You can check if the end of file has been reached with feof() .

Читайте также:  Java static builder method

Read entire file at once

This is more memory intensive but convenient. It is best for smaller files that will not exhauset the system RAM.

Read all lines of a text file

To quickly get an array containing each line of a file, use the file() function.

Common file tasks

Here are some examples of other common tasks I perform with files like:

  • Getting file size
  • Checking if a file exists
  • Check if a file is a directory
  • Get a lock on a file
  • Read and write JSON

Get filesize

You can quickly get the size of a file in bytes using the filesize() function.

Check if file exists

You can easily check if a file exists with the file_exists() function.

Get an exclusive lock on a file

This is useful when you want to ensure only one write operation is happening at a time. For example, if you have a file that stores an integer called hit_counter.txt you will want to make sure there is no race condition and that multiple writes are not happening at once.

Working with JSON

A common task is to take data from a PHP array and convert it to a JSON string for storage on disk. Then later reading the file with the JSON string and created a PHP array to work with. To learn more about PHP and JSON check out my tutorial, Working with JSON in PHP.

Here is a basic example of reading and writing a JSON file.

Reading and writing from STDIN, STDOUT, and STDERR

If you want to explicitly work with the standard input, output, and error streams, you can use them with special named constants STDOUT , STDIN , and STDERR .

Then run the file, and enter some text and press enter. Alternatively you can pipe some content in to STDIN like this:

echo "Testing" | php test.php 

Check if file is a directory

To check if a directory entry is a file or a directory, you can use is_dir() function.

Get current working directory

You can check what directory you are in with the getcwd() function.

Get the directory that the PHP file is in

This is useful for creating paths relative to the PHP file no matter what the current working directory is.

Get the path of the PHP file being executed

This is useful for checking what the full path of the PHP file is

Change directory

You can easily change directories with the chdir() function.

Make directory

You can make a directory with mkdir().

Remove directory

Similarly, delete a directory with rmdir().

Get directory contents

If you want to list the contents of a directory you have two main options:

  • scandir() — scandir() will return all contents of a directory
  • glob() — glob() lets you search for contents in a directory using a pattern like *.* or *.png
Читайте также:  Php trim for array

Which one you use will depend on your needs.

scandir()

The scandir() function will list everything in a directory. It will include both files and directories. Contents includes . and .. entries.

glob()

The glob() function lets you search a directory for contents using a pattern. It will return files and directories found.

Some example search patterns you can use are:

Using GZip compressed files

PHP has a convenient way to work with compressed files like GZip files. They call them compression wrappers and they make reading and writing compressed files totally seamless. It supports GZip (zlib), BZip2, and Zip compression but I will focus on GZip.

To use the compression wrappers, all you have to do is prefix your file with: compress.zlib:// .

fopen('compress.zlib://myfile.gz', 'r') 

You can open a file for reading or writing and work with it as normal. Any time a read or write operation is done, it will automatically compress or uncompress as needed.

This next example shows how you would take a video file that is gzipped ( .avi.gz ) and return it as the uncompressed .avi . This way, the files are zipped while they are stored on the server, but when the user downloads them they are unzipped.

In this example, there is a video filenamed my_video.avi.gz .

If the file is small enough and you have enough RAM, you can simply call file_get_contents() which will load the entire thing in to memory at once.

echo file_get_contents('compress.zlib://my_video.avi.gz'); 

Conclusion

After reading this, you should be comfortable with the following:

  • Reading, writing, and appending files
  • Getting file size
  • Checking if a file exists
  • Creating, checking, changing, and removing directories
  • Listing directory contents
  • Searching directories for files
  • Reading and writing compressed files

Источник

PHP Read File

Summary: in this tutorial, you’ll learn how to read a file using the various built-in PHP functions.

To read the contents from a file, you follow these steps:

  • Open the file for reading using the fopen() function.
  • Read the contents from the file using the fread() function.
  • Close the file using the fclose() function.

Here’s the syntax of the fread() function:

fread ( resource $stream , int $length ) : string|falseCode language: PHP (php)

The fread() function has two parameters:

  • The $stream is a file system pointer resource, which is typically the result of the fopen() function.
  • The $length specifies the maximum number of bytes to read. If you want to read the entire file, you can pass the file size to the $length parameter.

The fread() function returns the file contents or false if it fails to read.

The fread() function stops reading the file once the $length number of bytes has been read or the end of file (EOF) has been reached.

To check if the file pointer is at end of file, you can pass it to the feof() function:

feof ( resource $stream ) : bool Code language: PHP (php)

The feof() function returns true if the $stream is at the EOF or an error occurs. Otherwise, it returns false .

Читайте также:  Server to server authentication java

To read a file line by line, you use the fgets() function:

fgets ( resource $handle , int $length = ? ) : string|falseCode language: PHP (php)

Like the fread() function, the fgets() function accepts a file system pointer resource and up to a number of bytes to read. If you omit the $length argument, the fread() function will read the entire line.

PHP read file examples

Let’s take some examples of how to read a file.

1) Read the entire file into a string

Suppose that you have a file named population.txt located at public directory with the following contents:

1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,643 4 Houston Texas 2,316,120 5 Phoenix Arizona 1,708,127 6 Philadelphia Pennsylvania 1,578,487 7 San Antonio Texas 1,567,118 8 San Diego California 1,422,420 9 Dallas Texas 1,343,266 10 San Jose California 1,013,616 Code language: plaintext (plaintext)

The following example uses the fread() function to read the contents of the entire population.txt file into a string and shows it on the webpage:

 $filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, filesize($filename)); fclose($f); echo nl2br($contents); > Code language: HTML, XML (xml)

First, open the population.txt file using the fopen() function:

$f = fopen($filename, 'r');Code language: PHP (php)

Second, read the contents of the entire file using the fread() function; use the filesize() function to get the size of the file:

$contents = fread($f, filesize($filename));Code language: PHP (php)

Third, show the contents of the file on a web page; use the nl2br() function to convert the newline characters to
tags.

echo nl2br($contents);Code language: PHP (php)

Finally, close the file using the fclose() function.

Note that the file_get_contents() function is a shortcut for opening a file, reading the whole file’s contents into a string, and close it.

2) Read some characters from a file

To read some characters from a file, you specify the number of bytes to read. The following example uses the fread() function to read up to 100 bytes from the population.txt file:

 $filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, 100); fclose($f); echo nl2br($contents); >Code language: HTML, XML (xml)
1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,64Code language: plaintext (plaintext)

3) Read a file line by line

The following example uses the fgets() funtion to read the population.txt file line by line:

 $filename = './public/population.txt'; $lines = []; $f = fopen($filename, 'r'); if (!$f) < return; > while (!feof($f)) < $lines[] = fgets($f); >print_r($lines); fclose($f);Code language: HTML, XML (xml)

Summary

  • Use the fread() function to read some or all contents from a file.
  • Use the fgets() function to read a line from a file.
  • Use the feof() function to test the end-of-file has been reached.
  • Use the filesize() function to get the size of the file.

Источник

Оцените статью