PHP + cURL + POST无效

时间:2017-03-15 12:50:06

标签: php curl http-post

我试图在网站上发布帖子请求,但它无效。

我已经使用Postman(Chrome扩展程序)发出了POST请求,但它运行正常。

我想要获取的网址类似于:https://scanurl.net/?u=google.com

我的代码是:

    <?php
    $ch = curl_init();

    $postvars = [
    'u' => 'google.com'
    ];

  $url = "https://scanurl.net/";

  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
  curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  print "curl response is:" . $response;
  curl_close ($ch);
?>

解决方案(使用POSTMAN代码片段:

<?php

$curl = curl_init();

$url='https://scanurl.net/?u=gxxoe.com';
  curl_setopt($curl,CURLOPT_URL,$url);

curl_setopt_array($curl, array(
 // CURLOPT_URL => "https://scanurl.net/?u=gxoe.com",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: be8b2f15-e8fd-86f9-5d7a-01f4b4b79587"
  ),
));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>

3 个答案:

答案 0 :(得分:0)

它可能在Postman中起作用,因为您设置的是GET变量而不是POST变量。我已经将上面的代码修改为应该起作用的东西:

<?php
  $ch = curl_init();
  $url = "https://scanurl.net/";

  curl_setopt($ch,CURLOPT_URL,$url.'?u=google.com');
  curl_setopt($ch,CURLOPT_POST, 0);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  print "curl response is:" . $response;
  curl_close ($ch);
?>

编辑:我应该补充一下,确保在经常这样做之前先咨询网站所有者,因为他们可能不善于从网站上抓取信息。

答案 1 :(得分:0)

您可以直接从Postman生成curl-request,但请记住,有一个小错误: https://github.com/postmanlabs/postman-app-support/issues/2631

您必须使用值CURLOPT_CUSTOMREQUEST添加参数POST,然后必须添加CURLOPT_POSTFIELDS

答案 2 :(得分:0)

试试这个慢,需要3-5分钟导致重定向,但应该恢复数据。

$url = "https://scanurl.net/";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, "u=google.com");   
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded",'Content-Length: ' . strlen("u=google.com")  )  );
$result=curl_exec($ch);
curl_close($ch);
var_dump($result);