Web應用程式完整的URL管理包括兩個方面。首先, 當使用者請求約定的URL,應用程式需要解析 它變成可以理解的參數。第二,應用程式需求提供一種創造URL的方法,以便創建的URL應用程式可以理解的。對於Yii應用程序,這些透過CUrlManager輔助完成。
1. Creating URLs(創建網址)
雖然URL可被硬編碼在控制器的視圖(view)文件,但往往可以很靈活地動態創建它們:
$url=$this->createUrl($route,$params);
/index.php?r=post/read&id=100
/index.php/post/read/id/100
array( ...... 'components'=>array( ...... 'urlManager'=>array( 'urlFormat'=>'path', ), ), );
array( ...... 'components'=>array( ...... 'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( 'pattern1'=>'route1', 'pattern2'=>'route2', 'pattern3'=>'route3', ), ), ), );
'pattern1'=>array('route1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)
<parampattern>;</parampattern>
array( 'posts'=>'post/list', 'post/<id:>'=>'post/read', 'post/<year:>/<title>'=>'post/read', )</title></year:></id:>
指的是控制器實例; $route指定請求的route 的要求;$params列出了附加在網址中的
參數。
預設情況下,URL以get格式使用createUrl建立。例如,提供$route='post/read'和$params=array('id'=>100) ,我們將取得下列網址:
array( '<_c:>/<id:>/<_a:>' => '<_c>/<_a>', '<_c:>/<id:>' => '<_c>/read', '<_c:>s' => '<_c>/list', )</_c></_c:></_c></id:></_c:></_a></_c></_a:></id:></_c:>
參數以一系列Name=Value透過符號串連起來出現在請求字串,r參數指的是請求的route 。這種URL格式使用者友善性不是很好,因為它需要一些非字元。
- 我們可以使上述網址看起來更簡潔,更不言自明,通過採用所謂的'path格式,省去查詢字符串和把GET參數加到路徑信息,作為網址的一部分:
-
array( 'http://<user:>.example.com/<lang:>/profile' => 'user/profile', )</lang:></user:>
要更改URL格式,我們應該配置urlManager應用程式元件,以便createUrl可以自動切換到新格式和應用程式可以正確理解新的網址:
Options +FollowSymLinks IndexIgnore */* RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php
createurl方法所產生的是一個相對位址。為了得到一個絕對的url ,我們可以用前綴yii">
提示:此網址透過createurl方法所產生的是一個相對位址。為了得到一個絕對的url ,我們可以用前綴yii:array( // 一个标准的URL规则,将 '/' 对应到 'site/index' '' => 'site/index', // 一个标准的URL规则,将 '/login' 对应到 'site/login', 等等 '<action:>' => 'site/<action>', // 一个自定义URL规则,用来处理 '/Manufacturer/Model' array( 'class' => 'application.components.CarUrlRule', 'connectionID' => 'db', ), // 一个标准的URL规则,用来处理 'post/update' 等 '<controller:>/<action:>' => '<controller>/<action>', ),</action></controller></action:></controller:></action></action:>
這些規則以一系列的路線格式對數組指定,每對對應於一個單一的規則。式,沒有分隔符號和修飾語。參數,以一種特殊令牌格式表現如下:
class CarUrlRule extends CBaseUrlRule { public $connectionID = 'db'; public function createUrl($manager,$route,$params,$ampersand) { if ($route==='car/index') { if (isset($params['manufacturer'], $params['model'])) return $params['manufacturer'] . '/' . $params['model']; else if (isset($params['manufacturer'])) return $params['manufacturer']; } return false; // this rule does not apply } public function parseUrl($manager,$request,$pathInfo,$rawPathInfo) { if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) { // check $matches[1] and $matches[3] to see // if they match a manufacturer and a model in the database // If so, set $_GET['manufacturer'] and/or $_GET['model'] // and return 'car/index' } return false; // this rule does not apply } }上面的數組包含了一系列自定義的選項設置,在版本1.1.0中,下面的選項是有效的:
- urlSuffix: URL所使用的後綴設定規則,預設是null,使用的是CUrlManager::urlSuffix的設定.
caseSensitive: 規則是否是大小學敏感的,預設是null,使用的是null,使用的是null,使用的是:caseSensitive的預設值.
- defaultParams: 規則提供的GET參數的預設值(name=>value). 當規則用來解析輸入請求的時候,該屬性中宣告的值將會注入$_GET.
matchValue: 當建立一個URL的時候GET參數的值是否和規則中對應的子模式相符. 預設是null, 表示使用的是CUrlManager::matchValue中的值. 如果屬性值是false, 意味著如果路由和參數名稱與給定的匹配那麼該規則被用來創建一個URL. 如果該屬性被設置為true,那麼給定的參數值一定也要和相應的子模式參數值相匹配. 注意如果設定此屬性的值為true將會降低效能
调用
$this->createUrl('post/read',array('year'=>2008,'title'=>'a sample post'))
生成/index.php/post/2008/a%20sample%20post
。第三个规则适用。调用
$this->createUrl('post/read')
产生/index.php/post/read
。请注意,没有规则适用。
总之,当使用createUrl生成网址,路线和传递给该方法的GET参数被用来决定哪些网址规则适用。如果关联规则中的每个参数可以在GET参数找到的,将被传递给createUrl ,如果路线的规则也匹配路线参数,规则将用来生成网址。
如果GET参数传递到createUrl是以上所要求的一项规则,其他参数将出现在查询字符串。例如,如果我们调用$this->createUrl('post/read',array('id'=>100,'year'=>2008))
,我们将获得/index.php/post/100?year=2008
。为了使这些额外参数出现在路径信息的一部分,我们应该给规则附加/*
。 因此,该规则post/<id:>/*</id:>
,我们可以获取网址/index.php/post/100/year/2008
。
正如我们提到的,URL规则的其他用途是解析请求网址。当然,这是URL生成的一个逆过程。例如, 当用户请求/index.php/post/100
,上面例子的第二个规则将适用来解析路线post/read
和GET参数array('id'=>100)
(可通过$_GET
获得) 。
createurl方法所产生的是一个相对地址。为了得到一个绝对的url ,我们可以用前缀
<code>yii">
注:使用的URL规则将降低应用的性能。这是因为当解析请求的URL ,[ CUrlManager ]尝试使用每个规则来匹配它,直到某个规则可以适用。因此,高流量网站应用应尽量减少其使用的URL规则。
参数化路由
从版本1.0.5开始, 我们可能会用到命名参数作为路由规则的一部分. 这就允许一个规则可以基于匹配规范被用来匹配多个路由,这也许还会帮助减少应用所需的规则的数目,从而提高整体的性能.
我们使用如下示例规则来说明如何通过命名参数来参数化路由:
array( '<_c:>/<id:>/<_a:>' => '<_c>/<_a>', '<_c:>/<id:>' => '<_c>/read', '<_c:>s' => '<_c>/list', )</_c></_c:></_c></id:></_c:></_a></_c></_a:></id:></_c:>
在上面的示例中, 我们在路由规则中使用了两个命名参数: _c
和_a
. The former matches a controller ID to be either post
or comment
, while the latter matches an action ID to be create
, update
or delete
. You may name the parameters differently as long as they do not conflict with GET parameters that may appear in URLs.
使用上面的规则, URL /index.php/post/123/create
将会被解析为 post/create
使用GET参数 id=123
. And given the route comment/list
and GET parameter page=2
, we can create a URL /index.php/comments?page=2
.
参数化主机名
从版本1.0.11开始, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://www.php.cn/
may be parsed into GET parameters user=admin
and lang=en
. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.
In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:
array( 'http://<user:>.example.com/<lang:>/profile' => 'user/profile', )</lang:></user:>
The above example says that the first segment in the hostname should be treated as user
parameter while the first segment in the path info should be lang
parameter. The rule corresponds to the user/profile
route.
Note that CUrlManager::showScriptName will not take effect when a URL is being created using a rule with parameterized hostname.
Also note that the rule with parameterized hostname should NOT contain the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under http://www.php.cn/
, then we should still use the same URL rule as described above without the sub-folder sandbox/blog
.
隐藏 index.php
还有一点,我们可以做进一步清理我们的网址,即在URL中藏匿index.php
入口脚本。这就要求我们配置Web服务器,以及urlManager应用程序元件。
我们首先需要配置Web服务器,这样一个URL没有入口脚本仍然可以处理入口脚本。如果是Apache HTTP server,可以通过打开网址重写引擎和指定一些重写规则。这两个操作可以在包含入口脚本的目录下的.htaccess
文件里实现。下面是一个示例:
Options +FollowSymLinks IndexIgnore */* RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php
然后,我们设定urlManager元件的showScriptName属性为 false
。
注意在正式测试之前确保apache开启了rewrite模块,在ubuntu中开启的方式如下:
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/rewrite.load rewrite.load
sudo service apache2 restart
现在,如果我们调用$this->createUrl('post/read',array('id'=>100))
,我们将获取网址/post/100
。更重要的是,这个URL可以被我们的Web应用程序正确解析。
Faking URL Suffix(伪造URL后缀)
我们还可以添加一些网址的后缀。例如,我们可以用/post/100.html
来替代/post/100
。这使得它看起来更像一个静态网页URL。为了做到这一点,只需配置urlManager元件的urlSuffix属性为你所喜欢的后缀。
3. 使用自定义URL规则设置类
注意: Yii从1.1.8版本起支持自定义URL规则类
默认情况下,每个URL规则都通过CUrlManager来声明为一个CUrlRule对象,这个对象会解析当前请求并根据具体的规则来生成URL。 虽然CUrlRule可以处理大部分URL格式,但在某些特殊情况下仍旧有改进余地。
比如,在一个汽车销售网站上,可能会需要支持类似/Manufacturer/Model
这样的URL格式, 其中Manufacturer
和 Model
都各自对应数据库中的一个表。此时CUrlRule就无能为力了。
我们可以通过继承CUrlRule的方式来创造一个新的URL规则类。并且使用这个类解析一个或者多个规则。 以上面提到的汽车销售网站为例,我们可以声明下面的URL规则。
array( // 一个标准的URL规则,将 '/' 对应到 'site/index' '' => 'site/index', // 一个标准的URL规则,将 '/login' 对应到 'site/login', 等等 '<action:>' => 'site/<action>', // 一个自定义URL规则,用来处理 '/Manufacturer/Model' array( 'class' => 'application.components.CarUrlRule', 'connectionID' => 'db', ), // 一个标准的URL规则,用来处理 'post/update' 等 '<controller:>/<action:>' => '<controller>/<action>', ),</action></controller></action:></controller:></action></action:>
从以上可以看到,我们自定义了一个URL规则类CarUrlRule
来处理类似/Manufacturer/Model
这样的URL规则。 这个类可以这么写:
class CarUrlRule extends CBaseUrlRule { public $connectionID = 'db'; public function createUrl($manager,$route,$params,$ampersand) { if ($route==='car/index') { if (isset($params['manufacturer'], $params['model'])) return $params['manufacturer'] . '/' . $params['model']; else if (isset($params['manufacturer'])) return $params['manufacturer']; } return false; // this rule does not apply } public function parseUrl($manager,$request,$pathInfo,$rawPathInfo) { if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) { // check $matches[1] and $matches[3] to see // if they match a manufacturer and a model in the database // If so, set $_GET['manufacturer'] and/or $_GET['model'] // and return 'car/index' } return false; // this rule does not apply } }
自定义URL规则类必须实现在CBaseUrlRule中定义的两个接口。
[CBaseUrlRule::createUrl()|createUrl()]
[CBaseUrlRule::parseUrl()|parseUrl()]
除了这种典型用法,自定义URL规则类还可以有其他的用途。比如,我们可以写一个规则类来记录有关URL解析和UEL创建的请求。 这对于正在开发中的网站来说很有用。我们还可以写一个规则类来在其他URL规则都匹配失败的时候显示一个自定义404页面。 注意,这种用法要求规则类在所有其他规则的最后声明。
以上就是Yii框架官方指南系列43——专题:URL(创建、路由、美化及自定义)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

要保護應用免受與會話相關的XSS攻擊,需採取以下措施:1.設置HttpOnly和Secure標誌保護會話cookie。 2.對所有用戶輸入進行輸出編碼。 3.實施內容安全策略(CSP)限制腳本來源。通過這些策略,可以有效防護會話相關的XSS攻擊,確保用戶數據安全。

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显著提升应用在高并发环境下的效率。

theSession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceisesneededeededeedeedeededto toavoidperformance andunununununexpectedLogOgouts.3)

在PHP中,可以使用session_name()函數配置會話名稱。具體步驟如下:1.使用session_name()函數設置會話名稱,例如session_name("my_session")。 2.在設置會話名稱後,調用session_start()啟動會話。配置會話名稱可以避免多應用間的會話數據衝突,並增強安全性,但需注意會話名稱的唯一性、安全性、長度和設置時機。

會話ID應在登錄時、敏感操作前和每30分鐘定期重新生成。 1.登錄時重新生成會話ID可防會話固定攻擊。 2.敏感操作前重新生成提高安全性。 3.定期重新生成降低長期利用風險,但需權衡用戶體驗。

在PHP中設置會話cookie參數可以通過session_set_cookie_params()函數實現。 1)使用該函數設置參數,如過期時間、路徑、域名、安全標誌等;2)調用session_start()使參數生效;3)根據需求動態調整參數,如用戶登錄狀態;4)注意設置secure和httponly標誌以提升安全性。

在PHP中使用會話的主要目的是維護用戶在不同頁面之間的狀態。 1)會話通過session_start()函數啟動,創建唯一會話ID並存儲在用戶cookie中。 2)會話數據保存在服務器上,允許在不同請求間傳遞數據,如登錄狀態和購物車內容。

如何在子域名間共享會話?通過設置通用域名的會話cookie實現。 1.在服務器端設置會話cookie的域為.example.com。 2.選擇合適的會話存儲方式,如內存、數據庫或分佈式緩存。 3.通過cookie傳遞會話ID,服務器根據ID檢索和更新會話數據。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用