Shortest possible encoded string with decode possibility (shorten url) using only PHP

前端 未结 13 1732
甜味超标
甜味超标 2020-12-28 19:14

I\'m looking for a method that encodes an string to shortest possible length and lets it be decodable (pure PHP, no SQL). I have working sc

13条回答
  •  一整个雨季
    2020-12-28 20:05

    I'm afraid, you won't be able to shorten the query string better than any known compression algorithm. As already mentioned, a compressed version will be shorter by a few (around 4-6) characters than the original. Moreover, the original string can be decoded relatively easy (opposed to decoding sha1 or md5, for instance).

    I suggest shortening URLs by means of Web server configuration. You might shorten it further by replacing image path with an ID (store ID-filename pairs in a database).

    For example, the following Nginx configuration accepts URLs like /t/123456/700/500/4fc286f1a6a9ac4862bdd39a94a80858, where

    • the first number (123456) is supposed to be an image ID from database;
    • 700 and 500 are image dimentions;
    • the last part is an MD5 hash protecting from requests with different dimentions.
    # Adjust maximum image size
    # image_filter_buffer 5M;
    
    server {
      listen          127.0.0.13:80;
      server_name     img-thumb.local;
    
      access_log /var/www/img-thumb/logs/access.log;
      error_log /var/www/img-thumb/logs/error.log info;
    
      set $root "/var/www/img-thumb/public";
    
      # /t/image_id/width/height/md5
      location ~* "(*UTF8)^/t/(\d+)/(\d+)/(\d+)/([a-zA-Z0-9]{32})$" {
        include        fastcgi_params;
        fastcgi_pass   unix:/tmp/php-fpm-img-thumb.sock;
        fastcgi_param  QUERY_STRING image_id=$1&w=$2&h=$3&hash=$4;
        fastcgi_param  SCRIPT_FILENAME /var/www/img-thumb/public/t/resize.php;
    
        image_filter resize $2 $3;
        error_page 415 = /empty;
    
        break;
      }
    
      location = /empty {
        empty_gif;
      }
    
      location / { return 404; }
    }
    

    The server accepts only URLs of specified pattern, forwards request to /public/t/resize.php script with modified query string, then resizes the image generated by PHP with image_filter module. In case of error, returns an empty GIF image.

    The image_filter is optional, it is included only as an example. Resizing can be performed fully on PHP side. With Nginx, it is possible to get rid of PHP part, by the way.

    The PHP script is supposed to validate the hash as follows:

    // Store this in some configuration file.
    $salt = '^sYsdfc_sd&9wa.';
    
    $w = $_GET['w'];
    $h = $_GET['h'];
    
    $true_hash = md5($w . $h . $salt . $image_id);
    if ($true_hash != $_GET['hash']) {
      die('invalid hash');
    }
    
    $filename = fetch_image_from_database((int)$_GET['image_id']);
    $img = imagecreatefrompng($filename);
    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
    

提交回复
热议问题