带有URL参数的PHP echo语句

时间:2016-06-10 07:32:53

标签: php curl docker http-post

我在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。我正在使用remote API in Docker,这个小小的脚本有效! 但是,URL末尾的?t = 5会被忽略。 我想这与

有关

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

(到目前为止,我尝试了1,001种方法,引号和双引号,没有运气。花了4个多小时,我认为stackoverflow可以帮助吗?)

...谢谢

注意:“cid”只是硬盘驱动器上的一个文件,用于存储容器ID。所以我正在从文件中检索容器ID,并将其传递给URL(无论如何,这部分都可以工作)。 完整的URL由我编写,即未解析。

4 个答案:

答案 0 :(得分:3)

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

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

要回答关于为什么忽略查询字符串的实际问题,这是因为它没有正确地发送到服务器。 Google CURLOPT_POSTFIELDS

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

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

然后你可以调用你的函数

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

答案 1 :(得分:1)

您可以尝试这样执行吗?

<?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");

?>

答案 2 :(得分:1)

由于您正在尝试POST请求,因此您可以稍微修改一下您的功能。对于$ data,您可以传递数组(&#34; t&#34; =&gt; 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;
}

答案 3 :(得分:0)

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

<?php

$cid = trim(file_get_contents('cid'));
echo "$cid\n";

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 "$url\n";
echo httpPost($url)

?>