PHP Function Reference

PHP stream_supports_lock() Function



The PHP stream_supports_lock() function tells whether the stream supports locking through flock() function.

Syntax

stream_supports_lock(stream)

Parameters

stream Required. Specify the file pointer to check.

Return Value

Returns true on success or false on failure.

Example: stream_supports_lock() example

Lets assume that we have a file called test.txt in the current working directory. In the example below the stream_supports_lock() function is used to check if a stream associated with this file supports locking or not.

<?php
//open the file in r+ mode
$fp = fopen("test.txt", "r+");

//checking if the stream supports locking
if(stream_supports_lock($fp)) {
  
  //acquiring an exclusive lock
  if (flock($fp, LOCK_EX)) {
    //truncating the file
    ftruncate($fp, 0);
    
    //writing some content to it
    fwrite($fp, "stream_supports_lock() function example\n");

    //flushing output before releasing the lock
    fflush($fp); 

    //releasing the lock
    flock($fp, LOCK_UN);    
  } else {
    echo "Error locking file!";
  }

  //close the file
  fclose($fp);

  //displaying the file content
  echo file_get_contents("test.txt")."\n";
}
?>

The output of the above code will be:

stream_supports_lock() function example

❮ PHP Streams Reference