Home  >  Article  >  php教程  >  php短网址超简单代码

php短网址超简单代码

WBOY
WBOYOriginal
2016-06-07 11:34:38808browse

php短网址超简单代码
系统环境:
php,apache2,linux

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

网址生成结果:
把http://www.heimaolianmeng.com/heimaoseojishu/变成http://127.0.0.1/u/1
php短网址超简单代码

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

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

代码:


代码示例:



Shorten URL


URL to be shortened: (must include protocol like http:// or https:// etc.)







if (isset($_POST['url'])) {
$origin = $_POST['url'];
if (strlen($origin) > 10) {
$filename = count(scandir('.')) - 3; // strip php self . ..
file_put_contents($filename,
'');
$shortened = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.$filename;
echo 'Original URL is
'.$origin.'
'
.'Shortened URL is
'.$shortened.'';
} else {
echo "The URL you entered is NOT valid.";
}
}
?>


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


代码示例:

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
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