Error with PhP Script login_tools - php

I'm coding a basic PhP login script right now to develop later on, I've got as far as the Login_tools.php file but when I login in with the wrong details (to check login_tools is working) however I get this error:
"PHP Syntax Check: Parse error: syntax error, unexpected '$un' (T_VARIABLE) in your code on line 27
$q = "SELECT user_id, username FROM users WHERE username = '$un' AND pass = SHA1('$p')" ;"
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname( $_SERVER['PHP_SELF']);
$url = rtrim( $url, '\');
$url .= '/'.$page ;
header("Location:$url") ;
exit() ;
}
function validate( $dbc, $username =", $pwd=")
{
$errors = array();
if( empty($username))
{ $errors[] = "Enter your username."; }
else
{$un = mysqli_real_escape_string( $dbc, trim( $username));}
if( empty( $pwd))
{ $errors[]= "Enter your password.";}
else
{$p = mysqli_real_escape_string($dbc, trim($pwd)); }
if(empty( $errors))
{
$q = "SELECT user_id, username FROM users WHERE username = '$un' AND pass = SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q) ;
if(mysqli_num_rows( $r ) == 1)
{
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC) ;
return array (true, $row) ;
}
else
{ $errors[] = 'Username and/or Passsword not found.';}
}
return array ( false, $errors) ; }
?>
Any help as to why I am getting this error would be much appreciated...

The error is in this line:
url = rtrim( $url, '\');
backslash is an escape char.
Change it to
url = rtrim( $url, '\\');
and the error goes away.

Try this one:
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname( $_SERVER['PHP_SELF']);
$url = rtrim( $url, '\\');
$url .= '/'.$page ;
header("Location:$url") ;
exit() ;
}
function validate( $dbc, $username ="", $pwd="")
{
$errors = array();
if( empty($username))
{ $errors[] = "Enter your username."; }
else
{$un = mysqli_real_escape_string( $dbc, trim( $username));}
if( empty( $pwd))
{ $errors[]= "Enter your password.";}
else
{$p = mysqli_real_escape_string($dbc, trim($pwd)); }
if(empty( $errors))
{
$q = "SELECT user_id, username FROM users WHERE username = '$un' AND pass = SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q) ;
if(mysqli_num_rows( $r ) == 1)
{
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC) ;
return array (true, $row) ;
}
else
{ $errors[] = 'Username and/or Passsword not found.';}
}
return array ( false, $errors) ; }
I hope this helps.

Related

Show error message if that particular content is not in database

Here I have code where user is going to be created, they have to enter one accesscode given by admin. That accesscode is limited by some users like 10 or 20. After that it shows error like your accesscode is limited. So until now, it's working fine.
Now if user tries to enter accesscode that is not given by admin it has to show error message like your accesscode is wrong.
Here is my code:
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage'])) {
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage = 'Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))) {
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and `number` > `used` and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret))) {
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if ($result = $DB->insert_record('user', $insert_record)) {
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
} else
$errorMessage = "error! can you please try again";
} else
$errorMessage = "your access code limit completed";
}
}
?>
Can you give us more information about your problem? What doesn't work?Try some "var_dump()" in your loop to know if you pass through or not so you can tell us where is the problem !
But first thing I see is here :
if(! $chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
and here :
if($result = $DB->insert_record('user', $insert_record))
You should use "==" or "===" because using "=" means you assign a value to "$chk_username" and "result".
Then here is some librairie you can use if you want to display flash message, this is just for your information :
https://github.com/plasticbrain/PhpFlashMessages
And if you want to do it in JS you can use : https://github.com/CodeSeven/toastr
Hope it helps !
i changed the condition like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))
)
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and
status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'],
PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
it's working..

User logs in and is redirected to a page specific to them

