URL重定向我們會使用到header函數來操作,最簡單的就是直接使用header(‘Location: ‘ . $url);就可以了,如果要做像301定向我們還需要發送狀態代碼,下面整理了一些例子一起來看看吧,代碼如下:
- // URL重定向
- function redirect($url, $time=0, $msg=”) {
- //多行URL地址支持
- $url = str_replace(array(“\n”, “\r”), ”, $url);
- if ( emptyempty($msg) )
- $msg = “系統將在{$time}秒之后自動跳轉到{$url}!”;
- if (!headers_sent()) {
- // redirect
- if (0 === $time) {
- header(‘Location: ‘ . $url);
- } else {
- header(“refresh:{$time};url={$url}”);
- echo($msg);
- }
- exit();
- } else {
- $str = “<meta http-equiv=’Refresh’ content=’{$time};URL={$url}’>”;
- if ($time != 0)
- $str .= $msg;
- exit($str);
- }
- }
- //url重定向2
- function redirect($url) {
- echo “<script>”.
- “function redirect() {window.location.replace(‘$url’);}\n”.
- “setTimeout(‘redirect();’, 1000);\n”.
- “</script>”;
- exit();
- }
用HTTP頭信息
也就是用PHP的HEADER函數。PHP里的HEADER函數的作用就是向瀏覽器發出由HTTP協議規定的本來應該通過WEB服務器的控制指令,例如聲明返回信息的類型("Context-type: xxx/xxx"),頁面的屬性("No cache", "Expire")等等。
用HTTP頭信息進行PHP重定向到另外一個頁面的方法,代碼如下:
- <?php
- $url = "www.companysz.com";
- if (!emptyempty($url))
- {
- Header("HTTP/1.1 303 See Other"); //這條語句可以不寫
- Header("Location: $url");
- }
- ?>
注意一下,"Localtion:"后面有一個空格,下面整理了一個全面的函數,代碼如下:
- /**
- * get_redirect_url()
- * Gets the address that the provided URL redirects to,
- * or FALSE if there's no redirect.
- *
- * @param string $url
- * @return string
- */
- function get_redirect_url($url){
- $redirect_url = null;
- $url_parts = @parse_url($url);
- if (!$url_parts) return false;
- if (!isset($url_parts['host'])) return false; //can't process relative URLs
- if (!isset($url_parts['path'])) $url_parts['path'] = '/';
- $sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
- if (!$sock) return false;
- $request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1rn";
- $request .= 'Host: ' . $url_parts['host'] . "rn";
- $request .= "Connection: Closernrn";
- fwrite($sock, $request);
- $response = '';
- while(!feof($sock)) $response .= fread($sock, 8192);
- fclose($sock);
- if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
- return trim($matches[1]);
- } else {
- return false;
- }
- }
- /**
- * get_all_redirects()
- * Follows and collects all redirects, in order, for the given URL.
- *
- * @param string $url
- * @return array
- */
- function get_all_redirects($url){
- $redirects = array();
- while ($newurl = get_redirect_url($url)){
- if (in_array($newurl, $redirects)){
- break;
- }
- $redirects[] = $newurl;
- $url = $newurl;
- }
- return $redirects;
- }
- /**
- * get_final_url()
- * Gets the address that the URL ultimately leads to.
- * Returns $url itself if it isn't a redirect.
- *
- * @param string $url
- * @return string
- */
- function get_final_url($url){
- $redirects = get_all_redirects($url);
- if (count($redirects)>0){
- return array_pop($redirects);
- } else {
- return $url;
- }
- }
新聞熱點
疑難解答