如何将URL编解码为$link = $_GET['url'];多变的?

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

我想编码 urls 要传输解码到这个变量:
$link = $_GET['url'];

通常我这样使用我的 php 文件:mysite.com/view.php?url=http://othersite.com/file/123

我希望 link http://othersite.com/file/123 使用某种加密方式进行编码,然后解码到我的 php 文件 view.php 将无误地传递给 $link = $_GET['url'];

我该如何一步一步地做到这一点?谢谢。

简单的方法:

// 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 是:mysite.com/view.php?url=secretString

顺便说一句,如果你有列表,那么它可以像这样首先按照你的意愿完成:

// 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>';

外部文件示例:

txt 文件:

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

阅读:

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

或 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..
];

阅读:

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

或者只是:

// 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');