I’m trying to set a login script using PHP and JSON(No database) but i keep have this errors
Warning: Use of undefined constant Email – assumed ‘Email’ (this will
throw an Error in a future version of PHP) in
C:xampphtdocsnetworth-appindex.php on line 37Notice: Array to string conversion in
C:xampphtdocsnetworth-appindex.php on line 37Warning: Use of undefined constant Email – assumed ‘Email’ (this will
throw an Error in a future version of PHP) in
C:xampphtdocsnetworth-appindex.php on line 37
<?php
session_start();
$msg = '';
/* Trigger when the login btn is clicked */
if (isset($_POST['log'])) {
/* Fetch users.json file */
$data = json_decode(file_get_contents("users.json"), true);
/* Get form data */
$email = $_POST['email'];
$pwd = $_POST['password'];
/* Form validation */
if (empty($email || $pwd)) {
$msg = 'Please fill in all fields';
} elseif (strlen($pwd) < 5) {
$msg = 'Password must be more than 5 charcter.';
} else {
/* loop through the users.json data */
foreach ($data as $user) {
/* Login the user */
if ($email === $user['Email'] && $pwd === $user['Password']) {
$_SESSION['Name'] = $user['Name'];
header('location: home.php');
exit;
}
}
}
}
?>
users.json
{
"users": [
{
"Name": "Frank Spencer",
"Email": "[email protected]",
"Password": "test"
},
{
"Name": "Guy Daniel",
"Email": "[email protected]",
"Password": "test1"
}
],
"user": null
}
I want to be able to login to my home.php and echo session name
3
Answers
First of all, you have wrongly used the json data.
Just look at the $user variable in foreach loop.
You’re using it wrongly, because you’re appending to it (with dots (.)) some kind of Email constant, which logically doesn’t exist in your file.
You should have something like that (of course check, if the “Email” or “Password” array keys are correctly written):
when you decode the user.json , it convert to array , so if you want to access any array key directly just to need to write like the $user[‘Email’] not $user.Email, and also change the $user.Password to $user[‘Password’]
So you need to update your foreach like this
because you are trying to fetch Email index directly
Its
So you would access it like: