Analyze the principles and usage examples of generating short URLs/short links in PHP

coldplay.xixi
Release: 2023-04-09 13:40:02
forward
2764 people have browsed it

Analyze the principles and usage examples of generating short URLs/short links in PHP

本文实例讲述了php生成短网址/短链接原理和用法。分享给大家供大家参考,具体如下:

需求

在我们的项目当中,如果需要更好传播我们的活动链接,但是链接太长1来是不美观,2来是太过于“笨重”,例如拼多多,淘宝联盟,他们的推广链接都是有短链接的,还有新浪微博。

但是,这些始终都是别人的,我们调用别人的API进行生成,不稳定,所以可以自己做一个,注册一个稍微短一些的域名就行。

相关学习推荐:php编程(视频)

生成源码api.php

Copy after login

访问源码index.php

正在跳转"; //过滤数据 if (trim(empty($key))) { echo "链接不存在"; }else{ //解析KEY //定义数据库配置 $dbhost = "xxx";//数据库服务器地址 $dbuser = "xxx";//数据库账号 $dbpwd = "xxx";//数据库密码 $dbname = "xxx";//数据库名 //连接数据库 $con = mysql_connect($dbhost,$dbuser,$dbpwd); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db($dbname, $con); //查询数据库,通过KEY获取长链接进行跳转 //检查数据库是否存在该KEY $check = mysql_query("SELECT * FROM 表名 WHERE dwz_key = '$key'"); $check_result = mysql_num_rows($check); //如果存在,则解析出长链接并跳转 if ($check_result) { while ($row_long_url = mysql_fetch_array($check)) { $long_url = $row_long_url["long_url"]; // echo ""; header("Location: $long_url"); } }else{ echo "链接不存在"; } } ?>
Copy after login

Apache规则.htaccess

RewriteEngine On #RewriteBase / RewriteRule ^(\w+)$ index.php?id=$1
Copy after login

数据库字段

id(int)自增 dwz_key(varchar) long_url(text) creat_time(TIMESTAMP)
Copy after login

使用方法

1、访问api.php?url=长链接,即可生成短链接,例如返回JSON

{"code":"0","url":"http://xxx.cn/Hp8R"}
Copy after login

2、新建.htaccess,把上面规则复制进去,保存
3、新建index.php,把上面代码拷贝进去,配置好数据库。访问http://xxx.cn/Hp8R,就会自动跳转到你的长链接

相关学习推荐:编程视频

The above is the detailed content of Analyze the principles and usage examples of generating short URLs/short links in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!