PHP中file_get_contents的详细使用

虽然用了很久很久的file_get_contents,但是今天去看文档,发现我只是在浅显的使用,它还有很多参数,我甚至都没有见过。我这里就放几个例子,以方便我下次查看。

1、验证SSL证书

<?php
$url = 'https://secure.example.com/test/1';
$contextOptions = array(
    'ssl' => array(
        'verify_peer'   => true,
        'cafile'        => __DIR__ . '/cacert.pem',
        'verify_depth'  => 5,
        'CN_match'      => 'secure.example.com'
    )
);
$sslContext = stream_context_create($contextOptions);
$result = file_get_contents($url, NULL, $sslContext);
?>

2、不验证SSL证书

<?php
$url = 'https://secure.example.com/test/1';
$contextOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peername' => false
        // Ideally use instead
        // 'cafile' => 'path Certificate Authority file on local filesystem'
    ),
);
$sslContext = stream_context_create($contextOptions);
$result = file_get_contents($url, NULL, $sslContext);
?>

3、设置请求头

<?php
$validateurl="http://validator.w3.org/check?uri=$fileurl";
$cred = sprintf('Authorization: Basic %s',
    base64_encode('username:password') );
$opts = array(
    'http'=>array(
    'method'=>'GET',
    'header'=>$cred)
);
$ctx = stream_context_create($opts);
$validate=file_get_contents($validateurl,false,$ctx);

4、发送POST请求

<?php
$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peername' => false
        // Ideally use instead
        // 'cafile' => 'path Certificate Authority file on local filesystem'
    ),
    'http' => array(
        'method' => 'POST',
        'header' => 
            'Content-type: application/x-www-form-urlencoded'."\r\n".
            ''
        'content' => $postdata
    )
);
$context = stream_context_create($opts);
$result = file_get_contents('https://example.com/submit.php', false, $context);
// A good friend when it fails:
var_dump($http_response_header);

?>

5、设置超时时间

<?php
$opts = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peername' => false
    ),
    'http' => array(
        'method' => 'GET',
        'timeout' => 2,
    )
);
$gonggao = @file_get_contents("https://www.kekc.cn/",false, stream_context_create($opts));
if(!$gonggao){
    $gonggao = "该内容不存在,原因是在执行获取过程中,与系统服务器链接不正常!";
}

var_dump($gonggao);

6、设置代理

<?php
$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);
$data = file_get_contents('http://www.php.net', false, $context);
echo $data;
?>

7、POST请求并设置请求头

<?php
$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(array('foo'=>'bar'))
));
$context = stream_context_create($options);
$data = file_get_contents('http://www.example.com/',false,$context);
echo $data;
?>
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享