在PHP中使用curl_init函数的说明

2019-04-09 14:20:16于丽


// create a new curl resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, “http://www.google.nl/”);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// grab URL, and return output
$output = curl_exec($ch);
// close curl resource, and free up system resources
curl_close($ch);
// Replace ‘Google' with ‘PHPit'
$output = str_replace('Google', ‘PHPit', $output);
// Print output
echo $output;
?>

在上面的2个实例中,你可能注意到通过设置函数curl_setopt()的不同参数,可以获得不同结果,这正是curl强大的原因,下面我们来看看这些参数的含义。
CURL的相关选项:
如果你看过php手册中的curl_setopt()函数,你可以注意到了,它下面长长的参数列表,我们不可能一一介绍,更多的内容请查看PHP手册,这里只介绍常用的和有的一些参数。
第一个很有意思的参数是 CURLOPT_FOLLOWLOCATION ,当你把这个参数设置为true时,curl会根据任何重定向命令更深层次的获取转向路径,举个例子:当你尝试获取一个PHP的页面,然后这个PHP的页面中有一段跳转代码 ,curl将从http://new_url获取内容,而不是返回跳转代码。完整的代码如下:

// create a new curl resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, “http://www.google.com/”);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// grab URL, and print
curl_exec($ch);
?>

如果Google发送一个转向请求,上面的例子将根据跳转的网址继续获取内容,和这个参数有关的两个选项是CURLOPT_MAXREDIRS和CURLOPT_AUTOREFERER .
参数CURLOPT_MAXREDIRS选项允许你定义跳转请求的最大次数,超过了这个次数将不再获取其内容。如果CURLOPT_AUTOREFERER 设置为true时,curl会自动添加Referer header在每一个跳转链接,可能它不是很重要,但是在一定的案例中却非常的有用。
下一步介绍的参数是CURLOPT_POST,这是一个非常有用的功能,因为它可以让您这样做POST请求,而不是GET请求,这实际上意味着你可以提交
其他形式的页面,无须其实在表单中填入。下面的例子表明我的意思:

// create a new curl resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL,”http://projects/phpit/content/using%20curl%20php/demos/handle_form.php”);
// Do a POST
$data = array('name' => ‘Dennis', 'surname' => ‘Pallett');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// grab URL, and print
curl_exec($ch);
?>
And the handle_form.php file:
echo ‘Form variables I received:';
echo ‘';
print_r ($_POST);
echo ‘';
?>

正如你可以看到,这使得它真的很容易提交形式,这是一个伟大的方式来测试您的所有形式,而不以填补他们在所有的时间。
相关文章 大家在看