URL重寫-鏈接工廠

要根據數據庫中已有的數據,例如產品名稱或種類名稱,使用函數來生成新的URL地址,實現一致性
創建兩個PHP函數
1. _prepare_url_text接收一個字符串參數(比如產品或種類名稱,它將被用於包含到被重寫後的URL地址中),
並將它轉換爲能夠放入URL地址中的相應格式,比如:函數可以將“Super Drill”轉換爲"Super-Drill"
2. make_product_url接收產品和種類的名稱及ID作爲參數,並使用_prepare_url_text函數來生成
一個類似“/Products/Tools-C5/Super-Drill/P9.html”的URL地址


步驟:
1.創建include文件夾,並添加config.inc.php文件,內容如下

<?php
require_once 'config.inc.php';
function _prepare_url_text($string)
{
//刪除除了字母、數字、連接符、空格、下劃線之外的字符,用空格代替
$NOT_acceptable_characters_regex='#[^-a-zA-Z0-9]#';//#是php中加入正則表達式
$string=preg_replace($NOT_acceptable_characters_regex,'',$string);

$string=trim($string);//清除從參數中接收的字符串中的前後空格
$string=preg_replace('#[-_ ]#','-',$string);//將空格、破折號和下劃線轉換爲破折號

return $string;
}

function make_category_product_url($category_name,$category_id,$product_name,$product_id)
{
$clean_category_name=_prepare_url_text($category_name);
$clean_product_name=_prepare_url_text($product_name);

//連接字符串來生成鏈接字符串
$url=SITE_DOMAIN . '/Products/' .
$clean_category_name . '-C' . $category_id . '/' .
$clean_product_name . '-P' . $product_id . '.html';

return $url;
}

?>


2.創建catalog.php,內容:
<?php
require_once("url_factory.inc.php");
?>


<html>
<head>
<title>wskk8</title>
</head>
<body>
<h1>Products on Promotion at SEO Egghead Shop</h1>
<ul>
<li>
<a href="<?php echo make_category_product_url("Carpenter Tools", 12, "Belt Sander", 45); ?>">
lulu test1:Belt Sander
</a>
</li>

<li>
<a href="<?php echo make_category_product_url("Friends Shed", 2, "AJAX PHP Book", 42); ?>">
lulu test2:AJAX PHP Book
</a>
</li>

</ul>
</body>
</html>


3.創建product.php,內容:
<?php
echo $_GET['product_id'] . 'and ' . $_GET['category_id'];
?>


4.創建.htaccess文件,內容
RewriteEngine On
#RewriteRule ^mytest\.html$ /testphp/product.php?product_id=123
RewriteRule ^Products/C([0-9]+)/P([0-9]+)\.html$ /include/product.php?category_id=$1&product_id=$2 [L]


RewriteRule ^Products/.*-C([0-9]+)/.*-P([0-9]+)\.html$ /include/product.php?category_id=$1&product_id=$2 [L]


RewriteRule ^catalog.html$ /include/catalog.php [L]


5.config.inc.php,內容:
<?php
define ('SITE_DOMAIN','http://localhost/testphp');
?>


6.用http://localhost/include/catalog.html訪問
結果:


點擊鏈接後效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章