Updating user information - php

I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>

Related

i am try to create session but always session empty

I want to try to make a session but always session Empty.Use this code rate this product this link send an email open email and click link Active than code working session empty please help me...
<?php
session_start();
include("myhomeportal/setting/config.php");
$conform = $_GET['conform'];
$query = mysqli_query($conn, "SELECT * FROM item_users where com_code='$conform'");
$row = mysqli_fetch_array($query);
if ($row) {
// now update `com_code`
$sql = "UPDATE item_users SET com_code='active', user_type='user' WHERE com_code='$conform'";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
$inventory_id = $row['inventory_id'];
$active = $row['com_code'];
$_SESSION['sess_active'] = $active;
header("Location: category.php?inventory_id=$inventory_id");
} else {
// confirm code not found, show error
}
?>
Try to debug first.
Echo this $row['com_code']; then $_SESSION['sess_active'].
If they print something then go ahead.
There ir an error in your test page.
"sir other page is not working session just simple test code – Pankaj"
Instead you are only testing, you must start the session always with session_start() in every .php you want to use session.
Solving testing page.
"<h1>welcome <?php session_start(); echo $_SESSION['sess_active'];?> </h1> – Panka"
Note from w3schools:
The session_start() function must be the very first thing in your document. Before any HTML tags.
you are writting some html code before start the session, you should do that way:
<? php session_start(); ?>
<h1>welcome <?= $_SESSION['sess_active']; ?> </h1>
You can read more about this https://www.w3schools.com/php/php_sessions.asp

set session variable to user_id when user logs in

I'm setting up a login/logout and I'm trying to send the users id number to other pages in the website so that I can manipulate the database when I want.
I use a query to match email/password and log in user(n.b. this is not the full code and not the problem, I'm matching emails and passwords)
$find= mysqli_query("SELECT * FROM users WHERE email='$ema' and password="$pw");
Then I fetch an array and start a session which I then check on pages further on in the website.
if(mysql_num_rows($find) == 1){
$row = mysql_fetch_array($result, MYSQL_BOTH);
$id= $row ['id'];
session_start();
$_SESSION['Login']= $id;
// Redirect - I use JS to send users to next page
}
else {
echo '<script type="text/javascript">';
echo 'alert("Invalid Username or Password");';
echo 'history.back();';
echo '</script>';
}
mysql_close($link);
On other pages I have code that checks for the session and redirects users if they aren't logged in. Here's that code:
<?php
session_start();
if(!isset($_SESSION['Register'])){
if(!isset($_SESSION['Login'])){
header("location:../notLoggedIn.php");
}
}
$get_id = $_SESSION['Register'];
$get_id = $_SESSION['Login'];
?>
Then, when I check what's in the id variable passed from the login page with this:
$profile = mysql_query("SELECT * FROM profiles WHERE id= $id");
var_export($id);
I get a null value. What's going wrong?
You must check if session is not started then use session_start();
if (session_status() == PHP_SESSION_NONE) {//php >5.4
session_start();
}
and use $_SESSION['Login'] instead of $id
$profile = mysql_query("SELECT * FROM profiles WHERE id=".$_SESSION['Login']);
Multiple mistakes i have seen.
1)First revise your query :
$find= mysqli_query("SELECT * FROM users WHERE email='$ema' and password='$pw');
2) Secondly start session on the top of file.
3) mysqli_close($link); instead of mysql_close($link);
4) In the Last check if the session is properly set.
if(isset($_SESSION['Login'])) {
$get_id = $_SESSION['Login'];
$profile = mysql_query("SELECT * FROM profiles WHERE id= $id");
var_export($id);
}
Hi Please note these points
1) Start session_start on the top of page (before any echo or white space).
2) I don't see your $_SESSION['Register']. Have you set it
3) You are passing session variable not simple variable so use this
$profile = mysql_query("SELECT * FROM profiles WHERE id = $_SESSION['Login']");
var_export( $_SESSION['Login']);
As $id will be null here always

PHP Multiple Restricted Access

I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)

PHP - Managing Session - Doesnt Logout

I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link

This is my php for viewing user profile

My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>
than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli

Categories