Hey im creating a site with users that need to log in. For some reason after the user logs in with a successful combination of email and password, they are redirected to a blank index.php instead of the user_page.php that I have created. I know there are other questions similar to this, I have looked through them but was unable to implement their corrections into my own code.
$errors = array();
$message = "";
$email = "";
$password = "";
if(isset($_POST["submit"])) { //THIS CHECKS LOG IN INFORMATION
//form was submitted
//$email = trim($_POST["email"]);
//$password = trim($_POST["password"]);
//header('Location: user_page.php?id=' . $_SESSION['user_id']);
//Validations
$required_fields = array("email", "password");
validate_presences($required_fields);
foreach ($required_fields as $field){
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = ucfirst($field) . " can't be blank"?><br/><?php ;
}
}
if (empty ($errors)) {
//try to login in
$email = trim($_POST["email"]); //set the variables for use in the function so they can be used as a value in the form, if its been submitted prev it echos back
$password = trim($_POST["password"]);
$found_email = attempt_login($email, $password); //function find user or return null or false
if ($found_email) {
// Success
// Mark user as logged in
$_SESSION["email_id"] = $found_email["id"]; //better than using a cookie which is visible in browser
$_SESSION["email"] = $found_email["email"]; //always know what the user name can use it browser or return the value back
redirect_to("user_page.php");
} else {
// Failure
$_SESSION["message"] = "Email/password not found.";//do not alert as to which field was incorrect
}
}
} else {
/*$email = "";
$password = "";
$message = "";*/
} //if isset end
I have a separate page with validations and functions that come from my learning source. if any other information is needed let me know. Thank You!
functions
<?php
function redirect_to($new_location)
{
header("Location: " . $new_location);
exit;
}
function mysql_prep($string)
{
global $connection;
$escaped_string = mysqli_real_escape_string($connection, $string);
return $escaped_string;
}
function password_encrypt($password)
{
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length)
{
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash)
{
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
function find_all_users()
{
global $connection;
$query = "SELECT * ";
$query .= "From users ";
$query .= "ORDER BY position ASC";
$result = mysql_query($connection, $query);
confirm_query($user_set);
return $user_set;
}
function find_user_by_email($email)
{
global $connection;
$safe_email = mysqli_real_escape_string($connection, $email);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE email = '{$safe_email}' ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function find_email_by_id($email_id)
{
global $connection;
$safe_email_id = mysqli_real_escape_string($connection, $email_id);
$query = "SELECT * ";
$query .= "FROM email ";
$query .= "WHERE id = {$safe_email_id} ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function attempt_login($email, $password)
{
$email = find_user_by_email($email);
if ($email) {
// found user, now check password
if (password_check($password, $email["hashed_password"])) {
// password matches
return $email;
} else {
// password does not match
return false;
}
} else {
// user not found
return false;
}
}
function logged_in()
{
return isset($_SESSION['email_id']);
}
// function confirm_logged_in()
// {
// if (!logged_in()) {
// redirect_to("index.php");
// }
// }
?>

Error in checking if email exists in MySQL database?

Sorry for the poor formatting but can anyone help me. I am first checking if the email exists in the database. This is where my problem is occuring. Everything else works fine except $checkemail.
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "charlieroth", "Charlie123", "betausersdb");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
$checkemail = "SELECT `email` FROM `users` WHERE `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$query = mysqli_query($checkemail);
if (mysqli_num_rows($query) > 0) {
// do nothing
} else {
if (validateEmail($_POST['email'])) {
$addEmail = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $addEmail);
// add email
}
}
}
function validateEmail($useremail) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $useremail)) {
// echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $useremail, 2);
return in_array($user_domain, $domain);
}
}
?>
You have an error in your first mysqli_query. Do this:
<?php
function validateEmail($useremail) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $useremail)) {
// echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $useremail, 2);
return in_array($user_domain, $domain);
}
}
$mail = addslashes($_POST['email']);
if (array_key_exists("submit", $_POST)) :
$link = mysqli_connect("localhost", "charlieroth", "Charlie123", "betausersdb");
if ( $link ) :
$checkemail = "SELECT * FROM 'users' WHERE email = '$mail' ";
$query = mysqli_query($link, $checkemail );
if (mysqli_num_rows($query) > 0) {
// do nothing
}
else {
if (validateEmail($mail) {
$addEmail = "INSERT INTO 'users' (email) VALUES ($mail)";
mysqli_query($link, $addEmail);
// add email
}
}
}
else :
echo 'Error';
endif;
endif;
?>

Can't get login success to view

