diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1e4c958 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +data.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..510cc5c --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +## 短链接生成 + +又一个基于 PHP 简单实现的短链接在线生成工具,简单配置,快速搭建。 + +## 快速配置 + +### 安装 +#### 1. 下载源码,部署至服务器,环境 `PHP > 5.6`,需安装 `PDO` 扩展。 +#### 2. 配置 Nginx,参考如下: +```conf +server { + listen 80; + server_name url.local; + root /www/url; + index index.php index.html index.htm; + + access_log /dev/null; + error_log /var/log/nginx/nginx.url.error.log warn; + + # 伪静态 必须 + location / { + try_files $uri $uri/ /index.php?$query_string; + } + + # sqlite 数据库文件禁止访问 必须 + location ~ /(data\.db) { + deny all; + } + + location ~ \.php$ { + fastcgi_pass unix:/dev/shm/php-cgi.sock; + include fastcgi-php.conf; + include fastcgi_params; + } +} +``` +#### 3. 配置数据库,支持 MySQL 和 SQLite。 + +##### 3.1 MySQL 配置 + +###### 3.1.1 编辑 index.php + +``` +prepare("select * from url where hash = ?"); + $stmt->execute([$hash]); + $data = $stmt->fetchAll(); + + if ($data) { + $code = current($data)['code']; + } else { + $code = generate_code(); + + $stmt = $db->prepare("select * from url where code = ?"); + $stmt->execute([$code]); + $exist = $stmt->fetchColumn(); + if ($exist) { + json(-4, '天选之子,再来一次!'); + } + + $stmt = $db->prepare("insert into url(code, hash, url) values (?, ?, ?)"); + $result = $stmt->execute([$code, $hash, $url]); + if (!$result) { + json(-5, '系统繁忙,请稍后再试!'); + } + } + + $base_url = $_SERVER['HTTP_HOST'] .'/'. $code; + json(0, 'OK',[ + 'short' => $base_url, + 'generic' => 'http://' . $base_url, + 'long' => 'https://' . $base_url, + ]); +} else if ($_SERVER['REQUEST_METHOD'] == 'GET') { + header("Content-Type: text/html"); + if ($_SERVER['REQUEST_URI'] != '/') { + $code = substr($_SERVER['REQUEST_URI'], 1); + $db = db(); + $stmt = $db->prepare("select * from url where code = ?"); + $stmt->execute([$code]); + $data = $stmt->fetchAll(); + if ($data) { + $url = current($data)['url']; + header("Location: {$url}"); + } else { + header("Location: /"); + } + exit(0); + } +} + +function json($code, $msg, $data=[]) { + header("Content-Type: application/json; charset=utf-8"); + echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data]); + exit(0); +} + +function db() { + try { + $pdo = new PDO(DB_DSN, DB_USER, DB_PASSWD); + } catch (PDOException $e) { + json(-1, '数据库连接失败!'.$e->getMessage()); + } + + return $pdo; +} + +function generate_code() { + $seeds = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9)); + $depository = []; + for ($i = 0; $i < CODE_LENGTH-1; $i++) { + $depository = array_merge($depository, $seeds); + } + shuffle($depository); + return join('', array_slice($depository, 0, CODE_LENGTH)); +} + +header("Content-Type: text/html"); + +?> + + + +
+ + + +