check if value exist in json file using php - php

i make a login system using php with json file data. i tried to login with JavaScript file and it works fine. but it is not secure well. then i change some code with php login.
this is my php code
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
$jsonemail = $value['email'];
$jsonpass = $value['pass'];
}
if($email == $jsonemail && $pass == $jsonpass){
header('location: view.php');
}
else{
echo "please check your email or password";
}
}
but this not working. i want to fix this code. i want to check email and password is correct with json file data.
this is my login.json file data like
"1": {
"email": "test123#gmail.com",
"pass": "123"
},
and this is my html login form
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" required="require" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name="submit" >Submit</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>

I think your email and pass variable are not defined. Have a look at it.
if (isset($_POST['submit'])) {
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
$email = $_POST['email']; // I think you miss this
$pass = $_POST['pass']; // and this lines as in your code its missing
$flag = false;
foreach ($parsed_json as $key => $value) {
if ($value['email'] == $email && $value['pass'] == $pass) {
$flag = true;
break;
}
}
if ($flag) {
header('location: view.php');
} else {
echo "Please check your email and password."
}
}
And one more thing
while posting any form you must name element which you want in $_POST.
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
In above line you are missing name as pass. Replace above line with
<input type="password" class="form-control" id="pass" required="require" placeholder="Password" name="pass">
This should solve your problem.

Your foreach is just overwriting the values of $jsonemail and $jsonpass each time, so when you reach the if() part to check the user details, these will always be the last values in the file.
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
if($email == $value['email'] && $pass == $value['pass']){
header('location: view.php');
exit();
}
}
echo "please check your email or password";
}
This code redirects if the user is found and if it gets to the end of the loop, then the user doesn't exist in the file.

Related

How could I save on a file .txt with php?

<?php
$fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = = htmlspecialchars($_POST["nazionalita"]);
}
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
header("location: index.php");
?>
But of course, this doesn't work.
How can I save to a specific location with PHP?
Then I'll have to do an explode which will only get my email and password. on the login.php page.
Thank you.
I'm not going to fix your code for you, but give you three tips:
Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.
If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);
you should pass the $fp to fwrite() method as follow
$fp = fopen('user.txt', 'w+') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
Thanks everyone, I fixed my code!!!
Following the correct code!
<?php
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
//$fp = fopen("users.txt", "w");
//$fpw = fwrite($fp,$dati $email.' : '.$password);
//fclose($fp);
if(isset($_POST["submitPut"])){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = htmlspecialchars($_POST["telefono"]);
$dati= "\n". $name . ",". $surname .",".$email.",". $password . ",". $nazionalita. ",". $telefono;
$file= fopen("users.txt", "a+");
$credenziali=fwrite($file, $dati);
fclose($file);
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
}
//header("location: index.php");
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once "views/head.php" ?>
<body>
<?php include_once "views/navbar.php" ?>
<main>
<div class="container my-5">
<h2>Registration user</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" >
</div>
<div class="form-group">
<label for="surname">surname:</label>
<input type="text" class="form-control" id="surname" name="surname" placeholder="Enter surname" >
</div>
<div class="form-group">
<label for="email">email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="password">password:</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="form-group">
<label for="nazionalita">nazionalita:</label>
<input type="text" class="form-control" id="nazionalita" name="nazionalita" placeholder="Enter nazionality" >
</div>
<div class="form-group">
<label for="telefono">telefono:</label>
<input type="text" class="form-control" id="telefono" name="telefono" placeholder="Enter phone" >
</div>
<button type="submit"name="submitPut" class="btn btn-primary">Submit</button>
</form>
</div>
</main>
<?php include_once "views/footer.php" ?>
<?php include_once "views/scripts.php" ?>
</body>
</html>

show errors on login modal

i have a working login form that shows up via button click, i can log in but it doesnt show the errors
button that shows login form with the function(in a seperate file):
<button type="button" class="btn btn-lg btn-success" name="button" onclick="signin()" id="signin">Login</button>
function signin()
{
jQuery('#login-form').css("display","block");
jQuery('#reg-form').css("display","none");
jQuery('#signin').css("display","none");
jQuery('#signup').css("display","block");
}
the modal with php(included to the file where the button is):
<?php
$email = ((isset($_POST['Email']))?$_POST['Email']:'');
$password = ((isset($_POST['Password']))?$_POST['Password']:'');
$errors = array();
?>
<div class="" id="login-form" style="display:none">
<img class="Lpic" src="img/loginpic.png">
<br>
<div class="fieldtext">
<h2 class="text-center">Login</h2>
</div>
<br>
<div>
<?php
if($_POST)
{
//form validation
if(empty($_POST['Email']) || empty($_POST['Password']))
{
$errors[] = 'Please enter email and password';
}
//check if email exists
$query = $db->query("SELECT * FROM users WHERE Email = '$email'");
$user = mysqli_fetch_assoc($query);
$userCount = mysqli_num_rows($query);
if($userCount < 1)
{
$errors[] = 'Unknown email, pleas verify';
}
if(password_verify($password, $user['Password']))
{
$errors[] = 'Password doesn\'t match, try again';
}
if(!empty($errors))
{
echo display_errors($errors);
}else{
//log user in
$user_id = $user['ID'];
login($user_id);
}
}
?>
</div>
<form action="Login.php" method="post">
<div class="inputfield">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" value="<?=$email;?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" value="<?=$password;?>">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-success btn-block">
</div>
</form>
</div>
PS: login() is a function that logs in the user, any suggestions on how to show the errors without using alert??? TIA
Well it’s definitely not the prettiest solution, but you can instead of using the display_errors() function render the form validation messages in html whenever the $errorsarray is not empty.
Something like this:
if(!empty($errors)) {
echo ‘<div id=“errors”>’;
foreach ($error in $errors) {
echo $error . “<br>”;
}
echo ‘</div>‘;
}
Sorry that i couldn’t comletely write the code, its hard to code on the phone...
I hope you get the idea.
try setting the following at the top of your php file
ini_set('display_errors', 1);
error_reporting(E_ALL);
hope this helps.
You might also want to look at this answer

