PHP Coding Logic - php

I have some code that always is returning $aid=1 within an else/if statement. Can anyone help me figure out why this may be happening within the logic?
<?php
session_start();
require('includes/config.php');
if(!$user->is_logged_in()){ header('Location: login.php'); }
include_once("config.php");
if(isset($_SESSION['account_id'])) {
$aid = $_SESSION['account_id'];
} else if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
} else if(isset($_GET['aid'])) {
$aid = $_GET['aid'];
} else {$aid='1';}
include_once('includes/top.php');?>
Quick background (if it helps)... This is for a login. Once a client signs in I am trying to get only their data within the database to show. I have all of the correct data being pulled, but I cannot get the logged in user to call in the correct account_id. If I were to change the last $aid=1 to $aid=2, then it would correctly pull all of account_id=2 information, but it would do it for every logged in person.
Any advice is greatly appreciated.
Thanks!
Below is the login function
<?php
require_once('includes/config.php');
if( $user->is_logged_in() ){ header('Location: main.php'); }
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: main.php');
exit;
} else {
$error[] = 'Invalid username/password or your account has not been activated.';
}
}
$title = 'Login';
require('layout/header.php');
?>
There is some html below the php that calls in the form. I can load that up if that helps too. Thanks!
Also, the account_id's are managed within the admin section. There is an associated account_id within the clients table of the database that specifies which account each user has.

If else condition page your are not post and get any data's so post and get method will not work. Then u need to make sure session is set or not. After that only u can able to find out the exact value of $aid.

Related

Login / Logout Session Issue

I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...

php how to redirect user to index.html when sucessfully logging in

hi i am having problems with a login script for my website i need the script to redrect the user to index.html if the login details are correct. if you could help me at all it would be greatly appreciated.. thank you...
here is my script for checking the details ==>
<?php
include('config.php');
?>
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
any help would be greatly appreciated.. thank you.
UPDATE: As #Dagon corrected me..
To redirect user back to index.html, you can use the following:
header('Location: http://example.com/index.html');
exit;
after successful login.
So your source code is not preferly the best to this way of login, but even in this way you should make a redirection after login.
It you can do with JavaScript, exactly i recomend you tu use jQuery API, which will help you to improve many things on your site.
So in your situation i recomend you this way of solution:
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
}
So if you noticed, this line
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
writes a line into html document which call a function to load through jQuery a file with parameter that the user is logged in.
Don`t forget to include jQueries source code in head
Use the header() function after setting the user information in $_SESSION.
// If the password is good, we don't show the form
$form = false;
// We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location: http://example.com/index.html');
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location:http://sitename.com/index.php');
?>

PHP Page isn't storing cookies

I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

PHP Registration with sessions and user access

Im trying to understand how to build a user registration with PHP and MySQL.
I have built a form that the user can fill out and the information is then stored in my table.
error_reporting(E_ALL);
include_once ('connection.php');
// Required field names
$required = array('firstname', 'lastname', 'email', 'password', 'accounttype');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$accounttype = $_POST['accounttype'];
$query = "INSERT INTO users(firstname,lastname,email,password,accounttype) VALUES (:firstname,:lastname,:email,:password,:accounttype)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':accounttype', $accounttype);
$stmt->execute();
if(!$query){
echo 'Whoops, something went wrong!';
} else {
echo $accounttype;
if($accounttype == '1'){
header ('Location: /england/dashboard.php');
exit;
};
if($accounttype == '2'){
header ('Location: /ireland/dashboard.php');
exit;
};
};
};
When the users completes the form they're either reidrected to a different page based on their account type.
On those pages I need to somehow check to see if the user is of accounttype 'X'. So if they land in
header ('Location: /ireland/dashboard.php');
their account type value will be equal to 2, so only people with an account type of 2 can visit the above mentioned.
I've read about session variables, but where do I set these?
session_start(); // this at top of page
if($accounttype == '1'){
$_SESSION['accountType'] = 1; // or $accounttype
header ('Location: /england/dashboard.php');
exit();
};
if($accounttype == '2'){
$_SESSION['accountType'] = 2; // or $accounttype
header ('Location: /ireland/dashboard.php');
exit();
};
In england/dashboard.php
session_start();
if($_SESSION['accountType'] !== 1) header('location: login.php');
In ireland/dashboard.php
session_start();
if($_SESSION['accountType'] !== 2) header('location: login.php');
Start the session where you built form ,
session_start();
$_SESSION['account_type'] = 2;
and in the dashboard.php just get your session variable to check the account type.
if(($_SESSION['account_type'] == 2)) {
header('`dashboard.php');
} else {
// someother page or restrict access
}
simply begin your php script with session_start();
assign session vars with $_SESSION['whatever'] = "something";
You must begin your script with session_start(); on any page you wish to use session variables though.
To destroy a session and all associated vars simply use session_destroy();
One way to do this:
Use a 'Head/Config' file that you require_once() on every page
In this file store info in the session variable like this:
$_SESSION['myCustomValue'] = $accountType;
Then based on what is stored in there you can redirect:
if ($_SESSION['myCustomValue'] = 2):
header ('Location: /ireland/dashboard.php'); // oh yea!
endif;
First at least SHA1 hash the password. Store the result of that and not the actual password in your database. To test for login, you SHA1 hash what they gave you and compare the hashes. You should also salt the password before hashing, but just hashing would be a good start.
Also give your user record an id that can be used as the primary key.
You basically do a start_session() first thing in your script. This will either start a new one or attach to the one they have.
Then after they login/register and you know what their user id is store it in the session with $_SESSION['userid'] = $userid;
To test for login: isset($_SESSION['userid']) will return true.
Edit
Once you alter your table to have the id as an auto incrementing, primary key, your insert above does not need to change, but you get that ID by calling $dbh->lastInsertId()
You need to decide what you want to store in session data. When a person completes the form, passes validation and is saved in the DB, you might want to do this:
if(!$query) {
echo 'Whoops, something went wrong!';
} else {
session_start();
$_SESSION['account_type'] = $accounttype;
// Carry on functionality...
}
And at the beginning of your script, you can prevent existing users accessing the registration form:
session_start();
if(isset($_SESSION['account_type'])) {
header('Location: /ireland/dashboard.php');
}

Categories