Php check file is closed

PHP File() Handling & Functions

A file is simply a resource for storing information on a computer.

Files are usually used to store information such as:

  • Configuration settings of a program
  • Simple data such as contact names against the phone numbers.
  • Images, Pictures, Photos, etc.

In this tutorial, you will learn-

PHP File Formats Support

PHP file functions support a wide range of file formats that include:

  • File.txt
  • File.log
  • File.custom_extension i.e. file.xyz
  • File.csv
  • File.gif, file.jpg etc
  • Files provide a permanent cost effective data storage solution for simple data compared to databases that require other software and skills to manage DBMS systems.
  • You want to store simple data such as server logs for later retrieval and analysis
  • You want to store program settings i.e. program.ini

PHP file() Function

PHP provides a convenient way of working with files via its rich collection of built in functions.

Operating systems such as Windows and MAC OS are not case sensitive while Linux or Unix operating systems are case sensitive.

Adopting a naming conversion such as lower case letters only for file naming is a good practice that ensures maximum cross platform compatibility.

Let’s now look at some of the most commonly used PHP file functions.

PHP file_exists() Function

This function is used to determine whether a file exists or not.

  • It comes in handy when we want to know if a file exists or not before processing it.
  • You can also use this function when creating a new file and you want to ensure that the file does not already exist on the server.

The file_exist function has the following syntax.

  • “file_exists()” is the PHP function that returns true if the file exists and false if it does not exist.
  • “$file_name” is the path and name of the file to be checked

The code below uses file_exists function to determine if the file my_settings.txt exists.

Save the above code in a file named file_function.php Assuming you saved the file in phptuts folder in htdocs, open the URL http://localhost/phptuts/file_function.php in your browser You will get the following results.

PHP file() Function

PHP fopen() Function

The fopen function is used to open files. It has the following syntax

  • “fopen” is the PHP open file function
  • “$file_name” is the name of the file to be opened
  • “$mode” is the mode in which the file should be opened, the table below shows the modes
  • Read file from beginning.
  • Returns false if the file doesn’t exist.
  • Read only
  • Read file from beginning
  • Returns false if the file doesn’t exist.
  • Read and write
  • Write to file at beginning
  • truncate file to zero length
  • If the file doesn’t exist attempt to create it.
  • Write only
  • Write to file at beginning, truncate file to zero length
  • If the file doesn’t exist attempt to create it.
  • Read and Write
  • Append to file at end
  • If the file doesn’t exist attempt to create it.
  • Write only
  • Php append to file at end
  • If the file doesn’t exist attempt to create it
  • Read and write
  • “$use_include_path” is optional, default is false, if set to true, the function searches in the include path too.
  • “$context” is optional, can be used to specify the context support.

PHP fwrite() Function

The fwrite function is used to write files.

It has the following syntax

  • “fwrite” is the PHP function for writing to files
  • “$handle” is the file pointer resource
  • “$string” is the data to be written in the file.
  • “$length” is optional, can be used to specify the maximum file length.

PHP fclose() Function

The fclose() function is used to close a file in php which is already open

It has the following syntax.

  • “fclose” is the PHP function for closing an open file
  • “$handle” is the file pointer resource.

Let’s now look at an example that creates my_settings.txt.

We will use the following functions.

The code below “create_my_settings_file.php” implements the above example.

Testing the code

Open the URL http://localhost/phptuts/create_my_settings.php in your browser.

You will get the following page

Note: if your disk is full or you do not have permission to write files, you will get an error message.

Switch back to the URL http://localhost/phptuts/file_function.php .

PHP fgets() Function

The fgets function is used to read php files line by line. It has the following basic syntax. fgets($handle); HERE,

Let’s now look at an example that reads my_settings.txt file using the fopen and fgets functions.

The code below read_my_settings.php implements the above example.

  • “fopen” function returns the pointer to the file specified in the file path
  • “die()” function is called if an error occurs. It displays a message and exists execution of the script

PHP copy() Function

The PHP copy function is used to copy files. It has the following basic syntax. copy($file,$copied_file); HERE,

  • “$file” specifies the file path and name of the file to be copied.
  • “copied_file” specified the path and name of the copied file

The code below illustrates the implementation

Deleting a file

The unlink function is used to delete the file. The code below illustrates the implementation.

PHP file_get_contents() Function

The file_get_contents function is used to read the entire file contents.

The code below illustrates the implementation.

The difference between file_get_contents and fgets is that file_get_contents returns the file data as a string while fgets reads the file line by line.

"; // Enables display of line feeds echo file_get_contents("my_settings.txt"); echo "

«; // Terminates pre tag ?>

Summary

  • A file is a resource for storing data
  • PHP has a rich collection of built in functions that simplify working with files.
  • Common file functions include fopen, fclose, file_get_contents
  • The table below shows a summary of the functions covered

Источник

fclose

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

Return Values

Returns true on success or false on failure.

Examples

Example #1 A simple fclose() example

$handle = fopen ( ‘somefile.txt’ , ‘r’ );

See Also

User Contributed Notes 7 notes

It is a GOOD_THING to check the return value from fclose(), as some operating systems only flush file output on close, and can, therefore, return an error from fclose(). You can catch severe data-eating errors by doing this.

I learned this the hard way.

Generally, it’s always a good idea to close a file when you’re done with it. It’s very easy for something to go wrong and corrupt a file that hasn’t been closed properly. If you’re concerned about efficiency, the overhead is negligible.

In case you have some trouble to properly disconnect some client streams opened with stream_socket_server / stream_select you should give a try to stream_socket_shutdown.

Note that from PHP 8.0 onwards, attempting to close a stream that is already closed will throw a fatal TypeError.

Prior to PHP 8, this just caused a warning (that you can silence with @).

if you want to daysychain a filehandle through some functions and each function is allowed to close th file you might look in a following function first, if the handle is still valid.

Opening a file, there often will be used a code like

if (!$fh = fopen($filename, $mode)) return false;

But if you possably have closed the file and you want to check that, a smililar statement would not work.

DOES NOT WORK: if (!$fh) end_of_chain();

use beter: if (is_resource($fh)) end_of_chain();

It is very important to make sure you clear any incoming packets out of the incoming buffer using fread() or some equivalent. Although you can call fclose() the socket does not actually shut down until the inbound packets have been cleared. This can lead to some confusion.

In response to kumar mcmillan ‘gotcha’ note below, we get a different result on a W2K machine:

$file_pointer = fopen ( ‘textfile.dat’ , ‘r’ );
fclose ( $file_pointer );
echo ‘$file_pointer is resource = ‘ . ( is_resource ( $file_pointer ) ? ‘true’ : ‘false’ );
?>

output:
$file_pointer is resource = false

Источник

Читайте также:  Объектно ориентированные возможности php
Оцените статью