Search code examples
phpurlvariablesencryptionencode

How can I encrypt a PHP variable (a link)?


I need help encoding a link. Basically, upon completion of an event, I run a function that redirects the user to a link. The link is taken directly from a PHP variable.

<?php 

$url = "http://google.com/";
$mylink = "<a href=\"" . $url . "\">";

echo $mylink;

?>

My question is, how can I echo $mylink, without having the $url shown in the source code. I want the output of my link to still go to $url, but not show the value of $url ANYWHERE in my source code.

How can I achieve this?


Solution

  • Here is one sure way to do this: you could store in your database (or files on the server) the link and an ID. Instead of the actual url, print a link to a php script you write which passes in that ID. This page you write simply looks up the associated ID and uses a header to redirect to the link.

    For Example: you write a script redirector.php then the links in the page source point to "redirector.php?id=10293". The redirector script looks up what is id 10293 and sees http://www.example.com then calls

    header('Location: http://www.example.com/');
    

    This way the links are only in the server side and never show up in your source code. As user pst suggested in the comments you could also use something like tinyurl which operates on this same principal.

    Any other methods will rely on some sort of encryption which could be decrypted because the actual data (link url) is in the page source albeit obscured.

    EDIT : here is an example of how you could write your two scripts -- the one which is printing the urls and the one which would redirect. Assuming a table urls exists in your MySQL db add a column called 'hash' or 'id' or something and in the script which will print the urls add the lines:

    $hash = sha1($url);
    mysql_query("UPDATE url_table SET hash = '$hash' WHERE url = '$url'");
    $printURL = "../redirect.php?id=$hash";
    print "<a href='$printURL'>click me to go somewhere you don't know yet</a>";
    

    now in another file named redirect.php put the following code:

    <?php
    //connect to db or include files
    $givenHash = $_REQUEST['id']; $realURL = $_SERVER['HTTP_REFERER'];
    $result = mysql_query("SELECT url FROM url_table WHERE hash = '$givenHash'"); 
    while($row=mysql_fetch_assoc($result)) {
       $realURL = $row['url'];
    }
    header("Location: $realURL");
    ?>
    

    This will either send them to the url you want if it is found in the db or drop them back to the page they were on before they clicked the link. If you only have a few links that are known in advance then you can do this trick without the use of databases by just using a look up array. Hope this helps.