Get server url in html

Содержание
  1. Как получить текущий URL в PHP?
  2. Полный URL
  3. Результат:
  4. URL без GET-параметров
  5. Результат:
  6. Основной путь и GET-параметры
  7. Результат:
  8. Только основной путь
  9. Результат:
  10. Только GET-параметры
  11. Результат:
  12. Результат:
  13. Комментарии 2
  14. Другие публикации
  15. JavaScript: Get Current URL and Components (Protocol, Domain, Port, Path, Query, Hash)
  16. URL Components
  17. How to Get Current URL in JavaScript
  18. Get URL Origin
  19. Get URL Protocol
  20. Get URL Host and Hostname
  21. Get URL Port
  22. GET URL Path
  23. Get URL Query and Hash
  24. Free eBook: Git Essentials
  25. Conclusion
  26. Как получить ссылку на текущую страницу при помощи JS и PHP
  27. Как получить ссылку на текущую страницу в Javascript
  28. window.location.href
  29. window.location.hostname
  30. window.location.pathname
  31. window.location.search
  32. Как получить ссылку на текущую страницу в PHP
  33. Полный адрес текущей страницы на PHP
  34. Путь к текущей странице без параметров
  35. Путь без домена и параметров
  36. Получить только GET-параметры текущей страницы
  37. Похожие публикации
  38. Как получить текущий URL в PHP?
  39. Полный URL
  40. Результат:
  41. URL без GET-параметров
  42. Результат:
  43. Основной путь и GET-параметры
  44. Результат:
  45. Только основной путь
  46. Результат:
  47. Только GET-параметры
  48. Результат:
  49. Результат:
  50. Комментарии 2
  51. Другие публикации

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

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

Читайте также:  How to add class with css

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

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

Как получить данные из Google spreadsheets в виде массива PHP? Очень просто, Google docs позволяет экспортировать лист в формате CSV, главное чтобы файл был в общем доступе.

Сортировка массивов

В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.

Источник

JavaScript: Get Current URL and Components (Protocol, Domain, Port, Path, Query, Hash)

In this tutorial, we’ll take a look at how to get the current URL of a loaded HTML page, using JavaScript.

Firstly, let’s take a look at a URL:

https://www.stackabuse.com:8080/category/article-title.html?searchterm=Example+title#2 

It’s a made-up URL, that contains several components — the protocol, domain, port, path, query and hash.

If you’d like to avoid handling the parsing of URLs manually, especially with more complex URL formats such as Git’s — read on How to Easily Parse URLs in JavaScript with parse-url!

URL Components

The URL we’ve defined consists of different segments, divided by certain special characters such as / , ? and # . Each of these segments is a URL component:

  • Protocol — The protocol of a URL refers to the URL segment which defines which protocol is used for data transfer. In our case, we’re using https:// , signifying the HTTPS protocol.
  • Domain — The domain, also known as the hostname of an URL refers to the proceeding section of a URL — www.stackabuse.com .
  • Port — The port section of an URL is specified after the domain, preceded by : . Most of the time, the port isn’t public, so you’ll rarely actually see it in deployed applications, but very commonly in the development phase.
  • Path — The path section of an URL follows the domain name and port. It specifies a single resource on a website, HTML page, image, or some other type of file or directory. In our example, the path refers to the /category/article-title.html segment, meaning that it points to the article-title.html file on the server.
  • Query — The query is a string that is usually used to enable internal searches on a website. The query section refers to the ?articleTitle=Example+title section of the example URL and is a result of the user entering the search term Example title on the article-title.html page of the website.
  • Hash — The hash section is usually used to represent an anchor on the page, which is commonly a heading, but can be any other or tag, given that we aim at its id attribute. In our case, we aim at #2 , scrolling the user’s view to the tag with an id=2 .

Generally speaking, URLs have a fairly standardized structure, where certain elements are optional, while others aren’t:

Now, we can take a closer look at how to access the current URL, as well as each of its components using JavaScript.

How to Get Current URL in JavaScript

In JavaScript, the Location object contains the information regarding the URL of the currently loaded webpage. It belongs to window , though, we can access it directly because window is hierarchically located at the top of the scope

To get the current URL, we’ll leverage the Location object and retrieve its href property:

let url = window.location.href console.log(url) 
https://www.stackabuse.com:8080/python/article-title.html?searchterm=Example+title#2 

The href property contains the full URL to the currently loaded resource. If you’d like to retrieve some certain components, rather than the entire URL, the Location object has various properties as well.

Get URL Origin

The window.location.origin property returns the base URL (protocol + hostname + port number) of the current URL:

console.log(window.location.origin) 
https://www.stackabuse.com:8080 

Get URL Protocol

The window.location.protocol property returns the protocol used by the current URL:

console.log(window.location.protocol) 

Get URL Host and Hostname

The window.location.host property returns the hostname and the port number of the current URL:

console.log(window.location.host) 

