超简单的短网址php实现

网上搜出来的都太复杂了,还是自己写算了。

环境:

php,apache2,linux

操作:

把下面的代码粘贴到index.php,放在一个只有1个字符(如u)作为文件夹名的二级目录里即可,为此目录增加写权限,图省事就

chmod 777 u  (根目录也行,为避免影响别的文件可能要改改代码)

结果:

把 http://blog.csdn.net/hursing 变成 http://127.0.0.1/u/1

原理:

  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;	// skip 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后的结果页面截图:



转载请注明出处:http://blog.csdn.net/hursing

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蒙面侠

来一个五羊香芋甜筒~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值