php curl如何发送get或者post请求
admin
2023-07-02 11:24:02
0

php可以扮演资料的发送者。

  1. 简单的get

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://SomeDomain/SamplePath?SomeVar=test");
curl_exec($ch);
curl_close($ch);

2.  简单的post

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://SomeDomain/SamplePath");
curl_setopt($ch, CURLOPT_POST, true); // 啟用POST
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array( "a"=>"123", "b"=>"321") )); 
curl_exec($ch); 
curl_close($ch);

3. 高级的post,可设置多个参数

$toURL = "http://SomeDomain/SamplePath?SomeVar=XX";
$post = array(
  "a"=>"123",
  "b"=>"321",
);
$ch = curl_init();
$options = array(
  CURLOPT_URL=>$toURL,
  CURLOPT_HEADER=>0,
  CURLOPT_VERBOSE=>0,
  CURLOPT_RETURNTRANSFER=>true,
  CURLOPT_USERAGENT=>"Mozilla/4.0 (compatible;)",
  CURLOPT_POST=>true,
  CURLOPT_POSTFIELDS=>http_build_query($post),
);
curl_setopt_array($ch, $options);
// CURLOPT_RETURNTRANSFER=true 会返回服务器响应代码,
// false 时只返回成功与否;
$result = curl_exec($ch); 
curl_close($ch);
echo $result;

4. post 发送文件

发送端代码:

$target_url = 'https://cache.yisu.com/upload/information/20200310/52/110483.jpg');
        /* curl will accept an array here too.
         * Many examples I found showed a url-encoded string instead.
         * Take note that the 'key' in the array will be the key that shows up in the
         * $_FILES array of the accept script. and the at sign '@' is required before the
         * file name.
         */
	$post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);         
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$target_url);
	curl_setopt($ch, CURLOPT_POST,1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$result=curl_exec ($ch);
	curl_close ($ch);
	echo $result;	

接收端代码:

$uploaddir = realpath('./') . '/';$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);echo '
';
	if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
	    echo "File is valid, and was successfully uploaded.\n";
	} else {
	    echo "Possible file upload attack!\n";
	}
	echo 'Here is some more debugging info:';
	print_r($_FILES);
	echo "\n\n";
	print_r($_POST);print "\n";

相关内容

热门资讯

日本首次通过北约清单军援乌克兰 据凤凰卫视报道,日本外务省5月29日宣布,首次通过北约“乌克兰优先需求清单”框架,向乌克兰提供约22...
黑龙江大学科研成果首次被国际数... 近日,黑龙江大学计算机与大数据学院(网络安全学院)朱敬华教授团队在数据挖掘与知识发现领域取得重要科研...
原创 深... 提到深圳的科技创新,你脑海里是不是立刻蹦出南山区的粤海街道? 但可能从今年开始,这个答案要改写了。 ...
一天吃透一个行业09:液冷概念... 来源:市场资讯 (来源:券研社) 一、为什么液冷已成AI算力"刚需"? 芯片功耗突破风冷极限。英伟达...
2026年6月安卓摄影新选择:... 2026年6月安卓摄影新选择:CCD质感手机推荐 2026年6月安卓摄影新选择:CCD质感手机推荐 ...
总书记的人民情怀 | “要坚持... 本报记者 吴 丹原标题:“要坚持健康第一的教育理念”(总书记的人民情怀)
菲律宾防长“装可怜”:中美实力... 【文/观察者网 齐倩】菲律宾政府近年来仗着美国撑腰,在南海议题上“兴风作浪”。中美紧张关系缓和后,菲...
老板燃气灶一直报警是怎么回事 老板燃气灶一直报警是怎么回事原因可能有以下几点:1.熄火保护电路故障造成误报警,导致其长鸣声不断;2...
老板燃气灶一直报警怎么回事 原因可能有以下几点:1.熄火保护电路故障造成误报警,导致其长鸣声不断;2.燃气意外熄灭导致熄火保护功...
燃气灶报警器一直闪灯 这种情况原因有很多种,1、可能是某个零件出现了问题。2、当工业环境中燃气气体泄露,燃气报警器检测到气...