【问题标题】:Convert Query String URL to Static Path将查询字符串 URL 转换为静态路径
【发布时间】:2015-11-12 23:30:01
【问题描述】:

我目前正在压缩图像时生成查询字符串 URL。

例如example.com/img.php?compressed=image.jpg&w=280

但我需要生成静态 URL 路径。

例如example.com/img/image.jpg/width_280

我正在使用以下代码来构造查询字符串 URL:

require_once 'img.class.php'; 

$getImage = new GetImage();
$getImage->setCacheFolder(FOLDER_CACHE);
$getImage->setErrorImagePath(FILEPATH_IMAGE_NOT_FOUND);
$getImage->setJpegQuality(JPEG_QUALITY);

$img = $_GET["img"];

$width = -1;
$width = isset($_GET["w"])?$_GET["w"]:-1;
$height = isset($_GET["h"])?$_GET["h"]:-1;

$type = "";
if(isset($_GET["exact"])) $type = GetImage::TYPE_EXACT;
else if(isset($_GET["exacttop"])) $type = GetImage::TYPE_EXACT_TOP;

$getImage->showImage($img,$width,$height,$type);

是否可以通过任何方式更改此代码以生成静态 URL?

它必须是硬编码的,而不是 mod_rewrite 解决方案。

非常感谢!

B.

【问题讨论】:

  • 静态网址是什么意思?
  • 对不起,我的意思是没有 QS 的 URL 路径。例如example.com/img/image.jpg/width_280
  • 我不相信如果不使用 mod_rewrite 这将是可能的
  • 你可以试试 example.com/img.php/width_20/image.jpg - 查看 $_SERVER 获取有问题的 url

标签: php url query-string


【解决方案1】:

如果你不能使用 mod_rewrite(如果服务器配置允许,可以在 .htaccess 中)或类似“ErrorDocument 404 /img.php”的东西,你可以使用路径重载(我不知道这是否有名字):

PHP:

$subpath = substr($_SERVER['PHP_SELF'], strlen($_SERVER['SCRIPT_NAME']) + 1);

$parts  = explode('/', $subpath);
$opts = array(
    'width'  => -1,
    'height' => -1,
);
while ($parts) {
    if (preg_match('/^(width|height)_(\d+)$/', $parts[0], $matches)) {
        $opts[$matches[1]] = $matches[2];
    // more options with "} elseif () {"
    } else {
        break;
    }
    array_shift($parts);
}
$image = implode('/', $parts);
if (!$image) {
    die("No image given\n");
}

// test output
header('Content-Type: text/plain; charset=utf-8');
var_dump($opts);
var_dump($image);

示例:

http://localhost/img.php/width_200/test/image.jpg
// Output
array(2) {
  ["width"]=>
  string(3) "200"
  ["height"]=>
  int(-1)
}
string(14) "test/image.jpg"

我已将图像路径放在末尾,以便在末尾添加真正的扩展名。对于客户端来说,脚本名 img.php 只是另一个目录级别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2016-03-31
    • 2021-06-13
    • 2016-11-17
    相关资源
    最近更新 更多