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!
Related
How do I add Login Details confirmation if incorrect? what I want to happen is when the user puts his/her credentials their userID and Password are correct but the user type is wrong if the user presses the login button it will say "incorrect credentials" and same goes with userID and Password if they input the wrong credentials
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
}
}
}
}
?>
Dharma Is correct!
You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries!
If you embed a string in some SQL targeting MySQL, you must escape the string with MySQL's function for this purpose (mysqli_real_escape_string) and trigger db query to input on failed login.
Modified code:
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
$loginFlag = true;
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
$loginFlag = true;
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
$loginFlag = true;
}
else {
$loginFlag = false;
}
}
}
if($loginFlag == false){
#real_escape_string is used to prevent sql injection
$username = real_escape_string($_POST['username']);
$password = real_escape_string($_POST['password']);
$usertype = real_escape_string($_POST['usertype']);
# query assume table name log
$sql_query = "INSERT INTO log (username, password, usertype, ip_address)
VALUES ('$username ', '$password ', '$usertype ', '".$_SERVER['REMOTE_ADDR']."')";
}
}
?>
My cookies are not saving, I am using PHP 5.
Code:
require 'dbcon.php';
$sql = "SELECT * FROM accounts";
$result = $conn->query($sql);
$username = $_POST['username'];
$password = $_POST['password'];
$row = mysql_fetch_row($result);
setcookie("ID6", $row['ID'], time() + 60*60*24*31*12, "/") or die("Cookie could not be set. <a href='index.php'>Try again!</a>");
if(!isset($_POST['username']) || !isset($_POST['password'])) {
header("Location: index.php");
exit();
}
while($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) {
if($password == $row['password']) {
if($row['accdel'] == 1) {
echo("You are banned.");
exit();
}
echo "Logged in with cookie:" . $_COOKIE['ID6'];
exit();
}
else {
echo "The account does not exist, or you have put in the wrong log in.";
exit();
echo"That's not an account name though...";}
}
}
?>
Please help. Is the selected sql even a settable cookie value? (Please make it simple. I do not know much about php nor cookies.
https://www.jqueryscript.net/other/E-commerce-Cart-Plugin-For-jQuery.html
I tried save cookies with PHP many days never work.
Maybe try jquery.
The ID wasnt got from the database because it was not in the while loop.
How do I get a user_id for a PHP file from another PHP file. I'm using $_SESSION['user_id'] to do it but it's not working for me. Can anyone show me how to do it and where the $_SESSION['user_id'] should be placed in the PHP files, or if there is a better way of doing it. I think I have it placed in the right place in the login.php file but not sure about fitness.php. I'm using them for my Android app. The two PHP files are below. Any help will be greatly appreciated, thank you.
login.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT username, password, user_id FROM user WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if($username == $error || $password == $error) {
echo "Login Failed <br>";
}
elseif($result->num_rows > 0){
$_SESSION['user_id'] = 'user_id';
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Login Successful";
// header("location: login.php");
}
else{
echo "Login Failed <br>";
}
}
?>
fitness.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['pulseOne']) && isset($_POST['pulseTwo']) && isset($_POST['pulseThree'])){
$pulseOne = $_POST['pulseOne'];
$pulseTwo = $_POST['pulseTwo'];
$pulseThree = $_POST['pulseThree'];
$fitnessResult = 100;
$overall = 30000;
$fitnessScore = -1;
$fitnessScore = $pulseOne + $pulseTwo + $pulseThree;
if($fitnessScore != 0){
$fitnessResult = $overall/$fitnessScore;
$fitnessResult = round($fitnessResult, 0);
}
else{
$fitnessResult = NULL;
}
// $fitnessResult = mydivide($overall/$fitnessScore);
$date = date("Y-m-d");
$time = date("h:i:sa");
// $user_id = $_POST['user_id'];
$query = "INSERT INTO `fitness`(`fitnessScore`, `fitnessDate`,`fitnessTime`, `user_id`) VALUES ('$fitnessResult','$date','$time', 42)";
$result = mysqli_query($conn, $query);
if($pulseOne == $error || $pulseTwo == $error || $pulseThree == $error){
echo "Insert Failed";
}
elseif($result > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Insert Successfully";
}
else{
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "Registration Failed";
exit;
}
echo "Insert Failed";
}
}
?>
So many things to note here, first of all restructure your If and else statements if you are using else if use them properly. you are using mysqli no prepared statements plain query, try to learn better way so your code dont stay vulnerable. Last but not the least you are facing this proble because you are trying to use Session variable value with post keyword, try this:
$user_id = $_SESSION['user_id'] ; and it will be solved.
you can do like this First save your session variable in another variable than try to insert in database
$user_id = $_SESSION['user_id'] ;
Try to echo it thisway
echo $user_id;
once you get it use it or insert it in database
change your code from
$_SESSION['user_id'] = 'user_id';
this to
$_SESSION['user_id'] = $row['user_id'];
I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...
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";
}
?>