以下是一个用PHP编写的短网址缩短程序的示例:

<?php
function generateShortURL($long_url) {
    // 生成一个唯一的短码
    $short_code = substr(md5($long_url . time()), 0, 6);
    
    // 存储长网址和短码的对应关系到数据库或文件中
    // 这里使用一个简单的文件存储示例
    $data = file_get_contents('urls.json');
    $urls = json_decode($data, true);
    $urls[$short_code] = $long_url;
    file_put_contents('urls.json', json_encode($urls));
    
    // 返回短网址
    $short_url = 'http://example.com/' . $short_code;
    return $short_url;
}

function getLongURL($short_code) {
    // 从数据库或文件中获取短码对应的长网址
    // 这里使用一个简单的文件存储示例
    $data = file_get_contents('urls.json');
    $urls = json_decode($data, true);
    if (isset($urls[$short_code])) {
        return $urls[$short_code];
    } else {
        return false;
    }
}

// 获取长网址并生成短网址
$long_url = 'http://www.example.com/very-long-url';
$short_url = generateShortURL($long_url);
echo 'Short URL: ' . $short_url . "\n";

// 获取短网址对应的长网址
$short_code = 'abc123';
$long_url = getLongURL($short_code);
if ($long_url) {
    echo 'Long URL: ' . $long_url . "\n";
} else {
    echo 'Invalid short code!';
}
?>

上述代码使用了一个简单的文件存储来保存长网址和短码的对应关系。你可以根据自己的需求,将数据存储到数据库中或使用其他方法来保存数据。

PHP 短网址缩短程序:简单易用代码示例

原文地址: http://www.cveoy.top/t/topic/bTRx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录