我是一个新手,我试图让一个脚本在PHP中用Curl触发另一个脚本,但它似乎正在发送参数.
是否有单独的函数来追加参数?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
Chr*_*isR 17
你需要curl_setopt()和CURLOPT_POSTFIELDS参数.那将把给定的params发布到目标页面.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS:还要检查http_build_query(),这在发送许多变量时很方便.
可接受的答案对POST很有帮助,但是,如果OP想要专门针对GET怎么办?一些REST API指定了http方法,而当您应该进行GET时,通常不适合使用POST。
这是使用某些参数进行GET的代码片段:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
Run Code Online (Sandbox Code Playgroud)
这将导致与制造你的要求GET来http://example.com/endpoint?foo=bar。这是默认的http方法,除非您将其设置为其他类似POST的方法curl_setopt($ch, CURLOPT_POST, true)-因此,如果您特别需要GET,请不要这样做。
如果您需要使用其他http方法之一(例如DELETE或PUT),请使用curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method)。这也适用于GET和POST。
你需要设置CURLOPT_POSTas true和CURLOPT_POSTFIELDS=>参数
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
Run Code Online (Sandbox Code Playgroud)
建议,将' CURLOPT_RETURNTRANSFER' 设置为true,将转移作为返回值的字符串返回,curl_exec($ch)而不是直接输出
| 归档时间: |
|
| 查看次数: |
40613 次 |
| 最近记录: |