PHP 8.3.4 Released!

curl 基础例子

只要你编译完的PHP设置了支持 cURL 扩展,你就可以开始使用cURL函数了。使用 cURL 函数的基本思想是先使用 curl_init() 初始化 cURL会话,接着可以通过 curl_setopt() 设置需要的全部选项,然后使用 curl_exec() 来执行会话,当执行完会话后使用 curl_close() 关闭会话。这是一个使用 cURL 函数获取 example.com 主页保存到文件的例子:

示例 #1 使用 PHP cURL 模块获取 example.com 的主页

<?php

$ch
= curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
if(
curl_error($ch)) {
fwrite($fp, curl_error($ch));
}
curl_close($ch);
fclose($fp);
?>

add a note

User Contributed Notes 1 note

up
45
Roberto Braga
8 years ago
It is important to notice that when using curl to post form data and you use an array for CURLOPT_POSTFIELDS option, the post will be in multipart format

<?php
$params
=['name'=>'John', 'surname'=>'Doe', 'age'=>36];
$defaults = array(
CURLOPT_URL => 'http://myremoteservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
?>
This produce the following post header:

--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="name"

Jhon
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="surnname"

Doe
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="age"

36
--------------------------fd1c4191862e3566--

Setting CURLOPT_POSTFIELDS as follow produce a standard post header

CURLOPT_POSTFIELDS => http_build_query($params),

Which is:
name=John&surname=Doe&age=36

This caused me 2 days of debug while interacting with a java service which was sensible to this difference, while the equivalent one in php got both format without problem.
To Top