php之curl的简单使用

本文详细介绍了CURL在PHP中进行GET和POST请求的方法。GET请求主要用于获取资源,而POST请求用于传递数据。在POST请求中,需设置CURLOPT_POST为true,并通过CURLOPT_POSTFIELDS传递JSON字符串。当接收到application/json类型的数据时,应使用file_get_contents('php://input')获取。$_POST仅能处理application/x-www-form-urlencoded或multipart/form-data类型的POST数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

curl post与get请求

get 请求 [常用]

	// curl初始化
	$ch = curl_init($url);
	// 设置 curl 参数
	// 将头部文件的信息作为数据流输出 
	curl_setopt($ch, CURLOPT_HEADER, false);
	// 执行 curl
	$ret = curl_exec($ch);
	// curl 关闭请求
	curl_close();
	

post 请求[常用]

	// curl初始化
	$ch = curl_init($url);
	// 设置 curl 参数
	// 将头部文件的信息作为数据流输出 
	curl_setopt($ch, CURLOPT_HEADER, false);
	// post 请求
	curl_setopt($ch, CURLOPT_POST. true);
	// post 传参
	curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
	// 设置头部信息 [get 方式一般不用]
	$headerArr = [
		'Content-Type: application/json',
		'Content-Length: '.strlen($jsonStr)
	];
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
	// 执行 curl
	$ret = curl_exec($ch);
	// curl 关闭请求
	curl_close();
	

注:
1,当传参类型为 application/json 时,只能用 file_get_content(‘php://input’) 来接收。
2,$_POST 只能接收传参类型为 application/x-www-form-urlencoded || multipart/from-data 两种类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值