Home Backend Development PHP Tutorial How to generate short link in php

How to generate short link in php

Jul 04, 2018 pm 04:40 PM

 这篇文章主要介绍了关于php生成短连接的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

自己没事研究研究  PHP生成短连接 好多人都花钱买新浪的接口来生成短连接,我自己就写了一个 当然核心代码还是借助网络,我只是负责整合了一下而已。

我是在我本地测试的,接下来详细说下。

我做的是把域名信息都存在数据库里面,数据库表是这样的

 1.创建个数据库表

CREATE TABLE `links` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(255) DEFAULT NULL,
  `ctime` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=111 DEFAULT CHARSET=UTF8;
Copy after login

2.配置本地域名

我用的是phpstudy,你用wamp,或者 xampp都一样,根据我的phpstudy来就行

我phpstudy一个右键就可以设置了,如下图(右键-站点域名管理)

箭头几个位置是要注意的,自己设置域名 然后选择你写的代码的位置,端口你看着定,写完了 点新增,右侧就出现你设置的了。

肯定有一些用xammp或者用 wamp的朋友这个时候懵逼了,怎么办 ,我想办法装一个xampp,给你们截代码吧,

<VirtualHost *:80>
    DocumentRoot "E:/project/short"
    ServerName d.cn    <Directory "E:/project/short">
        DirectoryIndex index.html index.php 
        AllowOverride All
        Order deny,allow
        Allow from all    </Directory>
</VirtualHost>
 
 
<VirtualHost *:80>
    DocumentRoot "E:/project/short"
    ServerName localhost    <Directory "E:/project/short">
        DirectoryIndex index.html index.PHP 
        AllowOverride All
        Order deny,allow
        Allow from all    </Directory>
</VirtualHost>
Copy after login

这代代码 写在哪个文件呢,写在xampp/apache/conf/extra/httpd-vhosts.conf 你的xampp装哪个盘就去哪个盘找了,还有 DocumentRoot也要写你的对应的位置哦

3.改域名配置文件

位置在
C:\Windows\System32\drivers\etc\hosts

我写的是这样的

4.配置伪静态文件

在项目的根目录下创建一个.htaccess文件,里面代码是

<IfModule mod_rewrite.c>RewriteEngine on
RewriteRule ^(\S{1,7})$ index.php?code=$1 [L]</IfModule>
Copy after login

5.写系统公共函数

func.php

