使用file_get_contents和cURL从URL获取数据

时间:2015-12-16 06:28:40

标签: php codeigniter curl file-get-contents

我正在使用codeigniter框架。

我想从提供的网址中检索数据。我已经尝试过这个答案:fiddle

问题是,当我访问url时,它正在打印数据。但是当我使用file_get_contents函数进行尝试时,它不会打印任何数据。

<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>

该网址返回 json数据,如:

{
    "email": "test@t.com",
    "LOGIN": true,
    "name": "testing",
    "logintype": "ca"
}

还尝试使用 cURL

<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>

但是无法正常工作并且它返回空。我检查过allow_url_fopenon

2 个答案:

答案 0 :(得分:0)

这是我说的课程:

/**
 * Created by PhpStorm.
 * User: rain
 * Date: 15/11/2
 * Time: 下午4:08
 */
class MyCurlLibrary{
    public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
        $ch = curl_init();
        if($data){
            $bindQuery = http_build_query($data);
            $url.="?".$bindQuery;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        //if need return
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //this is for https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header 
        //this is for web redirect problem
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public static function postRequest($url,Array $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post Data
        curl_setopt($ch, CURLOPT_POST, 1);
        // post variable
        if($data){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        //return data
        return $output;
    }

}

/**
 * sample
 *
 * //test Data
    $url = "http://localhost:8080/test/test.php";//改文件有代码  print_r($_GET);         print_r($_POST)
    $data = array('a'=>'b','c'=>'d',8=>666,888);
    //test get function
    $result = MyCurl::getRequest($url,$data);
    //test post function
    $result = MyCurl::postRequest($url,$data);
    //print result
    var_dump($result);
 *
 *
 */

答案 1 :(得分:0)

这可能有帮助

http://php.net/manual/en/migration56.openssl.php

所以代码看起来像这样:

<?php

$arrContextOptions=array(
    "ssl"=>array(
        "cafile" => "/path/to/bundle/ca-bundle.crt",
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);


$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));

echo $response; ?>