Reputation: 609
I was wondering if what I'm using is safe:
Header(“Location:”);
I want to use it like this: $user would be the user's session and 1 would mean admin. (Just an example.)
if($user != 1){
header("location: index.php"); }
So would this stop users from using that page, including downloading files, looking at the source of that page? Because my adminpanel is going to have downloads and also inserts for the homepage..
If it's not safe to use, or the way I'm using it. What should I use instead?
Thanks.
Upvotes: 1
Views: 1363
Reputation: 5671
So what happens here is that by setting the Location
tag, you are in fact giving back a HTTP 30x request, pointing the users browser to the new page. But it's in the hands of the browser to respect it. If the browser/user is malicious, he might just ignore it.
So you need to stop your output right after sending the Location header with die()
. Than it's safe - the browser doesn't get any data it shouldn't get
Upvotes: 1
Reputation: 39389
header()
is safe to use, but it means you have to include that call in every page you don’t want a non-admin to view.
A better way would be to have an authenticated user class that handles this. The benefit is, it DRYs your code.
<?php
class User
{
public function __construct()
{
// create your user however, i.e. fetch a record from your database
}
public function isAdmin()
{
return ($this->user->role == 'admin');
}
public function redirect()
{
header('Location: index.php');
exit;
}
}
And then use it in your code:
<?php
$user = new User();
if (!$user->isAdmin()) {
$user->redirect();
}
// continue with your page as normal; user here is an admin
Upvotes: 2
Reputation: 89
I feel like a better way would be to exit the page and prevent any other code execution. I'm not sure but a user might be able to ignore header redirect requests if they wanted to.
I've always just added a little snippet like "Sorry, this is only available to Administrators" and then just return; or exit;
edit: great googly moogly you guys are quick to the draw.
Upvotes: 1
Reputation: 324620
Don't forget to die()
after setting a Location header. That's what really stops people from using pages they're not supposed to.
Upvotes: 2