Using the href property of the Location object

How to Redirect a Web Page with PHP

This short snippet will show you multiple ways of redirecting a web page with PHP.

So, you can achieve redirection in PHP by following the guidelines below.

Using the header() Function

This is an inbuilt PHP function that is used for sending a raw HTTP header towards the client.

The syntax of the header() function is as follows:

header( $header, $replace, $http_response_code )

Also, it is likely to apply this function for sending a new HTTP header, but one should send it to the browser prior to any text or HTML.

Let’s see how to redirect a web page using the header() function:

 header('Location: //www.w3docs.com'); // or die(); exit(); ?>

As you can notice, exit() is used in the example above. It is applied to prevent the page from showing up the content remained (for instance, prohibited pages).

Also, you can use the header() function with ob_start() and ob_end_flush() , like this:

 ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page

Using a Helper Function

Here, we will demonstrate how to use a helper function for redirecting a web page. Here is an example:

 function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); > Redirect('//www.w3docs.com/', false);

All HTTP status codes are listed at HTTP Status Messages

Note that this function doesn’t support 303 status code!

Let’s check out a more flexible example:

 function redirect($url, $statusCode = 303) < header('Location: ' . $url, true, $statusCode); die(); >

In some circumstances, while running in CLI (redirection won’t take place) or when the webserver is running PHP as a (F) CGI, a previously set Statusheader should be set to redirect accurately.

 function Redirect($url, $code = 302) < if (strncmp('cli', PHP_SAPI, 3) !== 0) < if (headers_sent() !== true) < if (strlen(session_id()) > 0) < // if using sessions session_regenerate_id(true); // avoids session fixation attacks session_write_close(); // avoids having sessions lock other requests > if (strncmp('cgi', PHP_SAPI, 3) === 0) < header(sprintf('Status: %03u', $code), true, $code); > header('Location: ' . $url, true, preg_match('~^30[1237]$~', $code) > 0 ? $code : 302); > exit(); > > ?>

JavaScript via PHP

Here, we will provide you with an alternative method of redirection implementing JavaScript via PHP. In JavaScript, there is a windows.location object that is implemented for getting the current URL and redirecting the browser towards a new webpage. This object encompasses essential information about a page (for example, href, a hostname, and so on).

This is how to redirect a web page using window.location:

html> html> head> title>window.location function title> head> body> p id="demo"> p> script> document.getElementById("demo").innerHTML = "URL: " + window.location.href + "
"
; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + "
"
; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + "
"
;
script> body> html>

To conclude, let’s assume that in this short tutorial, we provided you with multiple methods to redirect a web page with PHP. Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.

Источник

Как в PHP реализовать переход на другую страницу?

Предположим, что вы хотите, чтобы пользователям, которые переходят на страницу https://example.com/initial.php отображалась страница https://example.com/final.php . Возникает вопрос как в PHP реализовать редирект на другую страницу?

Это можно сделать с помощью несколько методов PHP , JavaScript и HTML . В этой статье мы расскажем о каждом из методов, которые можно использовать для PHP перенаправления на другую страницу.

Вот несколько переменных, которые мы будем использовать:

Использование функции PHP header() для редиректа URL-адреса

Если хотите добавить редирект с initial.php на final.php , можно поместить на веб-странице initial.php следующий код. Он отправляет в браузер новый заголовок location :

Здесь мы используем PHP-функцию header() , чтобы создать редирект. Нужно поместить этот код перед любым HTML или текстом. Иначе вы получите сообщение об ошибке, связанной с тем, что заголовок уже отправлен. Также можно использовать буферизацию вывода, чтобы не допустить этой ошибки отправки заголовков. В следующем примере данный способ перенаправления PHP показан в действии:

Чтобы выполнить переадресацию с помощью функции header() , функция ob_start() должна быть первой в PHP-скрипте . Благодаря этому не будут возникать ошибки заголовков.

В качестве дополнительной меры можно добавить die() или exit() сразу после редиректа заголовка, чтобы остальной код веб-страницы не выполнялся. В отдельных случаях поисковые роботы или браузеры могут не обращать внимания на указание в заголовке Location . Что таит в себе потенциальные угрозы для безопасности сайта:

Чтобы прояснить ситуацию: die() или exit() не имеют отношения к редиректам. Они используются для предотвращения выполнения остальной части кода на веб-странице.

При PHP перенаправлении на страницу рекомендуется использовать абсолютные URL-адреса при указании значения заголовка Location . Но относительные URL-адреса тоже будут работать. Также можно использовать эту функцию для перенаправления пользователей на внешние сайты или веб-страницы.

Вывод кода JavaScript-редиректа с помощью функции PHP echo()

Это не является чистым PHP-решением . Тем не менее, оно также эффективно. Вы можете использовать функцию PHP echo() для вывода кода JavaScript , который будет обрабатывать редирект.

Если воспользуетесь этим решением, то не придется использовать буферизацию вывода. Что также предотвращает возникновение ошибок, связанных с отправкой заголовков.

Ниже приводится несколько примеров, в которых использованы разные методы JavaScript для редиректа с текущей страницы на другую:

self.location='https://example.com/final.php';"; echo ""; echo ""; echo ""; ?>