Forgot password reset not displaying correct email address and not updating password if any error made by user during for submission

I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>

form data saved in localstorage and post to php

I am working on a simple login form for a mobile site that will save the form data in local storage but will also post data to a php file for url redirection with appended form data. I need help as the storage is working but the post for this is not.
Html
<form class="form-signin" action="siteurl/processing/login-app.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="Eventname" id='eventname'>
<input type="text" class="input-block-level" placeholder="Username" id='username'>
<input type="password" class="input-block-level" placeholder="Password" id="password">
<label class="checkbox">
<input type="checkbox" value="remember-me" id="remember_me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
Now the script
<script>
$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#remember_me').attr('checked', 'checked');
$('#username').val(localStorage.usrname);
$('#pass').val(localStorage.pass);
} else {
$('#remember_me').removeAttr('checked');
$('#username').val('');
$('#pass').val('');
}
$('#remember_me').click(function() {
if ($('#remember_me').is(':checked')) {
// save username and password
localStorage.usrname = $('#username').val();
localStorage.pass = $('#pass').val();
localStorage.chkbx = $('#remember_me').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
});
</script>
And the php
<?php
if (isset($_POST["eventname"]) && isset($_POST["username"]) && isset($_POST["password"])) {
$eventname = $_POST["eventname"];
$username = $_POST["username"];
$password = $_POST["password"];
$url = "siteurl/index.php/$eventname?user=$username&passw=$password";
header( "Location: $url" ) ;
} else {
echo "Username and Password not found";
}
?>
What am I missing?
Your POST variables work off the input names, not ids.
Add a name attribute to your inputs and access them.

Undefined Index PHP issue.Please help

I have the following error:
Notice: Undefined index: submit in C:\wamp\www\registration\register.php on line 6
Can't seem to work out whats wrong??? Here's the code::
<?php
//Create registration form (register.php)
include "../includes/db_connect.php";
if(!$_POST['submit']) ///Line 6
{
?>
<html>
<head><link rel="stylesheet" href="style.css"></head>
<div class="divider">
<strong>Register</strong><br/><br/>
<form method="post" action="register.php">
<div class="formElm">
<label for="first">First Name</label>
<input id="first" type="text" name="first">
</div>
<div class="formElm">
<label for="last">Last Name</label>
<input id="last" type="text" name="last">
</div>
<div class="formElm">
<label for="username">Desired Username</label>
<input id="username" type="text" name="username">
</div>
<div class="formElm">
<label for="password">Password</label>
<input id="password" type="password" name="password">
</div>
<div class="formElm">
<label for="pass_conf">Confirm Password</label>
<input id="pass_conf" type="password" name="pass_conf">
</div>
<div class="formElm">
<label for="email">Email</label>
<input id="email" type="text" name="email">
</div>
<div class="formElm">
<label for="about">About</label>
<textarea id="about" cols="30" rows="5" name="about">Tell us about yourself</textarea>
</div>
<input type="submit" name="submit" value="Register">
</form>
or Login
</div>
</html>
<?php
}
else
{
$first = protect($_POST['first']);
$last = protect($_POST['last']);
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$pass_conf = protect($_POST['pass_conf']);
$email = protect($_POST['email']);
$about = protect($_POST['about']);
$errors = array();
$regex = "/^[a-z0-9]+([_\.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
$errors[] = "E-mail is not in name#domain format!";
}
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about)
{
$errors[] = "You did not fill out the required fields";
}
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$errors[] = "Username already taken, please try another";
}
if(count($errors) > 0)
{
echo "The following errors occured with your registration";
echo "<font color=\"red\">";
foreach($errors AS $error)
{
echo "<p>" . $error . "\n";
}
echo "</font>";
echo "Try again";
//we use javascript to go back rather than reloading the page
// so the user doesn't have to type in all that info again.
}
else
{
$sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`)
VALUES ('$first','$last','$username','".md5($password)."','$email','$about');";
$query = mysql_query($sql) or die(mysql_error());
echo "Thank You for registering {$first}! Your username is {$username}";
echo " Click here to Login";
}
}
?>
If there is no POST parameter at all or if there is no parameter named submit then you're trying to access an array index that does not exists, hence the warning. You can simply test if there is such an index/element in the _POST array.
if( isset($_POST['submit']) )
It doesn't check the value (like you original script, which tests if the value of _POST['submit'] equals false, see type juggling), but the mere existence of the index/element should suffice in this case.
see http://docs.php.net/isset
To get rid of this error, it should be:
if(!isset($_POST['submit']))
However, your code is already OK.
What you are getting is not an error, it is a warning, which is caused by having strict warnings enabld. PHP is a dynamic language which does not usually require to define variables and array keys, and most documentation and code will skip this part. So you should consider turning this feature off, as it clutters code and has few additional benefits. Or, switch to a statically compiled language (say asp.net) which will really benefit from defined variables and static typing.
Your $_POST does not exist when you first load your page. Change your check to something like:
if(!isset($_POST["submit"]))
Because you did not post anything yet, there will be no "submit" key in your $_POST array. That's what causes the warning.
For those posting use if(isset($_POST['submit'])), you clearly did not read his code. He has put is there is not a submit write the HTML form else use the fields (backwards righting to me!)
If he wants to keep the structure as is, it should be
if(empty($_POST['submit']))

Categories