i did this code :
file index.php:
<?php
if (isset($_POST['valider']))
{ if (!isset($_SESSION)) { session_start(); }
require("function.php");
$email = mysql_escape_string($_POST['email']);
$password = mysql_escape_string($_POST['password']);
if(!VerifierAdresseMail($email)){?>
<script>alert('invalid mail');</script>
<?php
}
else{
if(!authentification($email,$password))
{?>
<script>alert('logging failed');</script>
<?php
}
else{
header('Location: choice.php');
}}
}
?>
In function.php:
<?php
function VerifierAdresseMail($adresse)
{
$Syntaxe='#^[\w.-]+#[\w.-]+\.[a-zA-Z]{2,6}$#';
if(preg_match($Syntaxe,$adresse))
return true;
else
return false;
}
function statistics($id){
$HOST_DB ="localhost";
$NAME_DB="makempf3_captcha";
$USER_DB ="root";
$PWD_DB="";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
?><script>alert(<?php echo $cle ?>);</script><?php
$Log_query=mysql_query(
"
SELECT *
FROM tbl_captcha
WHERE user_id ='$id'
") or die(mysql_error());
$_SESSION['success'] =0;
$_SESSION['fail'] =0;
if ($Log_query == true && mysql_num_rows($Log_query) >0) {
?><script>alert('heni');</script><?php
while ($Res_user = mysql_fetch_array($Log_query) ) {
$_SESSION['success'] += $Res_user['success'];
$_SESSION['fail'] += $Res_user['fail'];
}
}
}
function authentification($mail,$pwd_U){
$HOST_DB ="localhost";
$NAME_DB="makempf3_captcha";
$USER_DB ="root";
$PWD_DB="";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$Log_query=mysql_query(
"
SELECT *
FROM tbl_user
WHERE email ='$mail'
AND user_pass ='$pwd_U'
") or die(mysql_error());
if ($Log_query == true && mysql_num_rows($Log_query) >0) {
$Res = array();
while ($Res_user = mysql_fetch_array($Log_query) ) {
$_SESSION['mail'] = $mail;
$_SESSION['pwd'] = $pwd_U;
$_SESSION['id'] = $Res_user['id'];
}
return true;
}
else return false;
}
?>
when i verify $_SESSION['id'] in choice.php, it is null, but in index.php (before redirection) it has a value. i don't understand why i lost this session variable
Your isset() check isn't sufficient, because it would only be executed if $_SESSION is NULL, and it will never be - it's an empty array instead and it always exists, even before you call session_start().
You have to always run session_start(); to be able to use sessions, even if you're only reading them. Also, $_SESSION is a superglobal, so it is never empty : http://php.net/manual/en/reserved.variables.session.php.
You can run session_start without your isset() check. From the manual:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Don't forget to run session_start in choice.php
Your Index.php should probably be like this. You should never tell the user which part of the login they got wrong..... only that it failed.
<?php
session_start();
require("function.php");
if (isset($_POST['valider']))
{
$email = mysql_escape_string($_POST['email']);
$password = mysql_escape_string($_POST['password']);
if(VerifierAdresseMail($email) && authentification($email,$password))
{
header('Location: choice.php');
}
else
{
echo "Invalid Login";
}
?>
Related
I have been trying to solve this issue couldn't, tried reading from asked questions but couldn't get it. I started the session and required it in another page but when ever i want to use it to insert some text base on the current session id, it is always zero in the database. Please,explain to me, maybe i miss understood it. Thanks!
<?php
ob_start();
session_start();
if(isset($_SESSION['$user_id']) && !empty($_SESSION['$user_id']))
{
return true;
}
else
return false;
?>
include.php
<?php
include ("login._form.php");
require ("include.php");
require("require.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$username = mysqli_real_escape_string($link, $_POST["user"]);
$password = mysqli_real_escape_string($link,$_POST["password"]);
if(empty($username) || empty($password))
{
die();
}
$row = mysqli_query($link,"SELECT * FROM `users` WHERE username ='$username'");
if($row === false)
{
echo "Query Error";
}
while($fetch = mysqli_fetch_array($row)){
if($username == $fetch["username"] && $password == $fetch["password"])
{
$_SESSION["id"] = $id;
header('Location:index.php');
}
else
die("user does'n exist");
}
mysqli_close($link);
}
login.php
?>
require("include.php");
include ("yd_sendpage_form.php");
require("require.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$user_id = $_SESSION["id"];
$text = mysqli_real_escape_string($link,$_POST["text"]);
if(empty($text))
{
die("Field Can't Be Empty!");
}
$insert = mysqli_query($link,"INSERT INTO `text`(`id`, `user_id`, `text`) VALUES ('$user_id','$user_id','$text')");
}
?>
yd_sendpage.php
Change
if(isset($_SESSION['$user_id']) && !empty($_SESSION['$user_id']))
to
if(!empty($_SESSION['id']))
And don't forget about SQL injection, your code is vulnerable to it.
More information about SQL injection in your code
$_SESSION["id"] was not set, so i changed $_SESSION["id"] to $_SESSION["user"] = $username in the login.php and other pages to $_SESSION["user"] and that works. Thanks!
i want to make toefl test. so there will be a login button. when someone login in, then the login button will be logout button. but when i login in, the login button was not changed. please help me
function to check login status (i save this function in lib_function.php):
<?php session_start(); ?>
<?php
function check_login(){
$hasil = 0;
if (isset($_SESSION['email'])) {
$mail = $_SESSION['email'];
}
if (isset($_SESSION['pass'])) {
$pass = $_SESSION['pass'];
}
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
?>
index.php:
<?php session_start();
require_once("connection.php");
?>
<?php include("lib_function.php"); ?>
<--header-->
<?php
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
this is my login process:
<?php
session_start();
require_once("connection.php");
$email = $_POST['email'];
$password = $_POST['password'];
$cekuser = mysql_query("SELECT * FROM user WHERE email = '$email'");
$jumlah = mysql_num_rows($cekuser);
$hasil = mysql_fetch_array($cekuser);
if($jumlah == 0) {
echo "<script>alert('Email has registered!'); window.location = 'index.php'</script>";
} else {
if($pass > $hasil['password']) {
echo "<script>alert('Wrong password!'); window.location = 'index.php'</script>";
} else {
$_SESSION['email'] = $hasil['email'];
header('location:index.php');
}
}
?>
You check if $_SESSION['pass'] is set in your check_login function, but you never set it during the login process.
Either set $_SESSION['pass'] or remove and !empty($pass) from check_login().
Always try to check if the Session is already active before starting one. You also might want to assign default values of say NULL to the $mail & $pass variables inside your check_login() function because at a point, you were checking if $mail and $pass were empty. What if they were not even set at all? In this case those variables would not have existed at all...
<?php
// FILE:: lib_function.php
function check_login(){
$hasil = 0;
// GET THE $mail & $pass FROM SESSION; ASSIGNING A DEFAULT NULL
// TO EACH OF THEM IF THEY ARE NOT YET SET...
$mail = isset($_SESSION['email']) ? $_SESSION['email'] : null;
$pass = isset($_SESSION['pass']) ? $_SESSION['pass'] : null;
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
// FILE:: index.php
// START SESSION ONLY IF IT IS NOT ALREADY ACTIVE:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
require_once("connection.php");
include("lib_function.php");
// HEADER HERE
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
try this:
function login($email) {
$_SESSION['email'] = $email;
}
function is_logged() {
return isset($_SESSION['email']);
}
function logout() {
session_destroy();
}
So I've made a login system here, it initiates a session, checks if the password is correct and then sets the session variables.
Here are a few things you might want to note:
It successfully logs in
There is no problem with the mysql connection
All files are places correctly in folders
There are no warnings or error messages
The MYSQL Table structure is correct and there are no errors in database
Note: all functions I'm about to define are in the same file 'functions.php'
Over here we have the session function
include_once("global_config.php");
include_once("db_connect.php");
function sec_session_start()
{
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE)
{
echo "Could not initiate a secure session";
exit;
}
$cookieparams = session_get_cookie_params();
session_set_cookie_params($cookieparams['lifetime'],$cookieparams['path'],$cookieparams['domain'],$secure,$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
The global_config file define the mysql password, database, user and host and the db_connect file simply return the mysqli_connect to connect to the database.
And this over here is the login function
function login($user,$pass){
sec_session_start();
$link=linkit();
if(empty($user) || empty($pass) || !isset($user) || !isset($pass)){
echo "Error Code: 313, Please contact network administrator for more information";
exit;
}else{
$usercheck = "SELECT `id`,`username`,`password`,`salt` FROM `".LOGINTABLE."` WHERE `username`=? LIMIT 1";
if($stmt=$link->prepare($usercheck)){
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$username,$realpassword,$salt);
$stmt->fetch();
$stmt->close();
if(empty($realpassword)){
echo 'Unrecognized Username, Please enter a valid username';
exit;
}else{
if($realpassword===$pass){
$_SESSION['username'] = $user;
$_SESSION['user_id'] = $id;
$_SESSION['login_string'] = hash('sha512',$pass);
return true;
}else{
echo "Invalid Password!";
exit;
}
}
}
}
}
The linkit() method is the one defined in db_connect.php which returns mysqli_connect. Also note that the script successfully makes it to setting the Session variable which means that it does return true.
NOW THE PROBLEM is this, when I'm checking for logged in status
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}
AND FINALLY, this is WHERE I process my login script. Also note that there are no errors in POST methods or anything else. They all work fine.
This is in a separate php file and NOT in the functions.php
<?php
include_once '../includes/functions.php';
if(empty($_POST['loginuser']) || !isset($_POST['loginuser']) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['password']) || empty($_POST['password']))
{
echo "Error Code: 412, Please contact network administrator for more information";
exit;
}else{
if($_POST['loginuser']==="true")
{
$user = $_POST['id'];
$pass = $_POST['password'];
if(login($user,$pass)==true)
{
echo "Logged In!";
}else
{
echo "Failed to login, check your username or password";
}
}
}
?>
Additional Information :
The response I get is "Logged In"
Session is successfully creaated
PROBLEM: When I check for the login status, it returns false despite of having the session variables set.
In check_login you are hashing the password and then compare the unhashed password
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass ){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}
If I want to protect my files (pages), I use this code:
<?php
if( isset ($_SESSION['user']['name']) && $_SESSION['user']['ip'] == $_SERVER['REMOTE_ADDR']) {
echo'';
} else {
header ("Location: index.php");
}
?>
I put this code in each case from above on a page. So, if you're not logged in you will return to the login form.
The problem is, I can not really work with sessions and I would not know if I would make it into what it should be. Class.users a If anyone could help me I would be very happy. The problem with logging is that he probably does not use the sessions ... Here my sessions:
<?php
if($_SERVER['REQUEST_METHOD']== 'POST')
{
//echo 'Request started';
$username = $_POST['username'];
$password = $_POST['password'];
$sth = $db->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->bindParam(':username', $username);
$sth->bindParam(':password', $password);
$sth->execute();
$total = $sth->rowCount();
if($total == 1)
{
//echo 'Row found';
$row = $sth->fetch();
if($row['activated'] == 1)
{
//echo 'User is activated';
$_SESSION['user']['name'] = $username;
$_SESSION['user']['loggedin'] = true;
$_SESSION['user']['id'] = $row['id'];
$_SESSION['user']['timestamp'] = time();
$_SESSION['user']['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user']['time'] = date('d/m/Y - H-m-s');
header ("Location: ./home.php");
exit();
}
else
{
echo '<div id="login-form-alert"><div class="alert alert-warning"><h5>Uw account is niet actief. Contacteer aub de beheerder op het mail adres info#rallypodium.be<h5></div></div>';
}
}
else
{
echo '<div id="login-form-alert"><div class="alert alert-danger"><h5>Uw wachtwoord of gebruikersnaam klopt niet.<h5></div></div>';
}
}
?>
I'm looking here for a few weeks ... Who can help me, is my hero!!
You're missing session_start() at the top of your pages.
<?php
session_start();
if( isset ($_SESSION['user']['name']) && $_SESSION['user']['ip'] == $_SERVER['REMOTE_ADDR']) {
echo'';
<?php
session_start();
if($_SERVER['REQUEST_METHOD']== 'POST')
{
Put session start at first line of each page where this session should be used.
session_start();
/* #var $_SERVER type */
//use identical (====) operator instead instead
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
and here don't access Superglobarl $_POST array directly, use some filter input function instead (e.g. filter_input(); and etc)
/* #var $username type */
$username = $_POST['username'];
$password = $_POST['password'];
}
I'm getting an undefined variable error for $id variable in lines 15 & 21, could someone please explain why? I can't see what the problem is.
<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password, $id))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['id'] = $id;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password'], $_SESSION['id']);
}
}
function databaseContainsAuthor($email, $password, $id)
{
include 'db.inc.php';
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT COUNT(*) FROM author
WHERE email='$email' AND password='$password'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for author.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The variable $id is defined in databaseContainsAuthor($email, $password, $id), then stored in the $_SESSION['id'] session so naturally $id = mysqli_query($link, $sql); should have passed but it's not?
Variables changed (or defined) inside a function will not affect the rest of the script. For example:
<?php
function changeVariabe($person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Alice!
This can be avoided by passing the variable by reference, like this:
<?php
function changeVariabe(&$person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Bob!
You can also use global variables, like this:
<?php
function changeVariabe() {
global $person;
$person = 'Bob';
}
$person = 'Alice';
changeVariable();
echo "Hello $person!"; // Outputs: Hello Bob!
a few things
the variable $id should be defined (not required but good practice) before you use it
so for example
$id = NULL;
if (databaseContainsAuthor($_POST['email'], $password, $id))
also setting the $id inside the databaseContainsAuthor function doesn't mean that $id will change outside the scope of that function.
You could make it global but that is considered bad practice
also your function databaseContainsAuthor
contains this code
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
which will return TRUE or FALSE. but note that once the code returns a value, none of the code after it will be run
which means this part might as well be commented out, as it is after the return statement it will never be run
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}