PHP Curl提交登录表单未返回预期响应问题排查
问题描述
我在服务器上部署了一个用于测试Curl表单提交的基础登录页面,代码如下:
<?php if(isset($_POST['submit'])){ $email = $_POST['email']; $password = $_POST['password']; if($email == "email@gmail.com"){ if($password == "123456"){ echo "Correctamundo!"; }else{ echo "Wrong pass"; } }else{ echo "Wrong Email"; } } ?> <!DOCTYPE html> <html> <head> <title>Login Form</title> </head> <body> <form method="POST" action=""> <input type="email" name="email" value=""> <input type="password" name="password" value=""> <input type="submit" value="Submit" name="submit"> </form> </body> </html>
当提交的邮箱为email@gmail.com且密码为123456时,页面会显示**Correctamundo!**提示。
随后我在另一个文件中编写了PHP Curl代码来提交表单,代码如下:
<?php $data = array( "email" => "email@gmail.com", "password" => "123456", "form" => "submit" ); $ch = curl_init("http://sitename.com/login.php"); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Allow Redirections curl_setopt($ch, CURLOPT_POST, true); // Making a POST request curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // COOKIE-jar: To save data for cookie created for login process curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE means Don't just echo output the data instead we can store the Request response in some variable $result = curl_exec($ch); curl_close($ch); echo $result; ?>
我已传入正确的凭据参数,但加载页面时并未得到预期的**Correctamundo!**成功提示,请问问题出在哪里?
问题分析与解决
你的Curl代码存在一个核心错误:
- 登录页面的PHP逻辑通过
isset($_POST['submit'])判断表单是否提交,但你在Curl的$data数组里把触发参数名写成了"form" => "submit",正确的参数应该对应表单提交按钮的name="submit"和value="Submit",也就是"submit" => "Submit"。
修正后的$data数组如下:
$data = array( "email" => "email@gmail.com", "password" => "123456", "submit" => "Submit" );
另外,调试时可以加入Curl错误检查,方便快速定位问题:
$result = curl_exec($ch); if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); } curl_close($ch);
修改后,Curl提交的参数就能被登录页面的PHP逻辑正确识别,从而返回预期的**Correctamundo!**提示。
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

