[PHP] Using fopen and fread with PHP

Status
Not open for further replies.

litewarez

Active Member
1,367
2008
1
0
In PHP we have several connectivity functions that allow us to open connections to local and non-local streams such as files and http requests

The first version im going to show you is a local file, where you dont need to send any information such as headers to get data, but mealy open a stream and read.

Heres a brief desctiption if what the functions are used for.

fopen:
this is is usually know as file-open and is used to open a stream and store the connection data in the memory as a resource. this will return a resource witch will be used on conjunction with other parameters

fread:
This is used to read a defined amount of bytes from a stream, for example a line or 256 byts, this takes the resource that is returned by the above

fclose:
This is used to close a stream and free its memory blocks, this will unset the resource variable aswell.

fputs:
This is used to send data to a resource to be added to the content, this also takes the resource generated by the fopen command.


Ok so lets get started with a basic example and then talk about what's going on

PHP:
$resource = fopen('/temp/sample.ext','rb');
$data = array();

while(false != ($contents = fread($resource,128)))
{
     $data[] = $contents;
}

Explanation:
  • Creating a file pointer / resource
  • creating a data array to store data
  • reading using fread for a lengh of 128 untill theres no more contents.
  • Storing the contents into the data array

Note: in Fopen the second parameter is the read bod witch r = read and b = binary, we have to use b on windows systems.

Each block in the data array will contain 128 bytes, this is basically splitting the read contents into chunks.

Heres another example of reading a webpage:

PHP:
$resource = fopen('http://google.com','r');
$data = '';
while(false != ($contents = fread($resource,256)))
{
     $data .= $contents;
}

This example is the same as above, bar the address and read mode..
as were connection via the http:// socket fopen knows that its connecting externally. heres some more protocols you can use

  • ftp://
  • https://
  • data://
  • php://
  • ssh2.shell://
  • compress.zlib://
  • compress.bzip2://
  • ogg://

The list is much greater and is really scalable.

Ok so lets show an example of reading and putting in FTP://.
PHP:
$ftp_login_url = 'ftp://user:pass@hostname.com/';
$resource = fopen($ftp_login_url);
ftp_pasv($resource, true);

ftp_fput($resource, 'wordpress.zip', fopen('wordpress.zip'), FTP_ASCII);
fclose($resource);

AS you can see from the above example were connecting to the ftp socket via fopen and passing the credentials for the login via the user:pass section of the url. then we proceed to set the ftp mode as "pasive"..

The next part is putting a resource/fopen(ed)-file onto the server with a fillename and transfer mode.

Hope you enjoyed this :)
 
Status
Not open for further replies.
Back
Top