/home/lay-duong-dan-url-hien-tai-trong-php

Lấy đường dẫn URL hiện tại trong PHP

Published on | Updated

Trong PHP, việc xử lý thư mục khá giống trong C, có đôi phần dễ dàng hơn.

Để lấy thư mục làm việc hiện tại trong PHP, ta thường dùng dirname( __FILE__ ), nhưng để lấy đường dẫn URL hiện tại chúng ta phải dựa vào $_SERVER. Biến này nắm giữ tất cả các thông tin như: tên máy chủ, script nào đang chạy, giao thức (http hay https), ...

Bạn có thể tìm thấy hàng đống hướng dẫn về $_SERVER trên mạng, nên tôi sẽ không viết hướng dẫn cho biến này.
Tôi sẽ viết một function sẽ trả về đường dẫn url hiện tại.

Đây là vài dòng mã viết thành function, bạn có thể gọi ở bất cứ đâu

function my_url() {
    $url = (!empty($_SERVER[‘HTTPS’])) ? "https://".$_SERVER[‘SERVER_NAME’].$_SERVER[‘REQUEST_URI’] : "http://".$_SERVER[‘SERVER_NAME’].$_SERVER[‘REQUEST_URI’];

    return $url;
}

Gọi function đơn giản:

$url = my_url();

Nó sẽ trả về đường dẫn URL hiện tại.

Dưới đây là 1 class tôi mở rộng chức năng, cung cấp cho bạn nhiều tùy chọn trong thao tác với URL

<?php 
class Nx_Url { 
    public $protocol;
    public $site;
    public $thisfile;
    public $real_directories;
    public $num_of_real_directories;
    public $virtual_directories = array();
    public $num_of_virtual_directories = array();
    public $baseurl;
    public $thisurl;

    public function __construct() {
        $this—>protocol = ( isset( $_SERVER["HTTPS"] ) && strtolower( $_SERVER["HTTPS"] ) == "on" ) ? ‘https’ : ‘http’;
        $this->site = $this->protocol . '://' . $_SERVER[‘HTTP_HOST’];
        $this->thisfile = basename($_SERVER[‘SCRIPT_FILENAME’]);
        $this->real_directories = $this->clean(explode("/", str_replace($this->thisfile, "", $_SERVER[‘PHP_SELF’])));
        $this->num_of_real_directories = count($this->real_directories);
        $this->virtual_directories = array_diff($this->clean(explode("/", str_replace($this->thisfile, "", $_SERVER[‘REQUEST_URI’]))),$this->real_directories);
        $this->num_of_virtual_directories = count($this->virtual_directories);
        $this->baseurl = $this->site . "/" . implode("/", $this->real_directories) ;
        $this->thisurl = $this->baseurl . implode("/", $this->virtual_directories) ;
        if( strcmp ( substr( $this->thisurl, -1 ), "/" ) != 0 )
        $this->thisurl = $this->thisurl."/";
        if( strcmp ( substr( $this->baseurl, -1 ), "/" ) != 0 )
        $this->baseurl = $this->baseurl."/";
    }

    private function clean($array)
    {
        $cleaned_array = array();
        foreach($array as $key => $value)
        {
            $qpos = strpos($value, "?");

            if($qpos !== false)
            {
                break;
            }

            if($key != "" && $value != "")
            {
                $cleaned_array[] = $value;
            }
        }

        return $cleaned_array;
    }
}

Class này có thể trả về URL chính, đường dẫn URL hiện tại, tên script đang chạy, hostname, giao thức (http hay https), ...

Cơ bản là sử dụng $_SERVER để thao tác với đường dẫn và URL.

Ví dụ sử dụng:

$info = new Nx_Url();

echo "This url: ".$info->thisurl;
print "";
echo "Site: ".$info->site;
print "";
echo "This file: ".$info->thisfile;

Cảm ơn pelister :)