[英]How to pass user input to an api endpoint using php curl?
I am trying to POST HTML form login credentials(email & password) to an endpoint using PHP cURL and subsequently redirect to a different page(admin/index.php) after a successful login.我正在尝试使用 PHP cURL 将 HTML 表单登录凭据(电子邮件和密码)发布到端点,然后在成功登录后重定向到不同的页面(admin/index.php)。 However, I keep getting {"success":"false","message":"please provide email and password"}
error from my nodejs login endpoint.但是,我的 nodejs 登录端点不断收到{"success":"false","message":"please provide email and password"}
错误。 I am inexperienced with cURL hence I am failing to notice where I am getting it wrong.我对 cURL 没有经验,因此我没有注意到我在哪里弄错了。 Please help.请帮忙。
<?php
session_start();
// include('includes/config.php');
$error = ''; //Variable to Store error message;
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Email or Password is Invalid";
} else {
//Define $user and $pass
$email = ($_POST['email']);
$password = ($_POST['password']);
$url = 'http://localhost:5000/auth/login';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, $email.":".$password);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
$result = curl_exec($curl);
echo $result;
if ($result == 200) {
$_SESSION['alogin'] = $email;
header("Location: admin/index.php"); // Redirecting to other page
} else {
$error = "Try to login.";
}
curl_close($curl);
}
}
?>
Here is the HTML form.这是 HTML 表格。
<div class="panel panel-info"> <div class="panel-heading"> LOGIN FORM </div> <div class="panel-body"> <form role="form" method="post" name="login" action="index.php" role="form"> <div class="form-group"> <label>Enter Email</label> <input class="form-control" type="email" name="email" autocomplete="off" /> </div> <div class="form-group"> <label>Password</label> <input class="form-control" type="password" name="password" autocomplete="off" /> </div> <button type="submit" name="login" class="btn btn-info">LOGIN</button> </form> </div> </div>
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
There are two formats for CURLOPT_POSTFIELDS
Neither is JSON. CURLOPT_POSTFIELDS
有两种格式,JSON 也不是。
$post = 'key1=value1&key2=value2&key3=value3';
$post = array('key1'=>$value1,'key2'=>$value2,'key3'=>'value3');
You may need to use urlencode() on username and password.您可能需要在用户名和密码上使用 urlencode()。 Were you told to use the CURLOPT_USERPWD
,您是否被告知使用CURLOPT_USERPWD
,
That is unconventional.这是非常规的。
And this is just wrong.这是错误的。 It might work, but it is still wrong.它可能有效,但它仍然是错误的。
if ($result == 200) {
Use利用
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if ($status == 200){...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.