Not working: json_decode( file_get_contents( 'php://input' ));

Hello,

I’m working on a project on a local machine/localhost (xampp) and I can’t seem to get the values passed over to the next script with json_decode( file_get_contents( ‘php://input’ ));

Environmnet: windows 10
dev : XAMPP
php.ini: allow_url_fopen = On

Results from running the script:

NULL
-----------
string(61) "email=greenl%40test.com&password=greenpwd&btn_login=btn_login"

Two test scrip:

Memberlogin.php

<?php
<div>
    <form action="loginApi.php" method="POST">
     <form  method="POST">
        <label for="emai">Email address:</label><br>
            <input type="text" id="email" name="email"><br>
        <label for="password">Password:</label><br>
            <input type="text" id="password" name="password">
            <br><br>
            <button type="submit" name="btn_login" value="btn_login"> Login </button>            
    </form>
</div>
?>

loginApi.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$data1 = json_decode( file_get_contents( 'php://input' ));
var_dump($data1);

echo "<BR>-----------</br>";

$data2 = file_get_contents('php://input');
var_dump($data2);
?>

That doesn’t seem to be a JSON-encoded string, so it’s probably not surprising that you can’t JSON-decode it.

Did you intend to have two open FORM tags with only the outer one specifying the action parameter?

I don’t see any code that JSON-encodes the form contents on submission, is that somewhere else or is it just a standard form submission?

Is there any reason you can’t use the normal $_POST array to access the variables once you’re in loginapi.php?

1 Like

I agree with droopsnoot, you need to JSON-encoded the string.

Here’s my javascript file:

'use strict';

document.querySelector('.logout').style.display = "none";

const startBtn = document.querySelector('#startBtn');
const loginBtn = document.querySelector('#loginMessage');
const loginForm = document.querySelector('#loginForm');

const   loginUrl = 'loginUser.php';
var loginData = {},
        submitBtn = document.querySelector('#submit'),
        loginInfo = document.querySelector('#loginInfo'),
        loginWelcome = document.querySelector('.welcome');

startBtn.style.visibility = "hidden";

loginForm.style.display = "none";

/*
 * Throw error response if something is wrong: 
 */
const handleLoginErrors = (response) => {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

/* Success function utilizing FETCH */
const loginUISuccess = (parsedData) => {
    console.log('Login was ', parsedData);
    //console.log("loginData", loginData);
    if (parsedData !== false ) { 
        
        startBtn.style.visibility = "visible";
        document.querySelector('.logout').style.display = "block";
        loginForm.style.display = "none";
        loginInfo.style.display = 'block';
        loginWelcome.textContent = `Welcome, ${parsedData.username}!`;
    }
};

/* If Database Table fails to load */
const loginUIError = (error) => {
    console.log("Database Table did not load", error);
}


/* create FETCH request */
const createLoginRequest = (url, succeed, fail) => {
    var sendLoginData = loginData;
    loginData = {}; // Destroy the Login Credentials
    fetch(url, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(sendLoginData)

    })
            .then((response) => handleLoginErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
};

const displayForm = (e) => {
    e.preventDefault();
    const loginForm = document.querySelector('#loginForm');
    document.querySelector('#registerMessage').style.display = "none";
    loginBtn.style.display = "none";
    loginForm.style.display = "block";
    loginBtn.removeEventListener('click', loginForm, false);
};

loginBtn.addEventListener('click', displayForm, false);

const login = (e) => {
    e.preventDefault();
    loginData.username = document.querySelector('#username').value;
    loginData.password = document.querySelector('#password').value;
    
    
    
    createLoginRequest(loginUrl, loginUISuccess, loginUIError);
};

submitBtn.addEventListener('click', login, false);

Here’s a php that I used for FETCH/JSON

<?php

require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

//use Library\Email;
use Library\Database as DB;
use Library\Users as Login;

/* Makes it so we don't have to decode the json coming from JQuery */
header('Content-type: application/json');

/*
 * The below must be used in order for the json to be decoded properly.
 */
$data = json_decode(file_get_contents('php://input'), true);

$result = false;

$login = new Login();

//$login->delete();


if (isset($data['username']) && $data['password']) {

    $username = $data['username'];
    $password = $data['password'];
    $result = $login->read($username, $password);
    
    if ($result) {
        $_SESSION['username'] = $data['username'];
        $data['userId'] = $result;
        unset($data['password']);
        output($data);
    } else {
        output(false);
    }
    
    
}



function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * After converting data array to JSON send back to javascript using
 * this function.
 */

function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

Hope this helps a little.

John

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.