简体   繁体   中英

Match new session to old session in php and redirect to correct page

i got a situation when user email and password is in session on page editProfile.php with id. eg ../editProfile.php?id=17 and can update his own profile,

but if i change the url id value like ../editProfile.php?id=18 .. this can also update others information. why?

so, my question is how to redirect to other page if anyone change the id value or how to match session and then redirect.

Thanks

You need to check id in session with the one get from url like;

<?php
session_start();
$id = $_GET["id"];
// I assume you have user id in session also
if (!empty($_SESSION["user_id"] && $_SESSION["user_id"] == $id)) {
    // Do your updates here
} else {
    header("Location: other_page.php");
    exit;
}

Edit: If you have no user id in session, you can set in while making user logged in or you can get it on the flyw like;

$user_id = get_user_id($_SESSION["username"], $_SESSION["password"]); // You can write a function to get user id
$_SESSION["user_id"] = $user_id;

if (!empty($_SESSION["id"] && $_SESSION["id"] == $id)) {
    // Do your updates here
} else {
    header("Locatio: index.php");
    exit;
}

First of all when you are successfully logging in , you need to set this session variable like this on your login page..

$_SESSION['user_id']=$user_id; // Say , if it is 17 in this case..

So coming to your above scenario.. You could change your editprofile.php to look like this with the functionality

editprofile.php

<?php
session_start();

$userid = isset($_GET['id']) ? $_GET['id'] : "Not Set";

if($userid=="Not Set" || (int)$_SESSION['user_id']!=$userid)
{
  die("You don't have access !");
}

in your place i'd use check_session_id_from_db($ses_id) to check if the id exists in this session

<?php 
$ses_id = session_id(); 
$bsid_exists = false; 
$bsid_exists = check_session_id_from_db($ses_id); 
 if ($bsid_exists){ 
 //This is a reentry and the session already exists 
 // create a new session ID and start a new 
session_regenerate_id();         
$ses_id = session_id(); 
 } 
?>

check more about this method here: http://www.php.net/manual/fr/function.session-id.php

for more about sessions: http://www.php.net/manual/fr/book.session.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM