Consider File A, File B, and File X, where both File A and File B include the session instance that is File X.
File X has a variable initialized like so:
$login_order_submitted = false;
File A has a branch of code (that I know is being executed) as follows:
$login_order_submitted = true;
header('Location: FileB.php');
exit();
File B has a conditional such that:
<?php
if ($login_order_submitted === true) {
?>
<script>
alert('Order Successfully Submitted!');
</script>
<?php
/* now reset the order submitted variable */
$login_order_submitted = false;
}
?>
Why is my code in File B falling through (the script/alert isn't running) when it's being set to true in the file (File A) that redirects to it?
The code for File X is below.
<?php
include('db_const.php');
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Selecting Database
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=$connection->query("SELECT store_name, store_id FROM Store WHERE store_id='$user_check'");
$row = $ses_sql->fetch_assoc();
$login_user_name =$row['store_name'];
$login_user_ID = $row['store_id'];
$login_order_submitted = false;
if(!isset($login_user_name)){
mysqli_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
use $_SESSION["login_order_submitted"] instead of $login_order_submitted
Related
I am creating a login for a website. I can get the code below working: It lets me log in! Yet I can't get a start session to work: People can still get to my pages via URL.
Log in PHP:
<?php
//calling connection to database
include "connection.php";
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
Start session code which says undefined variables:
<?php
include"includes/loginrequiredb.php";
if($_SESSION['username'] !=$user){
session_destroy();
header("Location: view.php");
die();
}else
{
echo "welcome to the site you have logged in" . $_SESSION['username'];
}
?>
Without starting the session you can not get the values from $_SESSION.
You just need to start session in your both files as:
session_start();
Note that you need to start_session() in both files only in just welcome file.
Side note:
I suggest to also use isset() for checking either value set or not.
Start the session with session_start and Add a session verification file in adminmain.php page.
<?php
//calling connection to database
include "connection.php";
#session_start();
//session
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
##### file verify.php #####
<?php #session_start();
if (#$_SESSION['username']!=$user) {
header ("location: index.php");
exit;
}
?>
As this page is owned by it users, so it has each credentials to enter it which it is by using login form of php (that's what I know so far, I am not very good in php, to be honest).
The problem I do really guess about this must be in the using of session function (and this is the most complicated things to me know, I am not very familiar of using this.)
In the config of the form, I set the session like this (Well, I just copy paste the code from somewhhere) as follow:
// User Redirect Conditions will go here
if($count==1)
{
// Save type and other information in Session for future use.
$_SESSION[type]=$row[0];
$_SESSION[Region]=$row[1];
$_SESSION[myemail]=$myemail;
// if user type is ACTAdmin only then he can access protected page.
if($row[0] == 'ACTAdmin') {
header( "location:index.php");
}
else {
header( "location:login.html");
}
}
else
{
header("location:login.html");
}
// Closing MySQL database connection
$dbh = null;
In the head of the home page (and in each all related pages), I write a session start there like this:
<?php
include('UserSessionAdmin.php');
?>
In which it will get the data from UserSessionAdmin.php:
<?php
session_start();
if($_SESSION[type]!='ACTAdmin'){
header('location:login.html');
exit();
}
include('configPDO.php');
?>
What is included in the configPDO.php is here:
<?php
// mysql hostname
$hostname = 'mysql.com';
// mysql username
$username = 'alkushh';
// mysql password
$password = 'alkush';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=user", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It's been more than two days for me just to solve it but I don't have any idea how to. Some people who are experts in here may help me with this thing, please.
Thank you and regards,
Here is the full script that define the $count==1
<?php
// Start Session because we will save some values to session varaible.
session_start();
// include connection file
include("configPDO.php");
// Define $myusername and $mypassword
$myemail=$_POST['myemail'];
$mypassword=$_POST['mypassword'];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Type,Region FROM user WHERE myemail = :myemail AND mypassword = :mypassword");
// bind paramenters, Named paramenters alaways start with colon(:)
$STM->bindParam(':myemail', $myemail);
$STM->bindParam(':mypassword', $mypassword);
// For Executing prepared statement we will use below function
$STM->execute();
// Count no. of records
$count = $STM->rowCount();
//just fetch. only gets one row. So no foreach loop needed :)
$row = $STM -> fetch();
// User Redirect Conditions will go here
if($count==1)
.....
.....
Here it is
if ( $count == 1 ) {
$_SESSION['login_id'] = $row['id']; // i prefer to name it login_id, you can use $row['id'] or $row[0]. but i prefer to write with the column name
if ( $_SESSION['login_id'] == 1 ) { // it means if login id = 1 then go to index.php
header("location: index.php");
} else {
header("location: login.html");
}
}
else { header("location: login.html"); }
i cut session region because you didnt have a region column and also i cut session myemail because you didnt need it
UserSessionAdmin.php
<?php
session_start();
if ( $_SESSION['login_id'] == 0 || $_SESSION['login_id'] == '' ) {
header('location: login.html');
exit();
}
require_once('configPDO.php');
?>
Please turn on your error reporting to see, that there is no constants such as type, Region, myemail. Use " or ' around parameter of session:
if (strcmp($_SESSION['type'], 'ACTAdmin') !== 0) {
header('location:login.html');
exit();
}
My connection file is conn.php, adminname and password are the table field name and form text box name. when this code run on server FTP it shows No database selected. But i include connection file and update database on FTP server. This code is run on local wamp server.
**my login coding is:**
// this is my login page.
<?php
session_start();
// start here session
include('conn.php');
// here include connection file
if(isset($_POST['login']))
{
$sql="select * from admin where adminname='".$_POST['adminname']."'and password='".$_POST['password']."'";
// this is my sql query which select adminname and password in table
$result=mysql_query($sql) or die(mysql_error());
if($result)
{
$row=mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$_SESSION['admin']=$row['adminname'];
header("location:home.php");
}
else
{
header("location:index.php");
}
}
}
?>
add one line in conn file after getting connection from database
<?php
mysql_select_db ( string $database_name);
?>
Make sure about few things:
First check if you have created a database or not?
Make sure you entered the correct db_hostame, db_username, db_password, dbname
tricky way to make a database connection that works in your localhost and real server is:
$host = $_SERVER['HOST_NAME'];
if( $host == "localhost" ){
// localhost settings
}
else{
// Server Settings
}
it's just a simple trick.
hello this is my first post on stackoverflow i am at beginner level at php, mysql and work on a php log in page connected to a mysql database which i did try to test through xampp and getting the following error message
Warning: include(../storescripts/connect_to_mysql.php): failed to open stream: No such
file or directory in C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php
on line 15
Warning: include(): Failed opening '../storescripts/connect_to_mysql.php' for
inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\myonlinestore
\storeadmin\admin_login.php on line 15
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in
C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php on line 18
That information is incorrect, try again Click Here
I was able to successfully connect to the mysql database through dreamwavercs6 on win7 64bit and created a user for the db as also i created a administrator with full privileges in the created admin table. With a successful log in it should direct you to a follow up page called index.php which is a second index page only for admins to choose tasks, located in a subfolder in the same directory. The home page index.php is located here C:\xampp\htdocs\myonlinestore\index.php\
the file with the script called admin_login.php is shown under here
<?php
session_start();
if (isset($_SESSION["manager"])){
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])){
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]);
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND
password='$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount == 1){
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
the script connect_to_mysql.php under here
<?php
$db_host = "localhost";
$db_username = "user";
$db_pass = "user";
$db_name = "myonlinestore_db";
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to
mysql");
mysql_select_db("$db_name") or die ("no database");
?>
the script index.php which is the landing page where on successful login from admin_login should redirect you to, under here
<?php
session_start();
if(!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i', '',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND
password='$password' LIMIT 1"); // query the person
$existCount=mysql_num_rows($sql); // count the nums
if ($existCount==0){//evaluate the count
echo "Your login session data is not on record in the database";
exit();
}
?>
the problem is that i can not log in through my firefox browser and getting the error as mentioned at the top. All addons,extensions in my firefox browser are on disable and accepting cookies is selected, can anyone help to fix this problem?
Many thanks in advance
Here in your script you are not being able to include your connect_to_mysql.php file.
include "../storescripts/connect_to_mysql.php";
You are trying to provide relative path. Make sure you are properly able to access that file from relative path you are including. i.e. your admin_login.php file.
You can try passing absolute path in your include:
include "C:\xampp\htdocs\myonlinestore\storescripts\connect_to_mysql.php";
please check path in your file manager if it is correct absolute path.
Remove one of the dots from the include("../if the scripts are in
C:\xampp\htdocs\myonlinestore\storescript.
From
C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php
"../" will take you to htdocs, so you need "./" to get to htdocs\myonlinestore
may be it will help you.
<?php
$server = "localhost";
$connection = mysqli_connect ($server,"root","","your_database_name");
if(!$connection){
// if not connected it will gives the error here
echo "server not found".mysql_error();
}
else{
echo "Connected";
}
?>
I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?