Единственным недостатком этого метода перенаправления на другой сайт PHP является то, что JavaScript работает на стороне клиента. А у ваших посетителей может быть отключен JavaScript .

Использование метатегов HTML для редиректа

Также можно использовать базовый HTML для выполнения редиректа. Это может показаться непрофессиональным, но это работает. И не нужно беспокоиться о том, что в браузере отключен JavaScript или ранее была отправлена ошибка заголовков:

Также можно использовать последнюю строку из предыдущего примера, чтобы автоматически обновлять страницу каждые « n » секунд. Например, следующий код будет автоматически обновлять страницу каждые 8 секунд:

Заключение

В этой статье я рассмотрел три различных метода перенаправления с index php , а также их преимущества и недостатки. Конкретный метод, который стоит использовать, зависит от задач проекта.

Источник

How to redirect a page using onclick event in php? [duplicate]

Welcome to Stack Overflow. I see that this is your first post! If answers are helpful, you can vote them up with the arrow. It is good to pick the most helpful answer and accept it with the checkmark! This will let other people with the same issue know what answer best helped you solve your issue.

4 Answers 4

You can’t use php code client-side. You need to use javascript.

However, you really shouldn’t be using inline js (like onclick here). Study about this here: https://www.google.com/search?q=Why+is+inline+js+bad%3F

Here’s a clean way of doing this: Live demo (click).

var btn = document.getElementById('myBtn'); btn.addEventListener('click', function() < document.location.href = 'some/page'; >); 

If you need to write in the location with php:

   

Why do people keep confusing php and javascript?

PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE

You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.

 window.location.href = 'http://www.google.com'; //Will take you to Google. 
 window.open('http://www.google.com'); //This will open Google in a new window. 

Источник

PHP if URL equals this then perform action

So I have a page title that is part of a Magento template; I’d like it to display 1 of 2 options, depending on what the URL is. If the URL is option 1, display headline 1. If the URL is anything else, display headline 2. This is what I came up with, but it’s making my page crash:

 

__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!') > else < echo $this->__('Create an Account') > ?>

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if($host == 'http://domain.com/customer/account/create/?student=1') 

What does «making my page crash» mean? Do you revieve an error message? Further on: Where did you define the variable $domain?

3 Answers 3

Are you looking for the URL that the page is currently on? You are using parse_url the wrong way; that is if you only want to get the host, or domain, i.e. only «dev.obtura.com». It looks like you want more than that. In addition, you are never setting the $domain variable, so parse_url() doesn’t know what to do with it. So as it is now, your if statement will always return ‘Create an account`.

Instead, set $host with $_SERVER variables:

$host = $_SERVER[‘SERVER_NAME’] . $_SERVER[‘REQUEST_URI’];

You will also need to remove the «http://» from your checking — $host will only contain everything after «http://»

As Aron Cederholm suggested, you need to add semicolons ( ; ) to the end of your echo statements.

So, your PHP code should look like this:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if($host == 'domain.com/customer/account/create/?student=1') < echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!'); > else < echo $this->__('Create an Account'); > 

Источник

Redirect after submitting the form doesn’t work [duplicate]

This contact.php form was working to handle a submit and then redirect to a new page and then all of a sudden just stopped working. I have tried adding error handling and also moving header to the top in front of all other, but neither works. The form is still submitting the data as expected, it’s just the redirect that doesn’t work. Any ideas would be appreciated.

PHP headers are the right way to do this. Javascript / Meta tags are not as reliable. Remove the echo ‘OK’; line (and any other page output generating lines) otherwise the header redirect will not work (unless you have output buffering on in the php.ini). exit() is required otherwise script execution will continue!

9 Answers 9

header('location: http://www.google.com.au/'); 
?>   

It will redirect even if something is output on your browser.

But, one precaution is to be made: Javascript redirection will redirect your page even if there is something printed on the page.

Make sure that it does not skip any logic written in PHP.

And what about a meta refresh? This would be a solution without JS, as the question is referring to PHP.

Replace the header('location: http://www.google.com.au/'); line with the below code to redirect in php without using header function.

$URL="http://yourwebsite.com/"; echo ""; echo ''; 

If you're wondering that why I have used both Meta tag and JavaScript to Redirect, then the answer is very simple.

If JavaScript is Disabled in the Browser, then meta tag will redirect the page.

Then you should place javascript before html META. Because JS can be disabled but not HTML! Isn't it?

header not working after include, echo. try again without include, echo. OR instead of function header use

function GoToNow ($url)< echo ''; >

If you want to redirect to another page after html code then use location.href javascript method.

Refer to this sample code:

       

In addition to the above answers, you can use the following JavaScript code for both the document and the main window, as well as in iframes:

  

_self Opens the linked document in the same frame as it was.

In the above command, the values of the second parameter are similar to the values of the target attribute in the tag A( ) in HTML, which can use the following values in addition to the _self value:

_blank Opens the linked document in a new window or tab

_parent Opens the linked document in the parent frame

_top Opens the linked document in the full body of the window

framename Opens the linked document in a named frame

Источник

Читайте также:  Custom comparators in java
Оцените статью