大白菜

  • 优惠汇总
  • linux闲谈
  • shell脚本
  • PHP编程
  • nginx
  • 随笔
分享你我
  1. 首页
  2. PHP编程
  3. 正文

PHP中的context的理解

2024年11月19日 363点热度 0人点赞 0条评论

Table of Contents

Toggle
  • 前言
  • HTTP中的context
  • SSL请求中的context
  • ZIP文件中的context
  • 写入文件时标注权限

前言

一开始我不是很理解php中的context的是什么意思

因为在中间件中同样有这个概念

在同一个中间件实例下

可以根据不同的上下文来区分不同的应用程序

但是用同样的方式去理解php的context就解释不通了

后来发现这个东西其实很简单

 

HTTP中的context

通俗的说就是python在使用requests库时指定的headers

在请求一个http或者https的请求时

通常要指定比如编码方式、请求体报文、User-Agent等附属的信息

而php中的context就是充当了requests库中headers这个添加信息的角色

 

<?php
$postdata = http_build_query(

array(
'var1' => 'some content',
'var2' => 'doh'
)
);

$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

 

 

SSL请求中的context

比如说SSL中要添加SNI

<?php
$context
= stream_context_create([
'ssl' => [
'SNI_enabled' => true,
'SNI_server_certs' => [
'host1.com' => '/path/host1.com.pem',
'host2.com' => '/path/host2.com.pem',
],
]
]);
?>

 

ZIP文件中的context

打开带有密码的zip文件

<?php
// 读取加密归档
$opts = array(
'zip' => array(
'password' => 'secret',
),
);
// 创建上下文...
$context = stream_context_create($opts);
// ...并且使用它读取数据
echo file_get_contents('zip://test.zip#test.txt', false, $context);
?>

 

写入文件时标注权限

$context = stream_context_create([ 'file' => [ 'mode' => '0644' ] ]);

$file = fopen("example.txt", "w", false, $context);

 

 

 

标签: php
最后更新:2024年11月19日

bai

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复
  • 2025 年 2 月
  • 2025 年 1 月
  • 2024 年 12 月
  • 2024 年 11 月
  • 2023 年 12 月
  • 2020 年 5 月
  • 2020 年 4 月

jquery LINUX nginx php SSL tls安全 traefik 输入法

  • wordpress抓取缩略图
  • wordpress裁剪缩略图
  • fstab自动挂载防止无法启动
  • web程序请求头安全加固
  • 提升SSL协议安全性
最近评论
一位WordPress评论者 发布于 5 年前(04月03日) 嗨,这是一条评论。 要开始审核、编辑及删除评论,请访问仪表盘的“评论”页面。 评论者头像来自Grav...

COPYRIGHT © 2020-2025 大白菜的博客. ALL RIGHTS RESERVED.

冀ICP备18004313号-1