关闭会话:curl_close

完成我们的会话后,记得使用“curl_close”函数关闭它。

curl_close($handler);

执行会话:curl_exec

如果'CURLOPT_RETURNTRANSFER'选项设置为'TRUE',成功时返回请求的实际结果,失败时返回'FALSE'。
当执行我们的请求而不使用“CURLOPT_RETURNTRANSFER”时,我们得到以下结果:

$handler = curl_init("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");
curl_exec($handler);
{"copyright":"Alistair Symon","date":"2019-07-25","explanation":"In brush
strokes of interstellar dust and glowing hydrogen gas, this beautiful skyscape
is painted across the plane of our Milky Way Galaxy near the northern end of the
Great Rift and the constellation Cygnus the Swan. Composed with three different
telescopes and about 90 hours of image data the widefield mosaic spans an
impressive 24 degrees across the sky. Alpha star of Cygnus, bright, hot,
supergiant Deneb lies near top center. Crowded with stars and luminous gas
clouds Cygnus is also home to the dark, obscuring Northern Coal Sack Nebula,
extending from Deneb toward the center of the view. The reddish glow of star
forming regions NGC 7000, the North America Nebula and IC 5070, the Pelican
Nebula, are just left of Deneb. The Veil Nebula is a standout below and left of
center. A supernova remnant, the Veil is some 1,400 light years away, but many
other nebulae and star clusters are identifiable throughout the cosmic scene. Of
course, Deneb itself is also known to northern hemisphere skygazers for its
place in two asterisms -- marking the top of the Northern Cross and a vertex of
the Summer
Triangle.","hdurl":"https://apod.nasa.gov/apod/image/1907/CygnusMosaic07192000Symon.jpg","media_type":"image","service_version":"v1","title":"Cygnus
Skyscape","url":"https://apod.nasa.gov/apod/image/1907/CygnusMosaic07192000Symon_1024.jpg"}

如果我们使用上述选项,则函数返回结果,例如,我们可以使用它作为变量的值:

curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handler);

安装PHP CURL扩展

在Fedora上安装它的命令是:

$sudo dnf install php-curl

要在Debian和衍生系统中安装扩展:

$sudo apt-get install php-curl

在ArchLinux上,扩展合并在主PHP包中:

$sudo pacman -S php
PHP如何使用cURL扩展执行web请求

开源libcurl是客户端URL传输库,它支持大量协议,如“FTP”,“HTTP”,“HTTPS”,并在多种平台上工作。
PHP提供了“curl”模块允许我们执行curl相关的操作。

设置会话选项

可以通过CURL_SETOPT来修改curl的行为或者提供请求的参数。

curl_setopt($handler, CURLOPT_URL, "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");

或者使用常量CURLOPT_RETURNTRANSFER进行设置:

curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);

如果我们需要设置多个选项,可以不用多次调用curl_setopt。
而是把选项配置为键值对,通过“curl_setopt_Array”函数进行设置:

$options = [
    CURLOPT_URL => "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY",
    CURLOPT_RETURNTRANSFER => true
]
curl_setopt_array($handler, $options);

开始新的curl会话

curl_init函数用于初始化对URL的请求

$handler = curl_init("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");
日期:2020-07-07 20:54:27 来源:oir作者:oir