- Как получить текущий URL в PHP?
- Полный URL
- Результат:
- URL без GET-параметров
- Результат:
- Основной путь и GET-параметры
- Результат:
- Только основной путь
- Результат:
- Только GET-параметры
- Результат:
- Результат:
- Комментарии 2
- Другие публикации
- How to Get Current Page URL, Domain, Query String in PHP
- How to Get Current Page URL in PHP
- PHP Program for get Current Page Url
- Program 1 full source Code
- PHP Program to show current page URL
- PHP Program show Current page full URL
- Program 2 full source Code
- PHP Program show Current page full URL
- PHP Program show Current full URL with Query String
- Program 3 full source Code
- PHP Program show Current page full URL with Query String
- Other Important elements of $_SERVER that are very are useful and you must know that:
- Author Admin
- Php view page url
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Как получить текущий URL адрес в PHP
- Полный URL
- URL без GET параметров
- Адрес страницы с GET параметрами
- Только адрес страницы
- Только GET параметры
- How to Get the Current Page URL of a Web Page Using PHP
- Full URL of Current Page
- Actual PHP Output of this Page
- Directory Pathway and File name
- Actual PHP Output of this Page
- Just the Directory Pathway
- Actual PHP of this Page
- Just the File Name
- Actual PHP Output of this Page
- Just the File Name Without the File Extension
Как получить текущий URL в PHP?
Сформировать текущий адрес страницы можно с помощью элементов массива $_SERVER. Рассмотрим на примере URL:
Полный URL
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url;
Результат:
https://example.com/category/page?sort=asc
URL без GET-параметров
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;
Результат:
https://example.com/category/page
Основной путь и GET-параметры
$url = $_SERVER['REQUEST_URI']; echo $url;
Результат:
Только основной путь
$url = $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;
Результат:
Только GET-параметры
Результат:
Для преобразования строки с GET-параметрами в ассоциативный массив можно применить функцию parse_str() .
parse_str('sort=asc&page=2&brand=rich', $get); print_r($get);
Результат:
Array ( [sort] => asc [page] => 2 [brand] => rich )
Комментарии 2
Авторизуйтесь, чтобы добавить комментарий.
Другие публикации
Как получить данные из Google spreadsheets в виде массива PHP? Очень просто, Google docs позволяет экспортировать лист в формате CSV, главное чтобы файл был в общем доступе.
В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.
How to Get Current Page URL, Domain, Query String in PHP
In this tutorial, We would love to share with you, How to get current page URL in PHP, PHP get current URL path, PHP get full URL with parameters, PHP get a current page, PHP get current URL with query string, PHP get a domain from URL.
How to Get Current Page URL in PHP
Here you will discuss about superglobal variable $_SERVER, this is built-in PHP variable. We will use this variable get the current page URL in PHP. You can get every piece of information about the current URL using the $_SERVER superglobal.
Before we try to fetch the Current Page Full URL lets see how a normal URL structure looks like:
http://www.abc.com/dir1/test.php?glob=hello&name=world
Any typical URL like this can be broken into several common parts like:
- HTTP: The URL protocol
- www.abc.com – The domain name or the hostname.
- dir1: The directory within the root
- test.php – The actual PHP script
- glob=hello – the first URL parameter (glob) and it’s a value (hello)
- name=world – the second URL parameter (name) and its value (world)
Now we will create a program that is used to get current page url.
PHP Program for get Current Page Url
Program 1 full source Code
PHP Program to show current page URL
PHP Program show Current page full URL
Program 2 full source Code
PHP Program show Current page full URL
PHP Program show Current full URL with Query String
Program 3 full source Code
PHP Program show Current page full URL with Query String
Other Important elements of $_SERVER that are very are useful and you must know that:
- $_SERVER[‘SERVER_ADDR’]: IP address of the server
- $_SERVER[‘REQUEST_METHOD’]: Returns the page access method used i.e. ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’.
- $_SERVER[‘REQUEST_TIME’]: timestamp of the start of the request.
- $_SERVER[‘HTTP_REFERER’]: returns the referrer page uri – used in redirecting to last page after login
- $_SERVER[‘SCRIPT_FILENAME’]: returns the path including the filename, like DIR
- $_SERVER[‘HTTP_COOKIE’]. returns the raw value of the ‘Cookie’ header sent by the user agent.
- $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]): returns the default set language – useful for websites with multilingual content & readers
- $_SERVER[‘HTTP_USER_AGENT’]: returns the kind of device being used to access (desktop/mobile device etc) – suitable for switching interface for different devices.
Author Admin
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
Php view page url
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Как получить текущий URL адрес в PHP
Не пропусти свежие посты, подпишись:
Для работы с текущим URL страницы в основном используется глобальный массив $_SERVER. Этот массив содержит информацию о сервере и среде исполнения скриптов. Из него можно достать некоторые заголовки, адреса скриптов и другое. Однако, т.к. этот массив формируется сервером, его содержание может несколько разниться.
- HTTPS — Принимает непустое значение, если запрос был произведён через протокол HTTPS.
- HTTP_HOST — Содержимое заголовка Host: из текущего запроса, если он есть.
- REQUEST_URI — URI, который был передан для того, чтобы получить доступ к этой странице. Например, ‘/index.html’.
- QUERY_STRING — Строка запросов, если есть, с помощью которой была получена страница.
Полный URL
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url;
Результат: https://site.com/category/page?sort=asc
URL без GET параметров
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; //Разбиваем полный URL по символу «?», после которого перечисляются //GET параметры, т.е. получаем массив с 2 строками 0 - путь, 1 - GET параметры $url = explode('?', $url); $url = $url[0];
Результат: https://site.com/category/page
Адрес страницы с GET параметрами
$url = $_SERVER['REQUEST_URI']; echo $url;
Результат: /category/page?sort=asc
Только адрес страницы
$url = $_SERVER['REQUEST_URI']; //Разбиваем строку по тому же правило, что было описано выше $url = explode('?', $url); $url = $url[0]; echo $url;
Результат: /category/page
Только GET параметры
Однако с такой строкой не очень то удобно работать, но её можно преобразовать в ассоциативный массив. Для этого существует функция parse_str() она разбирает строку GET запроса на переменные.
$output = []; parse_str($_SERVER['QUERY_STRING'], $output);
Не пропусти свежие посты, подпишись:
How to Get the Current Page URL of a Web Page Using PHP
In this tutorial, we show how to get the current page URL of a web page using PHP.
Full URL of Current Page
To get the full URL of the current page, which takes the form http://www.website.com/Directory/pagename.html, you can use the following code below.
The $_SERVER[‘HTTP_HOST’] gets the www.website.com name of the website in use. For this web page you are current on, this would return www.learningaboutelectronics.com
The $_SERVER[‘REQUEST_URI’] returns the directory pathway and file name of the page you are on.
Actual PHP Output of this Page
Directory Pathway and File name
To return just the directory pathway and the file name of the web page, you can use the following code below.
This is the part after http://www.website.com/
So this code above returns the part after the type of domain name the web page is.
Actual PHP Output of this Page
Just the Directory Pathway
To return just the directory pathway of the current web page URL, you can use the following code below.
This code above returns just the directory pathway to the current page URL.
Actual PHP of this Page
Just the File Name
To just return the file name of the current page, you can use the following code below.
This code above returns only the file name of the current page URL.
Actual PHP Output of this Page
Just the File Name Without the File Extension
Sometimes you may just want to return the file name without the file extension.
To do this, you can use the following code below.
The code above returns just the file name without the file extension included.