so I've put in the write credentials to the login form, and it's supposed to redirect me to the home.php page which displays a successful login, however when I hit submit, the page just refreshes and doesn't do anything. If I change what the login_action loads after login it does it right, but then if I tell it to load home.php it just does nothing....Any Help?
Here's my home.php code:
<?php
session_start() ;
if( !isset($_SESSION['username']))
{
require('login_tools.php');
load();
}
$page_title = 'Home';
echo"<h1>HOME</h1>
<p>You are now logged in, {$_SESSION['username']}</p>";
echo'<p>Logout</p>';
?>
and the login_action.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
require ('../connect_db.php') ;
require ('login_tools.php') ;
list ($check, $data) =
validate($dbc, $_POST['username'], $_POST['password']);
if ($check )
{
session_start() ;
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
load('home.php') ;
}
else {$errors = $data ;}
mysqli_close( $dbc);
}
include('login.php');
?>
**login.php:**
<?php
$page_title = 'Login';
if ( isset( $errors ) && !empty( $errors))
{
echo'<p id="err_msg">Oops! There was a problem:<br>';
foreach ( $errors as $msg )
{
echo " - $msg<br>";
}
echo 'Please try again or Register</p>';
}
?>
<h1>Login</h1>
<form action="login_action.php" method="POST">
<p>
Username: <input type="text" name="username">
</p><p>
Password: <input type="password" name="password">
</p><p>
<input type="submit" value="Login" >
</p>
</form>
According to your code it is supposed to refresh. Indeed, it is not a refresh, it is the infinite loading of login.php by include it in the end of login_action.php
You should use header redirect instead of including as follows:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
if ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
require ('../connect_db.php') ;
require ('login_tools.php') ;
list ($check, $data) =
validate($dbc, $_POST['username'], $_POST['password']);
if ($check )
{
session_start() ;
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
$extra = 'home.php';
header("Location: http://$host$uri/$extra");
exit;
}
else {
$errors = $data ;
$_SESSION['Errors'] = $errors;
$extra = 'login.php';
header("Location: http://$host$uri/$extra");
exit;
}
mysqli_close( $dbc);
}
?>
In login.php
$page_title = 'Login';
if ( isset( $_SESSION['Errors'] ) && !empty( $_SESSION['Errors'])){
$errors = $_SESSION['Errors'];
//continue your code...
// at the end of the code:
unset($_SESSION['Errors']);
Based on your reply, i guess session doesn't get anything to load home. It is from:
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
this makes validate get unvalidated to send the session.
Try to change the $data into variables, as follows:
$_SESSION['user_id'] = $user_id ;
$_SESSION['username'] = $username ;
to show the message, you can use meta refresh to encertain that it really sends the login data.
If this not works, there must be something wrong with the grabbing data from the connection.
<?php # LOGIN HELPER FUNCTIONS.
# Function to load specified or default URL.
function load( $page = 'login.php' )
{
# Begin URL with protocol, domain, and current directory.
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'PHP_SELF' ] ) ;
# Remove trailing slashes then append page name to URL.
$url = rtrim( $url, '/\\' ) ;
$url .= '/' . $page ;
# Execute redirect then quit.
header( "Location: $url" ) ;
exit() ;
}
# Function to check email address and password.
function validate( $dbc, $email = '', $pwd = '')
{
# Initialize errors array.
$errors = array() ;
# Check email field.
if ( empty( $email ) )
{ $errors[] = 'Enter your email address.' ; }
else { $e = mysqli_real_escape_string( $dbc, trim( $email ) ) ; }
# Check password field.
if ( empty( $pwd ) )
{ $errors[] = 'Enter your password.' ; }
else { $p = mysqli_real_escape_string( $dbc, trim( $pwd ) ) ; }
# On success retrieve user_id, first_name, and last name from 'users' database.
if ( empty( $errors ) )
{
$q = "SELECT user_id, first_name, last_name FROM users WHERE email='$e' AND pass=SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q ) ;
if ( #mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array ( $r, MYSQLI_ASSOC ) ;
return array( true, $row ) ;
}
# Or on failure set error message.
else { $errors[] = 'Email address and password not found.' ; }
}
# On failure retrieve error message/s.
return array( false, $errors ) ;
}

