Skip to content
Advertisement

How to secure the id that are passed in a URL?

have a typical website that passed id values in the URL. ex. account.php?id=755

in the account.php page I do check the value

$id = 0;
if(isset($_GET['id'])){
    $id = intval($_GET['id']);
}
if($id == 0){
    echo 'this account does not exists!';
    exit();
}

But, I am trying to find away to encrypt the value 755 prior displaying it and then decode it prior checking the value. So I am not displaying the the actual id but a mask.

My question is this: 1) Is this a good idea to encrypt and decrypt ids? so a mask will be passed and not the actual id. 2) is there an easy way of encrypting the ids by returning a string with a mix of number and alphabets only, using PHP?

Advertisement

Answer

But, I am trying to find away to encrypt the value 755 prior displaying it and then decode it prior checking the value. So I am not displaying the the actual id but a mask.

It seems like a very cumbersome idea. But if it means something to you and security, then you need to devise an encoding/decoding scheme that works for you. On the most simple level you can perhaps base64_encode the id and then decode it with base64_decode. The examples below are just illustrative. Please clean and adjust for your needs.

$encrypted_id = base64_encode($id);

Now to get it back, just run base64_decode:

$decrypted_id = base64_decode($encrypted_id);

But that is simple to hack.

A better way might be too create some secret “salt” to add to the ID that only your system knows or understands.

$salt="MY_SECRET_STUFF";
$encrypted_id = base64_encode($id . $salt);

In that way, simply using base64_decode is meaningless if the $id decoding does not factor in the salt:

$decrypted_id = base64_decode($encrypted_id);

It would only be usefully decoded with your salt factored into the decryption process:

$decrypted_id_raw = base64_decode($encrypted_id);
$decrypted_id = preg_replace(sprintf('/%s/', $salt), '', $decrypted_id_raw);

The logic is the raw decrypted ID still has the salt mixed in and the preg_replace would strip this out. Since only you know the ‘salt’ guess what? You are secure! But of course if you loose the salt for some reason, your whole system is useless because who knows what about your ids.

But again, this seems excessive unless protecting user IDs is the goal of your app and truly critical to security. If someone guesses an ID what is the worst that can happen? And how can you program against that ‘worst’ scenario.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement