[PHP] URL取得のカンタンコード

2015年3月10日

PHP プログラミング

JavaScriptで今開いているブラウザのURLを取得するのは「location.href」で取得できるが、PHPは、意外と面倒くさい。 とりあえず、javascriptのように、サクッと取得できる関数を作ってみた。

コード

/** * URL関連処理 */ class URL{ /** * 現在のポートの取得(80 , 443判別有り) * port + domain [http://hoge.com:8800/] */ function getSite(){ //通常のhttp処理 if($_SERVER['SERVER_PORT']==80){ $site = 'http://'.$_SERVER['SERVER_NAME']; } //httpsページ処理 else if($_SERVER['SERVER_PORT']==443){ $site = 'https://'.$_SERVER['SERVER_NAME']; } //その他ペート処理 else{ $site = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT']; } return $site; } /** * 現在ページのサービスroot階層のパスを返す */ function getDir(){ $path = preg_match("@^/@","",$_SERVER['REQUEST_URI']); if(is_dir($path)){ return $path; } else{ return dirname($path); } } /** * 現在のクエリ無しパスを返す */ function getUrl(){ $uri = $this->getSite(); $req = explode('?',$_SERVER['REQUEST_URI']); $uri.= $req[0]; return $uri; } /** * フルパスを返す */ function getUri(){ $uri = $this->getSite(); $uri.= $_SERVER['REQUEST_URI']; return $uri; } /** * 基本ドメインを返す */ function getDomain(){ return $_SERVER['SERVER_NAME']; } /** * リダイレクト処理 */ function setUrl($url){ if(!$url){return;} header('Location: '.$url); } }

使い方

$url = new URL(); //root階層までを取得 # http://hoge.com/a/test.php?a=111 $url_string = $url->getSite(); print_r($url_string); # [結果] http://hoge.com/ //現在の階層までを取得 # http://hoge.com/a/test.php?a=111 $url_string = $url->getDir(); print_r($url_string); # [結果] http://hoge.com/a/ //URLを取得 # http://hoge.com/a/test.php?a=111 $url_string = $url->getURL(); print_r($url_string); # [結果] http://hoge.com/a/test.php //URIを取得 # http://hoge.com/a/test.php?a=111 $url_string = $url->getURI(); print_r($url_string); # [結果] http://hoge.com/a/test.php?a=111 //ドメインを取得 # http://hoge.com/a/test.php?a=111 $url_string = $url->getDomain(); print_r($url_string); # [結果] hoge.com

注意点

PHPは5.x以上を使おう。 もう4.xを使っていると、色々と面倒だぞ!

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。