Session script not setting variable - php

I'm new to sessions and don't think my code is working correctly.
My aim is to use PDO and not SQL, but as I'm also new to PDO too, I'm getting a little stuck.
I'm trying to set up my $who as a session but things are getting confusing for me as I go between SQL and PDO. Can you help me make things kosher?
<?php
require_once('/scripts/include.php');
require_once('/scripts/includePDO.php');
$error = '';
$form = $_POST['submit'];
$email = $_POST['email'];
$password = $_POST['password'];
if( isset($form) ) {
if( isset($email) && isset($password) && $email !== '' && $password !== '' ) {
$sql = "SELECT * FROM tbl_users WHERE email = :email and password = :password";
$q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':email',$email,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
$r = $q->fetch(PDO::FETCH_ASSOC);
if(($r)!=0)
{ //success
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
$_SESSION['logged-in'] = true;
$_SESSION['who']=$answer;
//If the login details are entered and they match those in the database, forward to new page.
header('Location: /social3/home/');
exit;
// If information is wrong or missing, provide error message.
} else { echo "Sorry, something hasn't worked. Are you entering all the information correctly?"; }
}
}
?>
I think everything is fine until I get to //success and then I lost my way.
----- Additional session question ----
At the top of each of my website pages, I include a php file that allows PDO to connect to my database. This is necessary as most of my pages use PDO queries.
But looking back at that coding now, it, for some reason, has some session coding at the top. Should this be there (taking into account, I assign a session on an entirely different page?
<?php
session_start();
$host = "xxxx";
$db = "xxxx";
$user = "xxxx";
$pass = "xxxxx";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
?>
--- Further questioning ---
So, finally... more session and PDO wonderings.
At the top of each page, I include a file to ensure the user is logged in, if not they get forwarded to the login page.
I'm changing this code to PDO from SQL also, and obviously have gaps in my PDO knowledge which show in the below code. Help?
<?php
session_start();
$who = $_SESSION['who'];
$host = "xxx";
$username = "xxxx";
$password = "xxxx";
$db = "xxx";
#mysql_connect(:host,:username,:password);
$q = $conn->prepare($sql);
$q->bindValue(':host',$host,PDO::PARAM_STR);
$q->bindValue(':username',$username,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
#mysql_select_db($db) or die("error");
// is the one accessing this page logged in or not?
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
// not logged in, move to login page
header('Location: /social3/');
exit;
}
?>

You are using PDO, so these line will not work -
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
You have already fetched the row and stored it in $r, so you just need -
$answer = $r['id'];
in response to your edit.
The session_start(); that is on the top of your included php code/page is necessary. Without it you could not do $_SESSION['logged-in'] = true; & $_SESSION['who']=$answer;. You need to start a session in order to set session values, and it must be before any data/headers are sent. Take a look at the manual - http://php.net/session_start

Related

PHP Session 5.4 to 5.6

I have created a website lately with a group of students, but were having some troubles.
We created the website in php 5.4 on a localhost and it worked perfectly.
But now we wanted to get the site online and the webhosting is using a different version of php(5.6).
So now the session does not start.
It redirects us to the homepage, but we are not logged in.
We were thinking that it was because of the version of php, since it did work at first.
<?php
include_once 'connect.php';
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['gebruiker'];
// SQL Query To Fetch Complete Information Of User
$ses_sql="select email_adres from gebruiker where email_adres='".$user_check".'";
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: login.php'); // Redirecting To Home Page
}
else{
header('Location: acountgegevens.php');
}
?>
<?php
include_once 'connect.php';
function logincheck(){
if(isset($_POST['submit'])){
$error = 0;
// declare variables
$email = null;
$password = null;
// check if email address has been set
if (isset($_POST['email_adres']) &&
!empty($_POST['email_adres'])) {
$email = addslashes($_POST['email_adres']);
}
// check if password has been set
if (isset($_POST['password']) && !empty($_POST['password'])) {
$password = md5($_POST['password']);
}
if ($email == null || $password == null) {
$error = 1;
}
// query database for user credentials
$db = new PDO('**');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT *
FROM gebruiker
WHERE email_adres = :email
AND wachtwoord = :password
LIMIT 1");
$statement->execute(array(':email' => $email, ':password' => $password));
$result = $statement->fetch(PDO::FETCH_OBJ);
if (!$result) {
$error = 1;
} else {
session_start();
$_SESSION['gebruiker'] = $email;
var_dump($_SESSION);
?>
<script>location.href='index.php'</script>
<?php
}
return $error;
}
}
?>
These two files are included, but we cant figure it out.
Could someone help?
I would hazzard a guess that your connect.php has not been changed to match the hosting companies host/user/password and therefore is outputting an error message.
This of course means that session_start() , which was placed after the connect.php and therefore after your script has attempted to send something to the browser, will not work.
You are only seeing the result of the failed session_start() but I would check the connect.php is configured correctly for its new hosting location

