带有 URL 参数的 PHP echo 语句



我用PHP编写了一个小脚本来向Web服务器发送POST请求:

<?php
$cid = file_get_contents('cid');
function httpPost($url)
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST, true);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}
echo httpPost("http://172.17.0.1:2375/containers/$cid/stop?t=5");
?>

是的,这是Docker。 我在 Docker 中使用远程 API,这个小脚本可以工作!但是,URL 末尾的 ?t=5 将被忽略。我想这与有关。

如何正确设置此 URL 的格式,以便 ?t=5 正常工作?

(到目前为止,我尝试了1,001种方法,有引号和双引号,但没有运气。 经过 4 个多小时的处理,我认为堆栈溢出会有所帮助?

谢谢。。。

注意:"cid"只是硬盘驱动器上的一个文件,用于存储容器 ID。 所以我从文件中检索容器 ID,并将其传递给 URL(无论如何,这部分有效)。完整的URL是由我写的,即没有解析。

既然你的URL没有特殊要求,为什么要使用不完整的cURL包装器函数呢?你可以简单地做

echo file_get_contents("http://172.17.0.1:2375/containers/$cid/stop?t=5");

要回答您的实际问题,即为什么您的查询字符串被忽略,这是因为它没有正确发送到服务器。谷歌CURLOPT_POSTFIELDS

编辑 由于提到请求方法必须是 POST,因此您可以在 cURL 代码中稍微更改内容以满足这一点

curl_setopt($ch, CURLOPT_POSTFIELDS,"t=5");

然后你可以像

echo httpPost("http://172.17.0.1:2375/containers/$cid/stop");

由于您正在尝试 POST 请求,因此您可以稍微修改一下函数。对于$data,您可以传递数组("t"=>5)。

function httpPost($url, $data = '')
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST, true);
    if ($data != '')
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

你可以尝试这样执行吗?

<?php
$cid = file_get_contents('cid');
function containeraction($cid, $action, $s) {
    //Time in Seconds
    $timedelay="t=".$s;
    //Docker Container Host
    $dockerhost="172.17.0.1";
    //Host Port
    $port="2375";
    $url = "http://".$dockerhost.":".$port."/containers/".$cid."/".$action;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $timedelay);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}
//containeraction(container id, action, delay)
echo containeraction($cid, "stop", "5");
?>

你的 curl 设置适用于 Docker 并传递查询字符串。读取文件时,您确实需要修剪空格,以防末尾有新行。

<?php
$cid = trim(file_get_contents('cid'));
echo "$cidn";
function httpPost($url)
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST, true);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}
$url = "http://172.17.0.1:2375/containers/$cid/stop?t=6";
echo "$urln";
echo httpPost($url)
?>

最新更新