<?php
function b64dec($b64) { //64进制转换成10进制
    $map = array(        &#39;0&#39;=>0,&#39;1&#39;=>1,&#39;2&#39;=>2,&#39;3&#39;=>3,&#39;4&#39;=>4,&#39;5&#39;=>5,&#39;6&#39;=>6,&#39;7&#39;=>7,&#39;8&#39;=>8,&#39;9&#39;=>9,
        &#39;A&#39;=>10,&#39;B&#39;=>11,&#39;C&#39;=>12,&#39;D&#39;=>13,&#39;E&#39;=>14,&#39;F&#39;=>15,&#39;G&#39;=>16,&#39;H&#39;=>17,&#39;I&#39;=>18,&#39;J&#39;=>19,
        &#39;K&#39;=>20,&#39;L&#39;=>21,&#39;M&#39;=>22,&#39;N&#39;=>23,&#39;O&#39;=>24,&#39;P&#39;=>25,&#39;Q&#39;=>26,&#39;R&#39;=>27,&#39;S&#39;=>28,&#39;T&#39;=>29,
        &#39;U&#39;=>30,&#39;V&#39;=>31,&#39;W&#39;=>32,&#39;X&#39;=>33,&#39;Y&#39;=>34,&#39;Z&#39;=>35,&#39;a&#39;=>36,&#39;b&#39;=>37,&#39;c&#39;=>38,&#39;d&#39;=>39,
        &#39;e&#39;=>40,&#39;f&#39;=>41,&#39;g&#39;=>42,&#39;h&#39;=>43,&#39;i&#39;=>44,&#39;j&#39;=>45,&#39;k&#39;=>46,&#39;l&#39;=>47,&#39;m&#39;=>48,&#39;n&#39;=>49,
        &#39;o&#39;=>50,&#39;p&#39;=>51,&#39;q&#39;=>52,&#39;r&#39;=>53,&#39;s&#39;=>54,&#39;t&#39;=>55,&#39;u&#39;=>56,&#39;v&#39;=>57,&#39;w&#39;=>58,&#39;x&#39;=>59,
        &#39;y&#39;=>60,&#39;z&#39;=>61,&#39;_&#39;=>62,&#39;=&#39;=>63
    );    $dec = 0;    $len = strlen($b64);    for ($i = 0; $i < $len; $i++) {        $b = $map[$b64{$i}];        if ($b === NULL) {            return FALSE;
        }        $j = $len - $i - 1;        $dec += ($j == 0 ? $b : (2 << (6 * $j - 1)) * $b);
    }    return $dec;
}function decb64($dec) { //10进制转换成64进制
    if ($dec < 0) {        return FALSE;
    }    $map = array(        0=>&#39;0&#39;,1=>&#39;1&#39;,2=>&#39;2&#39;,3=>&#39;3&#39;,4=>&#39;4&#39;,5=>&#39;5&#39;,6=>&#39;6&#39;,7=>&#39;7&#39;,8=>&#39;8&#39;,9=>&#39;9&#39;,
        10=>&#39;A&#39;,11=>&#39;B&#39;,12=>&#39;C&#39;,13=>&#39;D&#39;,14=>&#39;E&#39;,15=>&#39;F&#39;,16=>&#39;G&#39;,17=>&#39;H&#39;,18=>&#39;I&#39;,19=>&#39;J&#39;,
        20=>&#39;K&#39;,21=>&#39;L&#39;,22=>&#39;M&#39;,23=>&#39;N&#39;,24=>&#39;O&#39;,25=>&#39;P&#39;,26=>&#39;Q&#39;,27=>&#39;R&#39;,28=>&#39;S&#39;,29=>&#39;T&#39;,
        30=>&#39;U&#39;,31=>&#39;V&#39;,32=>&#39;W&#39;,33=>&#39;X&#39;,34=>&#39;Y&#39;,35=>&#39;Z&#39;,36=>&#39;a&#39;,37=>&#39;b&#39;,38=>&#39;c&#39;,39=>&#39;d&#39;,
        40=>&#39;e&#39;,41=>&#39;f&#39;,42=>&#39;g&#39;,43=>&#39;h&#39;,44=>&#39;i&#39;,45=>&#39;j&#39;,46=>&#39;k&#39;,47=>&#39;l&#39;,48=>&#39;m&#39;,49=>&#39;n&#39;,
        50=>&#39;o&#39;,51=>&#39;p&#39;,52=>&#39;q&#39;,53=>&#39;r&#39;,54=>&#39;s&#39;,55=>&#39;t&#39;,56=>&#39;u&#39;,57=>&#39;v&#39;,58=>&#39;w&#39;,59=>&#39;x&#39;,
        60=>&#39;y&#39;,61=>&#39;z&#39;,62=>&#39;_&#39;,63=>&#39;=&#39;,
    );    $b64 = &#39;&#39;;    do {        $b64 = $map[($dec % 64)] . $b64;        $dec /= 64;
    } while ($dec >= 1);    return $b64;
    
}
Copy after login

6.写核心方法

创建index.php

<?php
include &#39;func.php&#39;;define("HOST","localhost");define("DB_NAME","test");
define("USER","root");define("PASS","root"); 
function make_short_url($url){    $url=str_ireplace("http://","",$url);    
$pdo = new PDO("mysql:host=".HOST.";dbname=".DB_NAME,USER,PASS); 
    $rs = $pdo ->query("select id from links where url=&#39;".$url."&#39;");    
    $row = $rs -> fetch(); 
    if($row==false){        
    $pdo -> exec("insert into links(url,ctime) values(&#39;".$url."&#39;,&#39;".mktime()."&#39;)"); 
        $id=$pdo -> lastinsertid(); 
        return "http://d.cn/".decb64($id);
    }else{        return "http://d.cn/".decb64($row[&#39;id&#39;]);
    }
} 
function get_long_url($code){    
$pdo = new PDO("mysql:host=".HOST.";dbname=".DB_NAME,USER,PASS); 
    $rs = $pdo ->query("select url from links where id=&#39;".b64dec($code)."&#39;");    
    $row = $rs -> fetch(); 
    if($row==false){        print "链接错误";        exit;
    }else{        return "http://".$row[&#39;url&#39;];
    }
}//参数的接收与短链接返回部分if($_GET[&#39;code&#39;]){    
$code=trim($_GET[&#39;code&#39;],"/");    $url=get_long_url($code);    
if($url){        header("location:$url");
    }
}elseif($_GET[&#39;url&#39;]){    
$url=trim($_GET[&#39;url&#39;]);    
print make_short_url($url);
}
Copy after login

最后浏览器测试下

把生成的地址 粘贴到浏览器地址栏一访问就跳转到 www.cctv.com了

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

PHP根据秒PHP持续时长的方法

php生成xml数据的方法

The above is the detailed content of How to generate short link in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1247
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles