PHP 学习笔记 (三)

stream_context_create()函数的用法:

$url = "http://www.someweb.com"
$context = stream_context_create(
    array(
        'http' => array(
            'method' =>'post',
            'header' =>sprintf('Authorization Info %s
', base64_encode($username.':'.$password)).'content-type:application/x-www-form-urlencode
',
            'content' => http_build_query(array(''status' =>$message)),
            'timeout' =>5,        
         )        
    )   
);
$ret = file_get_contents($url, false, $context);

stream_context_create() 创建的上下文可用于流(stream),也可用于文件系统(file system). 对于像file_get_contents, file_put_contents, readfile直接使用文件名操作而没有文件句柄的函数来说更有用。 stream_context_create 增加header头 外,还可以定义代理,超时等。

sttream_context_create() 的作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(), file_get_contents() 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。还能通过增加timeout选项解决file_get_contents 潮湿处理。

file_get_contents(path, include_path,context,start,max_length)函数 可读取文件内容,配合stream_context_create()函数使用:

$postdata = '{"getAllPrice":{}}';
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/json',
            'content' => $postdata,
            'timeout' => 300
        )
    );
    $context = stream_context_create($options);
    if (! $context) {
        echo 'create context failed';
    } else {
        $result = file_get_contents($serviceURL, false, $context);
        $result = json_decode($result);
        return $result;
    }

在php 中,如果要访问https的地址,需要在php.ini文件中将ssl的配置打开:

[PHP_OPENSSL]
extension=php_openssl.dll
原文地址:https://www.cnblogs.com/JacobQiao/p/PHP.html