2015年10月1日木曜日

PHP curl with CURLOPT_CONNECTTIMEOUT_MS

If you want to set timeout of milliseconds with PHP curl_setopt, you have to compile new cURL and re-install PHP.

http://php.net/manual/en/function.curl-setopt.php
CURLOPT_CONNECTTIMEOUT_MS
The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second.
Added in cURL 7.16.2. Available since PHP 5.2.3.
Environment: CentOS6 with PHP5.6

Install cURL
# cd /var/tmp
# git clone https://github.com/bagder/curl.git
# cd curl
# ./buildconf
# ./configure --enable-threaded-resolver
# make 
# make install
# ./src/curl -V
curl 7.45.0-DEV (x86_64-unknown-linux-gnu) libcurl/7.45.0-DEV OpenSSL/1.0.1e zlib/1.2.3 libidn/1.18
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile NTLM NTLM_WB SSL libz UnixSockets
Set ldconfig
# echo '/usr/local/lib' > /etc/ld.so.conf.d/custom-libs.conf
# ldconfig
# ldconfig -p | grep curl
 libcurl.so.4 (libc6,x86-64) => /usr/local/lib/libcurl.so.4
 libcurl.so.4 (libc6,x86-64) => /usr/lib64/libcurl.so.4
 libcurl.so (libc6,x86-64) => /usr/local/lib/libcurl.so
 libcurl.so (libc6,x86-64) => /usr/lib64/libcurl.so
Version up PHP
# yum update --skip-broken --disablerepo=base,updates --enablerepo=remi --enablerepo=remi-php56 php
Re-install php-common
# yum reinstall --skip-broken --disablerepo=base,updates --enablerepo=remi --enablerepo=remi-php56 php-common
# php -i | grep cURL
cURL support => enabled
cURL Information => 7.45.0-DEV
Make Test Script
# vim curl_test.php
<?php

$url = 'http://www.yahoo.co.jp/';
echo $url . "\n";

$option = array(
    CURLOPT_CONNECTTIMEOUT_MS => 500,
    CURLOPT_TIMEOUT           => 500,
    CURLOPT_HEADER            => FALSE,
    CURLOPT_FAILONERROR       => TRUE,
    CURLOPT_RETURNTRANSFER    => TRUE
);

if (!$ch = curl_init()) {
    error_log('[error] curl_init');
    exit;
}

try {
    if (!curl_setopt_array($ch, $option)) {
        throw new Exception('[error] curl_setopt');
    }

    if (!$result = curl_exec($ch)) {
        throw new Exception('[error] curl_exec');
    }

    curl_close($ch);

    echo $result;
} catch (Exception $e) {
    curl_close($ch);
    error_log($e->getMessage());
}
Run Test Script.
# php curl_test.php

Top pic from Francisco Gonzalez Snow Curl