【问题标题】:Set cURL address via POST variable通过 POST 变量设置 cURL 地址
【发布时间】:2012-04-07 14:07:18
【问题描述】:

我一直在尝试在 PHP 中使用带有动态地址(即通过 POST 变量设置)的 cURL,但它不起作用!

<?php
$address = $_POST['address'];

//echo $address;
//$address = "http://twitter.com";

$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL, $address);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);

if (empty($buffer)) {
    echo "Sorry, ".$address." are a bunch of poopy-heads.<p>";
}
else {
    echo $buffer;
}
?>

我知道 POST 正在工作,因为我可以回显 $address 变量并查看我发送的 $address 的内容。

【问题讨论】:

  • 那么您有什么错误或问题?不工作是不够的
  • 检查你的$_POST['address']
  • $_POST['address'] 工作正常,请参阅我的问题的底线。
  • 没有错误,只是没有返回我通过 POST 指定的任何地址的任何内容。

标签: php ajax curl


【解决方案1】:

好的,既然你知道$_POST 正在工作,那么让我们看看你的 cURL。

这是我经常使用的功能。或许你可以试一试?

代码:

function getCurl(
                $url,
                $returntransfer=1, $httpproxytunnel=1, $referer=null,
                $useragent=null, $header=null, $httpheader=null,
                $proxy=null, $port=null
                )
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returntransfer);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $httpproxytunnel);

    if ($referer!=null)
        curl_setopt($ch, CURLOPT_REFERER, $referer);
    if ($useragent!=null)
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    if ($header!=null)
        curl_setopt($ch, CURLOPT_HEADER, $header);
    if ($httpheader!=null)
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    if ($proxy!=null)
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
    if ($port!=null)
        curl_setopt($ch, CURLOPT_PORT, $port);

    curl_setopt($ch, CURLOPT_TIMEOUT, 40);

    $result['DATA'] = curl_exec($ch);
    $result['INFO'] = curl_getinfo($ch);
    $result['ERROR'] = curl_error($ch); 

    return $result;
}

function getFile($url)
{
    $data = getCurl($url);

    return $data['DATA'];
}

并像这样使用它:

<?php
     $fileContents = getFile("http://www.somedomain.com/a-path-to-your-file.html");
     echo $fileContents;
?>

【讨论】:

  • 如果您不打算使用 em,为什么还要添加所有额外选项?
  • @LawrenceCherone 因为我有时可能需要... ;-)
  • 嗯...我试过 $fileContents = getFile($address);回声$文件内容;还是不行。
  • 那么在这种情况下,您应该使用return $data;,这样您就可以访问错误和信息数组;p
  • @CharlesJohnThompsonIII 既然你说你可以得到$_POST['address'],为什么不试试最简单的方法:echo file_get_contents($address) 返回什么?
【解决方案2】:

存在输入卫生问题,其中 $address 变量的值中有一个空格。

【讨论】:

    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 2019-04-03
    • 2014-09-04
    • 2015-10-17
    • 2011-12-07
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多