首先我们创建的文件有三个,API文件(生成短连接调用),index文件(访问短连接时跳转使用),config文件(连接数据库用的)
调用方法:域名/api.php?url=
Nginx规则
location / {
index index.php index.html;
if (!-e $request_filename){
rewrite ^/(\w+)$ /index.php?id=$1;
}
}
第一步创建config文件
<?php
define('db_host','localhost'); //数据库地址
define('db_user',''); //数据库用户
define('db_passwd',''); //数据库密码
define('db_name','img'); //数据库名称
//连接数据库
function mysqli(){
$mysqli = new Mysqli(db_host,db_user,db_passwd,db_name);
if($mysqli->connect_error){
die('connect error:'.$mysqli->connect_errno);
}
$mysqli->set_charset('UTF-8');
return $mysqli;
}
//获取域名
function realUrl(){
static $real_url = NULL;
if ($real_url !== NULL) {
return $real_url;
}
$real_url = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$real_url .= $_SERVER["SERVER_NAME"];
$real_url .= in_array($_SERVER['SERVER_PORT'], array(80, 443)) ? '/' : ':' . $_SERVER['SERVER_PORT'];
return $real_url;
}
第二步创建api文件
<?php
require_once 'config.php';
header("Access-Control-Allow-Origin:*");
header('Content-type: application/json');
!empty($_REQUEST['url']) ? $url = $_REQUEST['url'] : exit(json_encode(['code'=>201,"msg"=>"缺少参数"],JSON_UNESCAPED_UNICODE));
//过滤数据
if (trim(empty($url))){
echo json_encode(array('code'=>201,'msg'=>'未存入'),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}else{
$result = mysqli()->query("SELECT * FROM short_data WHERE long_url = '$url'");
$data = $result->fetch_all();
if ($data){
foreach ($result as $row) {
$key = $row['short_url'];
}
echo json_encode(array('code'=>202,'msg'=>'已存在','url'=>realUrl().$key),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}else{
//生成KEY
$key_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$key = substr(str_shuffle($key_str),mt_rand(0,strlen($key_str)-11),6);
$time = time();
//生成短链接
mysqli()->query("INSERT INTO short_data (long_url, short_url,time) VALUES ('$url', '$key', '$time')");
//返回结果
echo json_encode(array('code'=>200,'msg'=>'生成成功','url'=>realUrl().$key),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}
mysqli()->close();
}
第三步创建index文件
<?php
require_once 'config.php';
$short = $_REQUEST["id"];
//过滤数据
if (trim(empty($short))) {
echo json_encode(array('code'=>201,'msg'=>'链接不存在'),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}else{
$result = mysqli()->query("SELECT * FROM short_data WHERE short_url = '$short'");
$data = $result->fetch_all();
if ($data) {
foreach ($result as $row) {
$long_url = $row['long_url'];
}
header("Location: $long_url");
}else{
echo json_encode(array('code'=>201,'msg'=>'链接不存在'),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}
}
最后使用SQL创建数据字段
CREATE TABLE `img`.`short_data` ( `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'ID' , `short_url` VARCHAR(99) NOT NULL COMMENT '短连接' , `long_url` TEXT NOT NULL COMMENT '长链接' , `time` BIGINT(20) NOT NULL COMMENT '生成时间' , PRIMARY KEY (`id`)) ENGINE = InnoDB;