On the other hand, the window.location.hostname property returns the hostname of the current URL:

console.log(window.location.hostname) 

Get URL Port

The window.location.port property returns the port number of the current URL:

console.log(window.location.port) 

GET URL Path

The window.location.pathname property returns the path section of the current URL:

console.log(window.location.pathname) 

Get URL Query and Hash

The window.location.search property returns **the query section ** of the current URL:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

console.log(window.location.search) 

The window.location.hash property returns the hash section of the current URL:

console.log(window.location.hash) 

Conclusion

As we’ve seen, JavaScript provides a powerful, yet simple, way of accessing the current URL. The Location object, accessed by the Window interface enables us to get not only the string representation of the current URL but every single section of it.

The Location object also can change and manipulate the current URL, as well as redirect the page to the new URL.

Источник

Как получить ссылку на текущую страницу при помощи JS и PHP

Привет, друзья. Сегодня поговорим о том, как в JS и PHP получить адрес текущей страницы. Дело в том, что разработчику часто нужно выполнить какой-то код, только на определенных страницах или в зависимости от каких-то GET параметров. Как раз в таких случаях удобно сохранить все данные из адресной строки в объект или строку, чтобы иметь возможность удобно манипулировать своим кодом/разметкой в зависимость от полученных параметров.

Обычно я сталкиваюсь с такими задачами:

  • Получение utm-меток, в зависимости от которых мы можем менять контент на странице.
  • Определение адреса страниц, на которых стоит подключить какой-то скрипт.
  • Получение адреса страницы для передачи ссылки в форму обратной связи, чтобы понимать с какой страницы совершён заказ ( в том числе и передача utm-меток в форму).

Как получить ссылку на текущую страницу в Javascript

Для начала давайте разберемся как справиться с задачей при помощи js. В javascript есть объект Location, который позволяет получить текущий URL страницы. Доступ к нему я обычно произвожу через глобальный объект Window или Document. В итоге Window.location возвращает нам объект со свойствами, в которых и содержится интересующая нас информация. Например, самыми популярными для меня свойствами являются: href, hostname, pathname и search.

window.location.href

console.log(window.location.href); // вернёт: https://smartlanding.biz/smartroulette-lp/index.php?utm_source=yandex

Команда возвращает полный адрес страницы, то есть ссылку со всеми параметрами.

window.location.hostname

console.log(window.location.hostname); //вернет smartlanding.biz

Команда возвращает домен текущей страницы.

window.location.pathname

console.log(window.location.pathname); //вернет /smartroulette-lp/index.php

Вернет путь до текущей страницы, исключая домен и параметры. То есть покажет категорию/рубрику/папку, в которой находится страница.

console.log(window.location.search); // Вернет ?utm_source=yandex

Возвращает GET-параметр начиная со знака «?», то есть позволяет получить любые параметры, которые вы передаёте вместе со ссылкой. В том числе и пресловутые UTM-метки.

Как видите, в js есть все, чтобы легко справиться с задачей получения ссылки на текущую страницу. Но это не все возможности, которые дает нам javascript. Также можно получить протокол, порт, домен с портом и хеш из адресной строки. Делается это при помощи следующих свойств: protocol, port, host и hash.

console.log(window.location.protocol); // вернет https: console.log(window.location.port); // вернет номер порта, если он присутствует в адресной строке console.log(window.location.host); // вернёт домен и порт, если он есть console.log(window.location.hash); // вернет хеш страницы, начиная с символа #, например, #testmarker

Как получить ссылку на текущую страницу в PHP

Теперь давайте посмотрим на PHP. На самом деле тут тоже дела обстоят подобным образом. Есть готовый массив $_SERVER , который содержит в том числе и путь к текущей странице.

Как и в прошлый раз покажу на примере адреса:

Полный адрес текущей страницы на PHP

$currentUrl= ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $currentUrl; // Выведет https://smartlanding.biz/smartroulette-lp/index.php?utm_source=yandex

Путь к текущей странице без параметров

$currentUrl = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $currentUrl = explode('?', $currentUrl); $currentUrl = $currentUrl[0]; echo $currentUrl; // Выведет https://smartlanding.biz/smartroulette-lp/index.php

Путь без домена и параметров

$currentUrl = $_SERVER['REQUEST_URI']; $currentUrl = explode('?', $url); $currentUrl = $Url[0]; echo $currentUrl; // Вернет /smartroulette-lp/index.php

Получить только GET-параметры текущей страницы

$currentUrl = $_SERVER['QUERY_STRING']; echo $currentUrl; // Выведет utm_source=yandex

Если остались какие-то вопросы — задавайте в комментариях. Попробуем решить.

Похожие публикации

Источник

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

Как получить данные из Google spreadsheets в виде массива PHP? Очень просто, Google docs позволяет экспортировать лист в формате CSV, главное чтобы файл был в общем доступе.

Сортировка массивов

В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.

Источник

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