asdaqwr14241adadad214fvagsdg asdaqwr14241adadad214fvagsdg - 2 months ago 13
Javascript Question

How to encode and decode URL to $link = $_GET['url']; variable?

I want to encode urls to be transferred decoded to this variable:

$link = $_GET['url'];


Normally I use my php file like this: mysite.com/view.php?url=http://othersite.com/file/123


I want the link http://othersite.com/file/123 to be encoded using some encryption and then decoded into my php file view.php to be passed to
$link = $_GET['url'];
without errors.

How can I do this, step-by-step? Thanks.

Answer

simple way:

// view.php
$sources = [
    'secretString' => 'http://othersite.com/file/123',
    'secretString2' => 'http://othersite.com/file/1234',
    'secretString3' => 'http://othersite.com/file/12345'
    //etc..
];

if(isset($_GET['url']) && isset($sources[$_GET['url']])){
    $link = $sources[$_GET['url']];
}

if(isset($link)){
    // do something
}

url is: mysite.com/view.php?url=secretString

btw if you have list then it could be done as you want in the first place like this:

// view.php
$sources = [
    'http://othersite.com/file/123',
    'http://othersite.com/file/1234',
    'http://othersite.com/file/12345'
    //etc..
];

if(isset($_GET['url'])){
    foreach($sources as $source){
        if(sha1($source) == $_GET['url']){
            $link = $source;
            break;
        }
    }
}

if(isset($link)){
    // do something
}

//...

echo '<iframe src="mysite.com/view.php?url='.sha1('http://othersite.com/file/123').'"></iframe>';

external file examples:

txt file:

http://othersite.com/file/123
http://othersite.com/file/1234
http://othersite.com/file/12345

reading:

$sources = explode("\n", file_get_contents('path/to/file.txt'));

or by php:

// sources.php for example
return [
    'secretString' => 'http://othersite.com/file/123',
    'secretString2' => 'http://othersite.com/file/1234',
    'secretString3' => 'http://othersite.com/file/12345'
    //etc..
];

reading:

$sources = include('sources.php');

or just:

// sources.php for example
$sources = [
    'secretString' => 'http://othersite.com/file/123',
    'secretString2' => 'http://othersite.com/file/1234',
    'secretString3' => 'http://othersite.com/file/12345'
    //etc..
];

// in view.php
require_once('sources.php');
Comments