在php中使用curl提交表单

时间:2017-12-13 14:03:40

标签: php curl

我正在尝试使用PHP中的curl提交表单。是否有任何web来获取目标URL上的字段名称,以便我可以将它们映射到我的字段。下面是我的代码,我用于卷曲:

<form action="" method="post">
<input type="text" name="name" >
<input type="text" name="email">
<input type="submit" name ="create_account">
</form>


<?php
 if(isset($_POST['create_account'])){
 $name =    $_POST['name'];
 $email = $_POST['email'];
 $url = "www.exampleurl.com"; // Where you want to post data
 try {
  $ch = curl_init();

  if (FALSE === $ch)
     throw new Exception('failed to initialize');

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);  // Tell cURL you want to post something
   curl_setopt($ch, CURLOPT_POSTFIELDS, "name=". $name ."&email=". $email); 
   // Define what you want to post
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  //curl_setopt(/* ... */);
  $content = curl_exec($ch);
  $info = curl_getinfo($ch);
  $json = json_decode($content, true);
   if (FALSE === $content)
    throw new Exception(curl_error($ch), curl_errno($ch));

  } catch(Exception $e) {

   trigger_error(sprintf(
     'Curl failed with error #%d: %s',
     $e->getCode(), $e->getMessage()),
     E_USER_ERROR);
  }
}
?>

1 个答案:

答案 0 :(得分:1)

试试这个:

$data = array('name'=>$name, 'email'=>$email);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 

从php5开始,建议使用http_build_query

在php5之前,您可以对每个var值执行urlencode()。