简体   繁体   中英

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. However, I keep getting {"success":"false","message":"please provide email and password"} error from my nodejs login endpoint. I am inexperienced with cURL hence I am failing to notice where I am getting it wrong. 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.

 <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.

$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. Were you told to use the 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){...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM