PHP code example of thlib / php-curl-multi-basic

1. Go to this page and download the library: Download thlib/php-curl-multi-basic library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thlib / php-curl-multi-basic example snippets




$handles = [
    [
        // regular url
        CURLOPT_URL=>"http://example.com/",
        CURLOPT_FOLLOWLOCATION=>false,
        CURLOPT_WRITEFUNCTION=>function($ch, $body)
        {
            print $body;
            return strlen($body);
        }
    ],
     [
        // invalid url
        CURLOPT_URL=>"httpzzz://example.com/",
        CURLOPT_FOLLOWLOCATION=>false,
        CURLOPT_WRITEFUNCTION=>function($ch, $body)
        {
            print $body;
            return strlen($body);
        }
    ],
    [
        // url with a redirect
        CURLOPT_URL=>"http://www.php.net",
        CURLOPT_FOLLOWLOCATION=>false,
        CURLOPT_HEADERFUNCTION=>function($ch, $header)
        {
            print "header from http://www.php.net: ".$header;
            return strlen($header);
        },
        CURLOPT_WRITEFUNCTION=>function($ch, $body)
        {
            print $body;
            return strlen($body);
        }
    ]
];



//create the multiple cURL handle
$CurlMulti = new CurlMulti();

foreach($handles as $opts) {
    // create cURL resources
    $ch = curl_init();

    // set URL and other appropriate options
    curl_setopt_array($ch, $opts);

    // add the handle
    $CurlMulti->add($ch);
}

$statusCode = $CurlMulti->run(function($ch, $statusCode) {
    $info = curl_getinfo($ch);

    if ($statusCode !== CURLE_OK) {
        // handle the error somehow
        print "Curl handle error: ".curl_strerror($statusCode)." for ".$info['url'].PHP_EOL;
        return;
    }

    //$body = curl_multi_getcontent($ch);
    //print $body;
});
if ($statusCode !== CURLM_OK) {
    print "Curl multi handle error: ".curl_multi_strerror($statusCode)." for ".$info['url'].PHP_EOL;
}