Php script location href

Как получить ссылку на текущую страницу при помощи 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 , который содержит в том числе и путь к текущей странице.

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

Читайте также:  Sql select statements in java

Полный адрес текущей страницы на 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

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

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

Источник

How to Make a Redirect in PHP

Redirects are particularly useful when web admins are migrating websites to a different domain, implementing HTTPS, or deprecating pages.

There are several ways to implement a redirect, with PHP redirects being one of the easiest and safest methods. A PHP redirect is a server-side redirect that quickly redirects users from one web page to another.

Even though PHP redirects are considered safe, not implementing them correctly can cause serious server issues.

This guide explains two ways to set up a PHP redirect, and the advantages and disadvantages of each method.

How to set up a PHP redirect.

Method 1: PHP Header Function

The fastest and most common way to redirect one URL to another is by using the PHP header() function.

The general syntax for the header() function is as follows:

header( $header, $replace, $http_response_code ) 
  • $header . The URL or file name of the resource being redirected to. Supported file types include but are not limited to HTML, PDF, PHP, Python, Perl, etc.
  • $replace(optional). Indicates whether the current header should replace a previous one or just add a second header. By default, this is set to true . Using false forces the function to use multiple same-type headers.
  • $http_response_code(optional). Sets the HTTP response code to the specified value. If not specified, the header returns a 302 code.

Important: To correctly redirect using the header() function, it must be placed in the page’s source code before any HTML. Place it at the very top of the page, before the !DOCTYPE declaration.

Читайте также:  Задача все вместе python

Consider the following PHP code example:

The defined header() function redirects the page to http://www.example.com/example-url, replaces any previous header function and generates a 301 response code.

The exit() or die() function is mandatory. If not used, the script may cause issues.

Note: Permanent (301) redirects are typically used for broken or removed pages. That way, users are redirected to a page relevant to them.

Method 2: JavaScript via PHP

If using the PHP header() function is not a viable solution, use JavaScript to set up a PHP redirect. Take into consideration that JavaScript redirects via PHP work slower and require the end user’s browser to have JS enabled and downloaded.

There are three ways to set up a PHP redirect using the JS window.location function:

Below is a brief overview of the differences between the three options:

window.location.href window.location.assign window.location.replace
Function Returns and stores the URL of the current page Replaces the current page. Loads a new document.
Usage Fastest JS redirect method. Used when the original webpage needs to be removed from browser history. Safer than href.
Does it show the current page?
Does it add a new entry to the user’s browser history?
Does it delete the original page from the session history?

window.location.href

window.location.href sets the location property of a page to a new URL.

The following code is used to call window.location.href via PHP.

 window.location.href="http://www.example-url.com" ?> 

The advantage of window.location.href is that it is the fastest-performing JS redirect. The disadvantage is that if the user navigates back, they return to the redirected page.

window.location.assign

window.location.assign() calls a function to display the resource located at the specified URL.

Note: window.location.assign() only works via HTTPS. If the function is used for an HTTP domain, the redirect does not function, and it displays a security error message instead.

The following code snippet calls the window.location.assign() via PHP:

 window.location.assign("http://www.example-url.com") ?> 

The disadvantage of using window.location.assign() is that its performance and speed is determined by the browser’s JavaScript engine implementation. However, its the safer option. Should the target link be broken or unsecure, the function will display a DOMException – an error message.

window.location.replace

window.location.replace() replaces the current page with the specified URL.

Note: window.location.replace() only works on secure domains (HTTPS) too.

The following code is used to call window.location.replace() via PHP:

 window.location.replace("http://www.example-url.com") ?> 

Once a page is replaced, the original resource does not exist in the browser’s history anymore, meaning the user cannot click back to view the redirected page.

Читайте также:  Как научиться html языку

The advantage of window.location.replace() is that, just like window.location.assign() , it does not allow redirects to broken or unsecure links, in which case it outputs a DOMException .

The disadvantage of window.location.replace() is that it may perform slower than window.location.href() .

PHP Header Vs. JS Methods — What to Use?

The general consensus is that the PHP header() function is the easiest and fastest way to set up a PHP redirect. JavaScript via PHP is typically reserved as an alternative when setting up the PHP header fails.

This is due to two reasons:

  • JavaScript must be enabled and downloaded on the end user’s browser for redirects to function.
  • JavaScript redirects perform slower.

You now know how to set up a PHP redirect using the header() function or through some clever use of JavaScript.

After setting up redirects, monitor their performance. A routine website audit can detect the presence of redirect loops and chains, missing redirects or canonicals, and potential setup errors (redirects being temporary instead of permanent, and vice versa).

Источник

Как сделать редирект PHP

Как сделать редирект PHP

На страницах сайтов постоянно что-то добавляется, удаляется и обновляется, чтобы в поисковиках была только актуальная информация и нужные страницы не выпадали из поиска применяются редиректы. Также редиректы используются после отправки форм чтобы не было возможности отправить форму несколько раз.

  • 301 – текущая страница удалена на всегда, заменой старой считать новый URL.
  • 302 – текущая страница временно не доступна, заменой считать пока новый URL.
  • 303 – используется после отправки формы методом POST (подробнее Post/Redirect/Get — PRG).

Итак, сделать 301-й редирект можно так:

header('Location: https://example.com', true, 301); exit();

Но функция header() не сработает если до ее вызова в браузер уже выводился какой-то контент и вызовет ошибку:

Warning: Cannot modify header information — headers already sent by…

Исправить ее можно использовав буферизацию вывода добавив в самое начало скрипта ob_start() ;

Также можно подстраховаться добавив JS-редирект и ссылку если функция header() не сработает.

Упростить использование кода можно выделив его в отдельную функцию:

function redirect($url, $code = 301) < header('Location: ' . $url, true, $code); echo ""; echo 'Перенаправление… Перейдите по ссылке.'; exit(); > /* В index.php */ if ($_SERVER['REQUEST_URI'] == '/url-old') < redirect('https://example.com/url-new'); >
$urls = array( array('/url-old-1', 'https://example.com/url-new-1'), array('/url-old-2', 'https://example.com/url-new-2'), array('/url-old-3', 'https://example.com/url-new-3'), ); foreach ($urls as $row) < if ($_SERVER['REQUEST_URI'] == $row[0]) < redirect($row[1]); >>

Источник

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