如何阻止更改URL并查看其他用户文件夹的功能

I have a directory of folders and I want to prevent the user named "x" whos files are availiable like this:reports/x/2015/04/ from changing the x to y and seeing all of those folers in y. I have the sessions working so that you need to be logged in to see any folders, but if you are logged in as x you can see the y folder by changing the URL. here is my index.php.

<?php

session_start();

if(!isset($_SESSION['username'])){
   header("Location:../../../../login/login.php");
}

require_once('../../../config.php');
require_once('../../../boilerplate.php');

global $smarty;

$smarty->display('general-report.tpl');

There's some things that are inherently bad about doing it this way, but for simplicity's sake, a quick fix is going to be checking to see if the username matches the folder name.

So, looking at your code, you could do something like this.

if ($username == $dir_name) { $smarty->display('general-report.tpl'); } else { $smarty->display('error.tpl'); }

Now, as for why you shouldn't be doing it this way...

The logged in username shouldn't really be visible in the URL.

You don't want people to start sharing their usernames around via URLs and then have mischievous people start brute forcing their way into your login system since they know various usernames.

If it were me, I'd have the report URLs all be the same and just have the logged in username determine which user's reports to show.

That way you know it's only visible to that person and even if they share the URL somewhere, their username won't be getting out into the wild.

You can store in $_SESSION a value that represents the user's home. If a user is outside his home directory, he will be redirected into his home. The value `$_SESSION['home'] can be a value stored in the database or it can be the username itself.

You can do something like this:

preg_match('/reports\/([a-zA-Z0-9]*)\//',$_SERVER['REQUEST_URI'],$matches);
if($_SESSION['home'] != $matches[0]){
    header('location: reports/' . $_SESSION['home']);
}

Feel free to adjust the regex.

thank you everyone I got it working with this:

<?php
/*===== Start sesstion and include config and boilerplate=====*/ 
session_start();
require_once('../../../config.php');
require_once('../../../boilerplate.php');

global $smarty;

/*=====Prevents seeing any pages unless logged in =====*/
if(!isset($_SESSION['username'])){
   header("Location:../../../../login/login.php");
 exit;
 }
/*=====Allows only logged in users to see their profiles in path_report=====*/
preg_match('/maintenance_new\/([a-zA-Z0-9]*)\//',$_SERVER['REQUEST_URI'],$matches);
$path_report = explode("/", $_SESSION['path_report']);
if($path_report[0] != $matches[1]){
header('Location: /maintenance_new/' . $_SESSION['path_report'] );
exit;
}
 /*=====Renders out page=====*/
 $smarty->display('general-report.tpl');