Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php短网址超简单代码

php短网址超简单代码

发布时间:2017-10-19   编辑:www.jquerycn.cn
分享一个php短网址的实现代码,超简单的php短网址生成代码,有需要的朋友参考下。

系统环境:
php,apache2,linux

生成php短网址的操作:
把代码复制到index.php放在一个只有1个字符(如u)作为文件夹名的二级目录中。
为此目录增加写权限,图省事就chmod 777 u  (根目录也行,为避免影响别的文件可能要改改代码)

知网址生成结果:
把http://blog.csdn.net/hursing变成http://127.0.0.1/u/1

php生成短网址的原理:
1,通过form post获取要变短的url
2,把url放在一个javascript内写入文件,文件名按数字增长。javascript的作用就是跳转到指定的url

可优化:
如果可以设置二级域名,那就把二级域名指向那个目录就好了,就不用多输入一个 u/。

代码:
 

复制代码 代码示例:
<html> 
    <head> 
        <meta charset="utf-8" /> 
        <title>Shorten URL</title> 
    </head> 
    <body> 
        URL to be shortened: (must include protocol like http:// or https:// etc.)<br /> 
        <form method="post"> 
            <textarea rows='3' name="url" style="width:100%"></textarea><br /> 
            <input type="submit" value="submit" /> 
        <form><br /> 
        <?php 
            if (isset($_POST['url'])) { 
                $origin = $_POST['url']; 
                if (strlen($origin) > 10) { 
                    $filename = count(scandir('.')) - 3;    // strip php self . .. 
                    file_put_contents($filename,  
                        '<script type="text/javascript">location.href="'.$origin.'"</script>'); 
                    $shortened = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.$filename; 
                    echo 'Original URL is<br /><a href="'.$origin.'">'.$origin.'</a><br />' 
                        .'Shortened URL is<br /><a href="'.$shortened.'">'.$shortened.'</a>'; 
                } else { 
                    echo "The URL you entered is NOT valid."; 
                } 
            } 
        ?> 
    </body> 
</html> 

生成以数字为文件名的文件:
 

复制代码 代码示例:
<script type="text/javascript">location.href="http://blog.csdn.net/hursing"</script>

提交url后,生成的短网址截图如下:
php短网址生成代码

您可能感兴趣的文章:
php生成短网址示例代码
php生成短网址的简单代码
php短网址超简单代码
php 短网址的实现代码
c#.net 实现短网址的简单方法
PHP如何实现短网址
PHP实现百度、网易、新浪短网址服务的API接口调用
用PHP实现URL转换短网址的算法示例
php生成短网址的思路与实现
php微博短网址算法 php生成短网址的实现代码

关键词: php短网址  短网址   
[关闭]