入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

超简单的短网址php实现

创建时间:2013-12-07 投稿人: 浏览次数:8142

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

环境:

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

阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。