Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Direct I/O dio_read() Function



The PHP Direct I/O dio_read() function is used to read bytes from a file descriptor. This function can read and return len bytes from a file with a resource descriptor. If len is not specified, the dio_read() function can read 1K block and return it.

Syntax

Below is the syntax of the PHP Direct I/O dio_read() function −

string dio_read(resource $fd, int $len = 1024)

Parameters

Below are the parameters of the dio_read() function −

  • $fd − It is the file descriptor returned by dio_open().

  • $len − It is the number of bytes to read (default value is 1024 bytes).

Return Value

The dio_read() function returns the read string on success. And FALSE on failure.

PHP Version

First introduced in core PHP 4.2.0, the dio_read() function continues to function easily in PHP 5.1.0.

Example 1

This PHP example code shows how to open a file and read its content with the help of the PHP Direct I/O dio_read() function.

<?php
   //open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_RDONLY);

   //Read the file using dio_read
   $data = dio_read($fd, 256);

   // Close the file using dio_close
   dio_close($fd);

   echo $data;
?>

Output

The above code will result something like this −

Hello, World!:
Line 1
Line 2
Line 3

Example 2

In the below PHP code we will try to use the dio_read() function and read 512 bytes from the given file.

<?php
   // Open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/sample.txt', O_RDONLY);
   
   // Read 512 bytes
   $data = dio_read($fd, 512); 
   
   dio_close($fd);
   echo $data;
?> 

Output

After running the above program, it generates the following output −

Name: Amit Sharma
Email: as@example.com
Message: Hello, this is a test message.

Example 3

Now the below reads from a file in chunks until the end of the file with the help of dio_read(), and prints the content of the file.

<?php
   // Open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/newfile.txt', O_RDONLY);
   while ($data = dio_read($fd, 256)) {
       echo $data;
   }
   dio_close($fd);
?> 

Output

This will create the below output −

Hello this is a text file.

Example 4

In the below example, we are using the dio_read() function to read data from a serial port.

<?php
   // open a serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR);

   // Read data
   $data = dio_read($fd, 128);
   dio_close($fd);
   echo $data;
?> 

Output

When the above program is executed, it will produce the below output −

Hello, this is data from the serial port.
php_function_reference.htm
Advertisements