【发布时间】: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 支持。
【问题讨论】: