PHP CURL组件安装和常见错误

PHP组件CURL安装

1.安装curl

wget http://curl.haxx.se/download/curl-7.19.6.tar.gz
tar -zxvf curl-7.19.6.tar.gz
cd curl-7.19.6
./configure --prefix=/usr/local/curl
make && make install

2.编译生成扩展

/usr/local/php5/bin/phpize
./configure --with-curl=/usr/local/curl --with-php-config=/usr/local/php5/bin/php-config
make && make install

3.修改php.ini配置

# 添加扩展
extension=curl.so

PHP CURL常见问题

  1. PHP出现Call to undefined function curl_init
    解决方法:这种情况出现原因是php的curl扩展没有正常运行,按以上方法来配置
  2. PHP执行curl返回false
    解决方法:使用var_dump(curl_error($ch));来查看具体错误
  3. PHP执行curl请求https出现Problem with reading the SSL CA cert (path? access rights?)
    解放方法:
    ① 确认一下是否有证书sudo yum install ca-certificates
    ② 重启一下php环境(apache或php-fpm)
    ③ 设置curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0) 不验证证书

提供两个curl函数get和post

function curlGet($url) {
    $ch = curl_init ();
    if (stripos ( $url, 'https://' ) !== FALSE) {
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_SSLVERSION, FALSE ); // CURL_SSLVERSION_TLSv1
    }
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $sContent = curl_exec ( $ch );
    $aStatus = curl_getinfo ( $ch );
    if (curl_errno ( $ch )) {
        $result = 'Curl error: ' . curl_error ( $ch );
    } else {
        if (intval ( $aStatus ['http_code'] ) == 200) {
            $result = $sContent;
        } else {
            $result = FALSE;
        }
    }
    curl_close ( $ch );
    return $result;
}
function curlPost($url, $param, $post_file = FALSE) {
    $ch = curl_init ();
    if (stripos ( $url, 'https://' ) !== FALSE) {
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_SSLVERSION, FALSE ); // CURL_SSLVERSION_TLSv1
    }
    if (is_string ( $param ) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array ();
        foreach ( $param as $key => $val ) {
            $aPOST [] = $key . '=' . urlencode ( $val );
        }
        $strPOST = join ( '&', $aPOST );
}
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $strPOST );
    $sContent = curl_exec ( $ch );
    $aStatus = curl_getinfo ( $ch );
    if (curl_errno ( $ch )) {
        $result = 'Curl error: ' . curl_error ( $ch );
    } else {
        if (intval ( $aStatus ['http_code'] ) == 200) {
            $result = $sContent;
        } else {
            $result = FALSE;
        }
    }
    curl_close ( $ch );
    return $result;
}

发表评论