带有URL参数的PHP echo语句

我在PHP中写了一个小脚本来发送POST请求到Web服务器:

<?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个多小时,我认为stackoverflow可以帮忙?)

谢谢…

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

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

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

为了回答你实际的问题,为什么你的查询string被忽略,这是因为它没有被正确地发送到服务器。 Google 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起作用并传递查询string。 如果在结尾处有新行,则在读取文件时,您需要修剪空白。

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