Yii 1.1: URL component access functions

16 followers

Many applications wish to obtain parts of the URL for the current page (the hostname, the query string, etc.), and the CHttpRequest class wraps various $_SERVER variables to break down the URL into its constituent parts.

It's sometimes confusing to read the descriptions of each one and know exactly what it represents, so this page shows a full URL with all the parts broken out.

FULL URL ----->  http://www.example.com:8080/project/index.php?r=post/view&id=123

PROPERTY
hostInfo         http://www.example.com:8080
port                                    8080
baseUrl                                     /project
url                                         /project/index.php?r=post/view&id=123
requestUri                                  /project/index.php?r=post/view&id=123
scriptUrl                                   /project/index.php
queryString                                                    r=post/view&id=123
scriptFile                     /var/www/html/project/index.php

The names on the left are the properties of CHttpRequest, and can be accessed via Yii::app()->request->hostInfo and the like.

A few notes:

  • If the index.php script is directly under the webroot, CHttpRequest::baseUrl will return an empty string
  • Though it appears that CHttpRequest::url and CHttpRequest::requestUri return the same value, the underlying code is different and it's not clear how the differences manifest themselves (Update: in 1.1.7, the two will be the same)
  • There doesn't appear to be a single method to return the entire request URL in a single step; one can concatenate CHttpRequest::hostInfo and CHttpRequest::url to achieve this

Total 1 comment

#6055 report it
fsb at 2011/12/08 01:13pm
Very handy reference

Useful and nicely concise.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: Steve Friedl
  • Category: Tips
  • Yii Version: 1.1
  • Votes: +28
  • Viewed: 10,581 times
  • Created on: Mar 10, 2011
  • Last updated: Mar 11, 2011
  • Tags: URL, request