PHP Program to show current page URL

Содержание
  1. Как получить текущий URL в PHP?
  2. Полный URL
  3. Результат:
  4. URL без GET-параметров
  5. Результат:
  6. Основной путь и GET-параметры
  7. Результат:
  8. Только основной путь
  9. Результат:
  10. Только GET-параметры
  11. Результат:
  12. Результат:
  13. Комментарии 2
  14. Другие публикации
  15. How to Get Current Page URL, Domain, Query String in PHP
  16. How to Get Current Page URL in PHP
  17. PHP Program for get Current Page Url
  18. Program 1 full source Code
  19. PHP Program to show current page URL
  20. PHP Program show Current page full URL
  21. Program 2 full source Code
  22. PHP Program show Current page full URL
  23. PHP Program show Current full URL with Query String
  24. Program 3 full source Code
  25. PHP Program show Current page full URL with Query String
  26. Other Important elements of $_SERVER that are very are useful and you must know that:
  27. Author Admin
  28. Php view page url
  29. Learn Latest Tutorials
  30. Preparation
  31. Trending Technologies
  32. B.Tech / MCA
  33. Javatpoint Services
  34. Training For College Campus
  35. Как получить текущий URL адрес в PHP
  36. Полный URL
  37. URL без GET параметров
  38. Адрес страницы с GET параметрами
  39. Только адрес страницы
  40. Только GET параметры
  41. How to Get the Current Page URL of a Web Page Using PHP
  42. Full URL of Current Page
  43. Actual PHP Output of this Page
  44. Directory Pathway and File name
  45. Actual PHP Output of this Page
  46. Just the Directory Pathway
  47. Actual PHP of this Page
  48. Just the File Name
  49. Actual PHP Output of this Page
  50. 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

Авторизуйтесь, чтобы добавить комментарий.

Читайте также:  Python smtp send message

Другие публикации

Чтение Google таблиц в PHP

Как получить данные из 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

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

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 RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Как получить текущий 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.

Источник

Оцените статью