译者注:本文原名《site navigation with php》,原文详述了如何用php编程来做出效果理想的网页导航条,本文只选译了其中的部分文章,所选取的部分是文章精髓之所在,只要大家能弄懂这部分内容就可以用同样的原理、思想做出我
们需要的效果来,希望给读者能起到抛砖引玉的作用。本文只需要读者具备php、html的初步知识就可以基本读懂了。
译 文:如大家所知php对于用数据库驱动的网站(making database-driven sites)来讲可谓功能强大,可是我们是否可以用它来做点其他事情呢?php给了我们所有我们期望的工具:for与while的循环结构、数学运算等等,还可以通过两
种方式来引用文件:直接引用或向服务器提出申请。其实何止这些,让我们来看一个如何用它来做导航条的例子:
完整的原代码:
<!-- this "<?" is how you indicate the start of a block of php code, -->
<?php
# and this "#" makes this a php comment.
$full_path = getenv("request_uri");
$root = dirname($full_path);
$page_file = basename($full_path);
$page_num = substr($page_file
, strrpos($page_file, "_") + 1
, strpos($page_file, ".html") - (strrpos($page_file, "_") + 1)
);
$partial_path = substr($page_file, 0, strrpos($page_file, "_"));
$prev_page_file = $partial_path . "_" . (string)($page_num-1) . ".html";
$next_page_file = $partial_path . "_" . (string)($page_num+1) . ".html";
$prev_exists = file_exists($prev_page_file);
$next_exists = file_exists($next_page_file);
if ($prev_exists)
{
print "<a href="$root/$prev_page_file">previous</a>";
if ($next_exists)
{
print " ";
}
}
if ($next_exists)
{
print "<a href="$root/$next_page_file">next</a>";
}
?>//原程序完。
代码分析:
ok! 前面做了足够的铺垫工作,现在让我们来看看如何来用php来完成这项工作:
<!-- this "<?" is how you indicate the start of a block of php code, -->
<?php
# and this "#" makes this a php comment.
$full_path = getenv("request_uri");
$root = dirname($full_path);
$page_file = basename($full_path);
/*
php函数getenv()用来取得环境变量的值,request_uri的值是紧跟在主机名后的部分url,假如url
是http://www.yourmom.com/dinner/tuna_1.html, 那它的值就为/dinner/tuna_1.html. 现在我们将得到的那部分url放
在变量$full_path中,再用dirname()函数来从url中抓取文件目录,用basename()函数取得文件名,用上面的例子来
讲dirname()返回值:/dinner/;basename()返回:tuna_1.html。接下来的部分相对有些技巧,假如我们的文件名以
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器