PHP: Example of usage CURLOPT_WRITEFUNCTION


CURLOPT_WRITEFUNCTION: A callback accepting two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by this callback. It must return the exact number of bytes written or the transfer will be aborted with an error.

<?php

$ch = curl_init();
$result = '';
$callback = function ($ch, $str) {
    global $result;
    $result .= $str;
    return strlen($str);
};
curl_setopt($ch, CURLOPT_URL, 'http://tutorialspots.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_exec($ch);
curl_close($ch);
var_dump($result);

Result:

string(120955) "
<!doctype html >
<!--[if IE 8]>    <html class="ie8" lang="en"> <![endif]-->
<!--[if IE 9]>    <html class="ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-US"> <!--<![endif]-->
...

Example 2:

<?php
set_time_limit(0);
@header("Content-Type:video/mp4");
$url = 'https://cs508406.userapi.com/4/u330693590/videos/92b2dc68ca.240.mp4?extra=4Gcx1QRbTb9L-KnybR62GHqd-yXkkermpNo9FXlTXyzjAmIy4riNKfKvI6_CNu3_nqAYCj8Tzlk5bj0bZBh5LsvI8tDi4hqaKDbTcCjJWDlpwa7kDw3NGOZzTsco9IathZzQ-Ds5Z-GI';
$ch = curl_init();
$count = 0;
$callback = function ($ch, $str) {
    global $count;

    if(($count++)==0) header("Content-Length: ".curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD).""); 
    echo $str;
    flush();
    return strlen($str);
};
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1000);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
curl_close($ch);

2 Comments

Leave a Reply