Friday, July 15, 2011

Alternative for file_get_contents()

SkyHi @ Friday, July 15, 2011
cURL

cURL is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, FILE and LDAP. cURL supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and other useful tricks.
Contents
[hide]

    1 Examples
        1.1 Fetching a web page
        1.2 Alternative for file_get_contents()
        1.3 Getting binary data
            1.3.1 Images
        1.4 Alternative for file()
        1.5 Wrapping it all in an easy class
    2 See Also
    3 External Links

Examples
Fetching a web page

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>

Alternative for file_get_contents()

Instead of:

<?php
$file_contents = file_get_contents('http://example.com/');

// display file
echo $file_contents;
?>

Use this:

<?php
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);

// display file
echo $file_contents;
?>

Otherwise if you are getting some errors with the code above, use this:

<?php
$site_url = 'http://example.com';
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $site_url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

ob_start();
curl_exec($ch);
curl_close($ch);
$file_contents = ob_get_contents();
ob_end_clean();

echo $file_contents;
?>

Getting binary data
Images

This script retrieves a remote image and assigns the binary data to the variable $image, before outputting the image to the browser:

<?php
$image_url = "http://example.com/image.jpg";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $image_url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

// Getting binary data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$image = curl_exec($ch);
curl_close($ch);

// output to browser
header("Content-type: image/jpeg");
print $image;
?>

Alternative for file()

Instead of:

<?php
$lines = file('http://example.com/');

// display file line by line
foreach($lines as $line_num => $line) {
    echo "Line # {$line_num} : ".htmlspecialchars($line)."<br />\n";
}
?>

Use this:

<?php
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
$lines = array();
$lines = explode("\n", $file_contents);

// display file line by line
foreach($lines as $line_num => $line) {
    echo "Line # {$line_num} : ".htmlspecialchars($line)."<br />\n";
}
?>

Wrapping it all in an easy class

Use the following class to make reading/saving remote files easy. This class will automatically delete the temp files downloaded at the end of your PHP script.

<?php

class downloader {
    var $tempFolder;
    var $tempFiles = array();

    function __destruct () {
        foreach ($this->tempFiles as $file) {
            unlink($file['temp']);
        }
    }
   
    function __construct ($temp)
    {
        $this->tempFolder = $temp;
    }
   
    function get ($url) {
        array_unshift($this->tempFiles, array(
            'extension'=> array_pop(explode('.', $url)),
            'original'=> basename($url),
            'temp'=> $this->tempFolder . md5(microtime()),
        ));
        $ch = curl_init($url);
        $fp = fopen($this->tempFiles[0]['temp'], 'w');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $this->tempFiles[0]['temp'];
    }
   
    function read ($index = 0) {
        return file_get_contents($this->tempFiles[$index]['temp']);
    }
   
    function readArray ($index = 0)
    {
        return file($this->tempFiles[$index]['temp']);
    }
   
    function listFiles () {
        return $this->tempFiles;
    }
   
    function save ($path, $index = 0) {
        copy($this->tempFiles[$index]['temp'], (is_dir($path) ? $path . $this->tempFiles[$index]['original'] : $path));
    }
}

$d = new downloader('/home/<username>/<temp folder>');

?>

See Also

allow_url_fopen
cURL PHP tutorial

External Links

    List of Features
    cURL (Client URL Library) Functions
    List of curl_setopt options
    Resize & Display Remote Photos

Categories: Web Applications | PHP

REFERENCES
http://wiki.dreamhost.com/CURL