Php if file ends with

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() .

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
Читайте также:  Ttps seller edu ozon ru docs work with goods dobavlenie rich kontenta json html

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

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.

Читайте также:  Including Bootstrap Icons in HTML

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

Источник

feof

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose() ).

Return Values

Returns true if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns false .

Notes

If a connection opened by fsockopen() wasn’t closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

/* Assuming $fp is previously opened by fsockopen() */

$start = NULL ;
$timeout = ini_get ( ‘default_socket_timeout’ );

while(! safe_feof ( $fp , $start ) && ( microtime ( true ) — $start ) < $timeout )
/* Handle */
>
?>

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return true .

Example #2 feof() example with an invalid file pointer

// if file can not be read or doesn’t exist fopen function returns FALSE
$file = @ fopen ( «no_such_file» , «r» );

// FALSE from fopen will issue warning and result in infinite loop here
while (! feof ( $file )) >

User Contributed Notes 16 notes

I really thought that the feof() was TRUE when the logical file pointer is a EOF.
but no !
we need to read and get an empty record before the eof() reports TRUE.

$fp = fopen(‘test.bin’,’rb’);
while(!feof($fp)) $c = fgetc($fp);
// . do something with $c
echo ftell($fp), «,»;
>
echo ‘EOF!’;

prints for two time the last byte position.
If our file length is 5 byte this code prints

Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on «do something with $c» ^_^).

To prevent errors you have to use this code

$fp = fopen(‘test.bin’,’rb’);
while(!feof($fp)) $c = fgetc($fp);
if($c === false) break;
// . do something with $c
>

$fp = fopen(‘test.bin’,’rb’);
while(($c = fgetc($fp))!==false) // . do something with $c
>

Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php developer said that this does not imply a bug in PHP itself (http://bugs.php.net/bug.php?id=35136&edit=2).

Читайте также:  Css transform scale calc

If this is not a bug I think that this need at least to be noticed.

Sorry for my bad english.
Bye 😉

When using feof() on a TCP stream, i found the following to work (after many hours of frustration and anger):

NOTE: I used «;» to denote the end of data transmission. This can be modified to whatever the server’s end of file or in this case, end of output character is.

while( strcmp ( $cursor , «;» ) != 0 ) $cursor = fgetc ( $sock );
$inData .= $cursor ;
>
fclose ( $sock );
echo( $inData );
?>

Since strcmp() returns 0 when the two strings are equal, it will return non zero as long as the cursor is not «;». Using the above method will add «;» to the string, but the fix for this is simple.

$cursor = fgetc ( $sock );
while( strcmp ( $cursor , «;» ) != 0 ) $inData .= $cursor ;
>
fclose ( $sock );
echo( $inData );
?>

I hope this helps someone.

$fp = fopen(«myfile.txt», «r»);
while ( ($current_line = fgets($fp)) !== false ) // do stuff to the current line here
>
fclose($fp);
?>

AFAICS fgets() never returns an empty string, so we can also write:

$fp = fopen(«myfile.txt», «r»);
while ( $current_line = fgets($fp) ) // do stuff to the current line here
>
fclose($fp);
?>

feof() is, in fact, reliable. However, you have to use it carefully in conjunction with fgets(). A common (but incorrect) approach is to try something like this:

$fp = fopen(«myfile.txt», «r»);
while (!feof($fp)) $current_line = fgets($fp);
// do stuff to the current line here
>
fclose($fp);
?>

The problem when processing plain text files is that feof() will not return true after getting the last line of input. You need to try to get input _and fail_ before feof() returns true. You can think of the loop above working like this:

* (merrily looping, getting lines and processing them)
* fgets used to get 2nd to last line
* line is processed
* loop back up — feof returns false, so do the steps inside the loop
* fgets used to get last line
* line is processed
* loop back up — since the last call to fgets worked (you got the last line), feof still returns false, so you do the steps inside the loop again
* fgets used to try to get another line (but there’s nothing there!)
* your code doesn’t realize this, and tries to process this non-existent line (typically by doing the same actions again)
* now when your code loops back up, feof returns true, and your loop ends

There’s two ways to solve this:

1. You can put an additional test for feof() inside the loop
2. You can move around your calls to fgets() so that the testing of feof() happens in a better location

$fp = fopen(«myfile.txt», «r»);
while(!feof($fp)) $current_line = fgets($fp);
if (!feof($fp)) // process current line
>
>
fclose($fp);
?>

And here’s solution 2 (IMHO, more elegant):

$fp = fopen(«myfile.txt», «r»);
$current_line = fgets($fp);
while (!feof($fp)) // process current line
$current_line = fgets($fp);
>
fclose($fp);
?>

FYI, the eof() function in C++ works the exact same way, so this isn’t just some weird PHP thing.

Источник

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