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);

Related Post

, ,

Trackbacks/Pingbacks

  1. PHP CURL: How to limit read size | Free Online Tutorials - May 11, 2017

    […] case, we need to read a first part of a website page or a file. How to limit read size? We can use CURLOPT_WRITEFUNCTION: Example […]

Leave a Reply