Php Login issue [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Following is my php login script, There are one problem. If i put any password then it's doesn't validate the password and it's going to user panel page. where is the wrong in my code, can anyone tell me the right direction
N:B: I'M NEW IN PHP ALSO NEW IN THIS SITE.
<?php
if(isset($_POST['action']) && isset($_POST['action']) == 'Log In')
{
$uname = mysql_real_escape_string(trim(htmlspecialchars($_POST['uname'])));
$pass = mysql_real_escape_string(trim(htmlspecialchars($_POST['pass'])));
$crytpass = hash('sha512','$pass');
$err = array();
include_once("toplevel/content/manage/dbcon/dbcon.php");
// check username
$check_uname = mysql_query("SELECT uname FROM members WHERE uname = '$uname'");
$num_uname = mysql_num_rows($check_uname);
// check password
$check_pass = mysql_query("SELECT pass FROM members WHERE pass = '$crytpass'");
$num_pass = mysql_num_rows($check_pass);
/// userid
$userid = mysql_query("SELECT userid FROM members");
$re = mysql_fetch_array($userid);
$userid = (int) $re['userid'];
if(isset($uname) && isset($pass))
{
if(empty($uname) && empty($pass))
$err[] = "All field required";
else
{
// username validation process....
if(empty($uname))
$err[] = "Username required";
else
{
if($num_uname == 0)
$err[] = "Username is not correct";
}
// password validaiton process...
if(empty($pass))
$err[] = "Password required";
else
{
if($num_pass == 0)
$err[] = "Password is not correct";
}
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red>$er<br></font>";
}
}
else
{
include("user/include/newsession.php");
header("Location:user/index.php");
}
}
?>
So many thing are wrong here
Replace
if (isset ( $_POST ['action'] ) && isset ( $_POST ['action'] ) == 'Log In') {
With
if (isset ( $_POST ['action'] ) && $_POST ['action'] == 'Log In') {
Too many things to replace .. hold on while i rewrite the script for you
Edit 1
if (isset ( $_POST ['action'] ) && $_POST ['action'] == 'Log In') {
$uname = prepareStr ( $_POST ['uname'] );
$pass = prepareStr ( $_POST ['pass'] );
$shaPass = hash ( 'sha512', $pass );
$errors = array ();
include_once ("toplevel/content/manage/dbcon/dbcon.php");
if (! isset ( $uname ) || empty ( $uname )) {
$err [] = "Empty Username not allowed";
}
if (! isset ( $pass ) || empty ( $pass )) {
$err [] = "Empty Password not allowed";
}
if (count ( $err ) == 0) {
$mysqli = new mysqli ( "localhost", "root", "", "test" ); // Replace with
// DB
// Information
$result = "SELECT uname ,pass FROM members WHERE uname = '$uname' AND pass = '$shaPass'";
if ($result->num_rows > 0) {
$err [] = "Invalid username or Password";
}
if (count ( $err ) == 0 && $result) {
$userInfo = $result->fetch_assoc ();
/**
* You can do what every you like here
*/
}
}
if (count ( $err ) > 0) {
/**
* Kill the user
*/
echo "<pre>";
foreach ( $err as $value ) {
echo $value . "\n";
}
die ( "Die! Die! Die!" );
}
}
function prepareStr($str) {
$str = htmlspecialchars ( $str );
$str = trim ( $str );
$str = mysql_real_escape_string ( $str );
return $str;
}
Thanks
You shouldnt tell your users if the username was wrong, this makes it easier for brute force attemps to break in.
<?php
if(isset($_POST['action']) && $_POST['action'] == 'Log In') {
$userid = false;
$uname = mysql_real_escape_string(trim(htmlspecialchars($_POST['uname'])));
// or better
// $uname = filter_var($_POST['uname'], FILTER_SANITIZE_STRING);
$pass = $_POST['pass'];
$crytpass = hash('sha512',$pass);
$err = array();
include_once("toplevel/content/manage/dbcon/dbcon.php");
$q = mysql_query("SELECT userid FROM members WHERE uname = '$uname' AND pass='$cryptpass'");
if(mysql_num_rows($q) > 0){
$re = mysql_fetch_array($q);
$userid = (int) $re['userid'];
} else {
// username or password wrong
)
if($userid) {
// successfull login
}
}

Categories