我试图通过使用PHP Curl填写表单

时间:2018-01-15 15:40:50

标签: php forms curl post

我正在做一个小项目。对于需要在第三方网站上填写表格的项目。我尝试了下面显示的代码,有人可以告诉我我做错了什么吗?我正在尝试这个表格:

        <form name="contactform" method="post" action="send_form_email.php">
        <table width="450px">
        <tr>
         <td valign="top">
          <label for="first_name">First Name *</label>
         </td>
         <td valign="top">
          <input  type="text" name="first_name" maxlength="50" size="30">
         </td>
        </tr>
        <tr>
         <td valign="top">
          <label for="last_name">Last Name *</label>
         </td>
         <td valign="top">
          <input  type="text" name="last_name" maxlength="50" size="30">
         </td>
        </tr>
        <tr>
         <td valign="top">
          <label for="email">Email Address *</label>
         </td>
         <td valign="top">
          <input  type="text" name="email" maxlength="80" size="30">
         </td>
        </tr>
        <tr>
         <td colspan="2" style="text-align:center">
          <input type="submit" value="Submit"> 
         </td>
        </tr>
        </table>
        </form>

这是我的PHP代码

$url = '[domain]';
$fields = array(
'lname' => urlencode($_POST['$last_name']),
'fname' => urlencode($_POST['$first_name']),
'title' => urlencode($_POST['$title']),
'company' => urlencode($_POST['$institution']),
'age' => urlencode($_POST['$age']),
'email' => urlencode($_POST['$email']),
'phone' => urlencode($_POST['$phone'])
);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试看到卷曲错误:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}else var_dump($result);

另外,考虑使用http_bulid_query而不是这个混乱。

$data = array(
    'foo' => 'bar',
    'baz' => 'boom',
    'cow' => 'milk',
    'php' => 'hypertext processor'
);

echo http_build_query($data) . "\n";