PHP login got Too Many Redirect Loop error

Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.

My if / else statement doesnt work for my custom php login script

Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "project";
$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$prepared = mysqli_stmt_init($connection);
$request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
mysqli_stmt_bind_param($prepared, "ss", $name, $password);
$result= mysqli_stmt_bind_result($request);
$rows_counter = mysqli_num_rows($result);
mysqli_stmt_close($prepared);
if ($rows_counter > 0) {
$_SESSION['member'] = $name;
header("location:../../success.php");
}
else {
header("location:../../relogin.php");
}
}
Here is my input and approach to your code.
First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.
Before going and building a complete login system and put if statement or make prepare statement with inputs etc.
Make your solution in small working chops and put the puzzle together.
You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.
I removed the if statement and a lot and just focused to see if I get some thing returned, I did not.
You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.
I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name, call it username, database username call it dbUser or dbUsername etc.
And if you want to check your code returning some thing or not, use var_dump($someVariable).
Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:
$username = "user1";
$password = "1234";
The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.
Here is my suggestion:
<?php
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// Check connection
if ($connection->connect_error)
{
header("location:maintenance.php");
exit();
// or for debugging, activate following line
//die("Connection failed: " . $connection->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
//if username and password empty stop login
if (!$username || !$password)
{
//do something, die is only example
die ("Not all the fields were filled in");
} else
{
login_check($username, $password);
}
function login_check($username, $password)
{
global $connection;
//sql statements is corrected, change field name to username
$sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$output = $stmt->get_result();
$row = $output->fetch_array(MYSQLI_NUM);
$stmt->close();
//print what comes out in $row
//print_r($row);
//check if $row has data
if ($row)
{
echo "success do something";
$_SESSION['member'] = $username;
} else
{
echo "fail do something";
}
}
After defining the function login_check(), you should also call it (if the conditions are right):
function login_check() {
// your implementation as above
}
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
As a side note, it is good practice to also explicetely close the connection before redirecting.
Edit
as KhomeHoly comments, only call the function when necessary...
You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.
So what you need to do is the following:
// your script as it is right now
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!
Something like this would work, depends on your requirements
if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
login_check(); // actually call the function
}
The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)
Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.
Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.
header("location:../../success.php");
exit();
Why?

How do i write restrict access to a page?

I wrote custom login script for users to login to the main control page. I found out that even when users are not login they can still visit the main control of which I want someone to help me to write a restrict access to page().
Please look through my php login script and based on that code help me write the restrict access to the main control page. assume that my main crontrol page is: cecontrolpage.php
I know we use $_SESSION to that but I have little idea of it.
this is my login.php code which is working fine:
<?php
Session_start();
$Email = $_POST["email"];
$Password = $_POST["password"];
$cn = "localhost";
$db_username = "root";
$pas = "***";
$db_name = "cemembers";
//Open a connection to a MySQL Server
if ($Email && $Password) {
$connect = mysqli_connect($cn, $db_username, $pas, $db_name) or die("Could not connect to database");
//sending MySqli query
$query = mysqli_query($connect, "SELECT * FROM users WHERE Email= '$Email'");
$numrows = mysqli_num_rows($query);
//After PHP declaration we are going to create index file[form]
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($query)) {
$dbEmail = $row["Email"];
$dbPassword = $row["Password"];
}
if ($Email == $dbEmail && $Password == $dbPassword) {
header("location:ce membership birthday system control_pannel.php");
#$_SESSION("Email") == $Email;
} else
header("location:index.php?login_attempt=1");
} else
header("location:index.php?login_attempt=2");
} else
header("Location:index.php?login_attempt=0");
?>
please can someone help me write the php code to restrict access to cecontrol.php ??
Please STEP by STEP with php comments on each part.
First you need to check if the user is logged in:
you do that by checking if the session has been set.
//Check if the user is logged in
function userlogged_in()
{
return(isset($_SESSION['userid']))?true:false;
}
Then you need to redirect the user to a page that says the access to is not authorised, they need to be logged in to view that page:
You do this by checking if the userlogged_in function returned a true or false
function user_restricted()
{
if (userlogged_in()=== false)
{
header('Location: permission.php ');
exit();
}
}
Then you need to call the user_restricted() function on each page, just after starting the session.
First you have to save user values in session after authentication from database like
$_SESSION['username'] = "name"; $_SESSION['user_id'] = 1;
function check_session() {
session_start();
if ($_SESSION['user_id']=='')
{
// redirect to login
}
}
On every page that you want to restrict access you can call check_session().

PHP session_start question

So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.

Categories