- Вернуться на ту страницу, с которой я пришёл
- Return to Previous Page in PHP
- Use the HTTP_REFERER Request Header to Return to the Previous Page in PHP
- Related Article — PHP Redirect
- How to get the previous page URL in PHP?
- How to get the previous page URL using PHP?
- How to spoof HTTP_REFERER?
- How to get the previous page URL after redirect in PHP?
- Leave a Comment Cancel reply
- Trending Now
- Как вернуться на предыдущую страницу без отправки данных заново (проблема возникает при нажатии кнопки назад в браузере)?
- Возврат на страницу назад
Вернуться на ту страницу, с которой я пришёл
Получить страницу, с которой пришел пользователь
Даже не знаю куда еще смотреть: необходимо узнать с какой страницы перешел пользователь. Вроде все.
Переход на web страницу, с которой пришел запрос
перехожу из одной страницы на другую с помощью метода redirect Response.Redirect("string.aspx").
Как вернуться на блок div c id, с которого пришел
Добрый день всем. Помогите пожалуйста. Есть 10 блоков у которых есть ссылка на один и тот же <div.
Как сделать redirect на url с которой пришел?
Пишу приложение на Zend Как и откуда можно вытащить предыдущую url? К примеру на сайте есть.
все действия происходят в index.php
допустим, я перешёл в меню «редактирования текста»
index.php?id=5 там я изменил текст, перешёл на index.php?id=5&st=1, после чего он должен у меня моментом вернуться index.php?id=5
через хейдер так нельзя, у меня все через пост =(
а сессии у меня и так забиты по уши
Добавлено через 1 минуту
можно как-то ведь, я минимум 2-а способа видел, не помню где, найти не магу
через SERVER[»] или в хейдере какая-то функция
header("Location: index.php?id=".$_GET['id']);
a href="#" OnClick="history.back();">Назад/a>
Добавлено через 2 минуты
хотя лучше чем никак, с этим буду рыть землю
$redicet = $_SERVER['HTTP_REFERER']; @header ("Location: $redicet");
a href="#" onclick="history.go(-1); return false;">Назад/a>
«-1» это на сколько страниц назад возвращаться.
Добавлено через 13 минут
Сообщение от Unick-legenda
Сообщение от boong
Сообщение от boong
Сообщение от boong
$redicet = $_SERVER['HTTP_REFERER']; @header ("Location: $redicet");
form action="http://full_url_with_get_vars/" method="post" name="theform"> input type="hidden" name="post1" value=" " /> input type="submit" value="Continue" /> /form> script type="text/javascript">document.theform.submit();/script>
3) Как ни странно — сессии (имхо, самое правильное решение)
4) Делаешь внутреннюю переброску на скрипт, который формирует полноценный постовый редирект:
$req="submit=true&cmd=test"; header("method: POST\r\n"); header("Host: localhost\r\n"); header("Content-Type: application/x-www-form-urlencoded\r\n"); header("Content-Length: ".strlen($req)."\r\n"); header($req."\r\n\r\n"); header("Connection: close\r\n\r\n"); header("Location: http://127.0.0.1/php_tuts/redirect/end.html\r\n");
Return to Previous Page in PHP
This article will introduce some methods to return to the previous page in PHP.
Use the HTTP_REFERER Request Header to Return to the Previous Page in PHP
The HTTP_REFERER request header returns the URL of the page from where the current page was requested in PHP. The header enables the server to acknowledge the location from where the users are visiting the current page. The header is used as the index of the $_SERVER array. We can use the header() function with the location header to redirect the current page to the previous page. We should set the location to $SERVER[‘HTTP_REFERER’] to return to the previous page.
Let’s see how the HTTP_REFERER header works. For instance, create a button in HTML. Set the action attribute to home.php and the method attribute to post . Save the file as index.php . In the home.php file, check whether the form is submitted with the isset() function. Then, use the echo function to display the $_SERVER[HTTP_REFERER] header.
form action ="home.php" method = "POST"> button type="submit" name="button"> Submitbutton> form>
if(isset($_POST['button'])) echo $_SERVER[HTTP_REFERER]; >
Here, we created the form in the index.php file. Then, the form is submitted to the home.php file. It means that the home.php page was requested from the index.php page. Therefore, the index.php page is the referrer. The output section above shows that the HTTP_REFERER returns the URL http://localhost/index.php , the referrer.
Our goal is to redirect the current page home.php to the previous page index.php .
For example, in the home.php file, create a variable $message to store the message to be displayed after the redirection occurs. Use the urlencode() to write the message in its parameter. Next, write the header() function to set the location of the redirection. Concatenate $_SERVER[HTTP_REFERER] and «?message ezoic-autoinsert-video ezoic-mid_content»>
When we click the button on the index.php page, the form gets submitted to home.php and will redirect back to the index.php page, the previous page.
In this way, we can use the header() function and the HTTP_REFERER header to return the current page to the previous page in PHP.
//index.php form action ="home.php" method = "POST"> button type="submit" name="button"> Submitbutton> form> php if(isset($_GET['message'])) echo $_GET['message']; > ?>
//home.php if(isset($_POST['button'])) $message = urlencode("After clicking the button, the form will submit to home.php. When, the page home.php loads, the previous page index.php is redirected. "); header("Location:".$_SERVER[HTTP_REFERER]."?message=".$message); die; >
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
Related Article — PHP Redirect
How to get the previous page URL in PHP?
There are many times when you need to know the previous page URL after a redirect. Maybe you’re wondering where your traffic is coming from, or if a particular campaign is driving users to your site. In any case, knowing the previous page URL is essential for understanding how users are interacting with your site.
Fortunately, it’s easy to get this information using some simple code. Keep reading to learn how!
How to get the previous page URL using PHP?
$_SERVER[‘HTTP_REFERER’] always contains the referrer or referring page URL. When you want to get the previous page’s URL, use this code:
However, you should know that someone can change the $_SERVER[‘HTTP_REFERER’] header at any time. This will not tell you if they have been to a website before.
Sometimes you may notice a warning like
Notice: Undefined index: HTTP_REFERER
Some user agents don’t set HTTP_REFERER, and others let you change HTTP_REFERER. So it’s not a reliable piece of information. So, always check if it is set or not by using isset() .
How to spoof HTTP_REFERER?
It’s very easy to spoof as well as there are many ways to grab the header from the user. This is a very common problem that I have come across in almost every single web application which requires the referer check to be enabled.
Referer spoofing is a simple process and can often be done by any individual who has little knowledge of the HTTP protocol. Let’s look at how it works:
How to get the previous page URL after redirect in PHP?
The best way to get the previous URL is with the PHP session. The value for $_SESSION[‘previous_location’] will be set as the previous page URL after a redirect.
Now set the session on your homepage like this:
You can access this session variable from any page like this:
About Ashis Biswas
A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.
Leave a Comment Cancel reply
Enjoying the articles? I would appreciate a coffee to help me keep writing and coding!
Trending Now
Как вернуться на предыдущую страницу без отправки данных заново (проблема возникает при нажатии кнопки назад в браузере)?
Как вернуться на предыдущую страницу без отправки данных заново (проблема возникает при нажатии кнопки назад в браузере)?
Вот код программы:
1) Использовать метод get в запросах для получения данных.
2) При отправке данных формы методом post делать редирект на страницу результата.
sunnyrio, а вы что, стесняетесь get параметров? это нормальный способ хранить состояние. Не хотите гет — используйте сложный роутинг.
а где проблема? Возврат на страницу куда ты отсылал данные методом пост требует отсылки данных еще раз, это не переход по ссылке, а выполнение некоторого запроса методом post, например отсылка логина и пароля, просто так браузер по таким адресам перейти не может, переход должен быть так же по методу пост, с отсылкой данных снова. Иногда это вызывает конфликт данных/ошибку или в целом не совсем безопасно. Вот и предупреждают — данные будут отосланы еще раз.
Возврат на страницу назад
При нажатии на кнопку внизу страницы выводится «Hello».
Если перейти на любую другую страницу сайта, а потом вернуться назад (кнопкой «Назад» в браузере), то выдаётся такое сообщение:
«Подтвердить повторную отправку формы
Для правильного отображения эта веб-страница требует данные, которые вы ввели ранее. Вы можете отправить данные повторно, но поступая так, вы повторяете любые действия, уже произведенные на странице. Нажмите «Перезагрузить», чтобы отправить данные повторно и отобразить страницу.»
То есть, чтобы оказаться опять на первоначальной странице, приходится её перезагружать. Как-то можно этого избежать, чтобы сразу назад переход был? Как это можно реализовать для данного примера?
Возврат на шаг назад с обновлением!
Доброго времени суток ув.программисты! такой вопрос: как осуществить возврат на предыдущую.
Как сделать РЕДИРЕКТ на страницу назад?
Я могу передать ссылку предыдущей страницы через гед запрос, но это будет как вновь открытая.
Возврат на пред. страницу
Всем доброе время суток. Суть проблемы. после авторизации пользователя он попадает на страницу.
Автоматический возврат на главную страницу
всем привет. как сделать чтобы после успешной отправки сообщение обратно вернулось на главную.
Это свойство браузера и изменить ни как. Только если создашь ссылку которая введет назад. Обычно никто не нажимает назад в браузере. Программист должен предусмотреть такую кнопку которая можно будет вернутся назад, если есть такая необходимость. Думаю я понятно объяснил.
Вместо того, чтобы плодить темы, нужно просто правильно сформировать вопрос. Что ты хочешь в итоге?
При POST запросах echo не делают. Используй GET в форме либо редирект. Если нужно что-то вывести по результату POST, то используй сессии и так называемые флеш-сообщения. Примерно так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
if (session_status() == PHP_SESSION_NONE) { session_start(); // теперь можно в массив $_SESSION писать что угодно // в пределах разумного и безопасности, конечно же } if($_SERVER['REQUEST_METHOD'] == 'POST') { // обрабатываем полученные данные $_SESSION['message'] = 'Hello!'; header('Location: ' . $_SERVER['REQUEST_URI']); exit; } if(isset($_SESSION['message'])) { $message = $_SESSION['message']; unset($_SESSION['message']); echo $message; } echo ' ';
в Location можно устанавливать любой url. если нам нужен этот же url без потери параметров, то используем REQUEST_URI, если параметры не важны, то PHP_SELF, можно просто прописать ‘Location: /’ для перехода на главную и т.д.