【问题标题】:CURL post form doesn't workCURL 帖子表单不起作用
【发布时间】:2018-08-20 17:21:52
【问题描述】:

我使用的是 PHP 版本 7.1.9,但我在通过 CURL 提交表单时遇到问题。 在我的 index.html 中,我想通过 AJAX 显示表单的响应,该表单位于 form.html 页面上,使用 CURL。

index.html

 function sendForm() {
        $.ajax({
            url: "formHandler.php",
            type: "POST",
            success: function (response) {
                showResponse.html("");
                showResponse.append(response);
            },
            error: function (response) {
                showResponse.html("");
                showResponse.append(response);
            }
        });
    }

Form.html 非常简单

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<form action="form.php" method="post">
    name:
    <input type="text" name="name"/><br/>
    <input type="submit" value="submit"/>
</form>
</html>

表单的处理程序也很简单,只显示提交的数据,只是为了安全将其写入txt文件。

form.php:

<?php
$name=$_POST["name"];
    echo "hello $name";
$myfile = fopen("log.txt", "w") or die("Unable to open file!");
$txt = "$name";
fwrite($myfile, $txt);
fclose($myfile);
?>

formHandler.php:

<?php
// add form data
$data = array();
$data['name'] = 'SuperUser';
$post_str = '';

foreach($data as $key=>$value){
    $post_str .= $key.'='.urlencode($value).'&';
}
$post_str = substr($post_str, 0, -1);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/form.html');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);

echo $response;
curl_close($ch);
?>

现在的问题是,当我使用 sendForm() 时,我看不到提交的表单 (form.php),而只看到未提交的表单 (form.html)。首先我想,那只是 CURL 没有显示提交的页面,但 log.txt 也是空的。可能是因为PHP版本,还是有其他问题?在我的phpinfo.php 中,我在 7.55.0 版本中启用了 cURL 支持。

【问题讨论】:

    标签: php ajax curl


    【解决方案1】:

    你应该提交给form.php,而不是form.html。 form.html 在浏览器中所做的事情是由 formHandler.php 使用 Curl 完成的

    这行应该改

    curl_setopt($ch, CURLOPT_URL, 'http://localhost/form.html');
    

    curl_setopt($ch, CURLOPT_URL, 'http://localhost/form.php');
    

    【讨论】:

      【解决方案2】:

      我看到你有函数 sendForm() 但在任何地方都没有被调用。

      我认为,在提交表单时,您可能会要求它调用它。

      告诉我你的要求,我可以帮忙处理这段代码。

      还有在form.php中,修复下面一行

      $txt = "$name";
      

      作为

      $txt = $name;
      

      对于 PHP 变量,您不需要给出双引号

      【讨论】:

      • 我在 index.html 中实现了 sendForm() 到按钮。无论如何感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 2011-12-30
      • 2023-03-13
      • 2018-10-16
      • 2014-09-09
      • 2010-11-22
      • 2018-09-17
      • 2010-12-20
      • 1970-01-01
      相关资源
      最近更新 更多