Php unset all post

Как удалить переменную $ _POST после нажатия кнопки «Обновить» в браузере с PHP?

Когда я нажимаю кнопку «Обновить» в моем браузере, кажется, что переменная $_POST сохраняется во время обновления. Если я хочу удалить содержимое $_POST , что мне делать? Использование unset для полей $_POST не помогло. Помощь? Спасибо!

Это проблема браузера. Старайтесь не нажимать Повторно отправить данные формы, когда ваш браузер предложит вам.

После отправки формы и прочтения данных POST, перенаправьте на другую страницу. Затем, если пользователь обновит эту страницу, данные POST не будут повторно присоединены.

@blender Я бы не сказал, что это «проблема», поскольку это функциональность всех браузеров. Сказать это так же, как сказать, что кнопка возврата — это проблема.

16 ответов

Заголовок запроса содержит некоторые данные POST. Независимо от того, что вы делаете, когда вы перезагружаете страницу, rquest будет отправлен снова.

Простым решением является перенаправление на новую (если не та же) страницу. Этот шаблон очень распространен в веб-приложениях и называется Post/Redirect/Get. Типично для всех форм делать POST, а затем в случае успеха вы должны сделать перенаправление.

Попробуйте как можно больше разделить (в разных файлах) свой вид script (html в основном) с вашего контроллера script (бизнес-логика и прочее). Таким образом, вы всегда отправляете данные отдельному контроллеру script, а затем перенаправляете обратно в представление script, которое при визуализации не будет содержать данных POST в заголовке запроса.

Читайте также:  Android java string to char

Простое решение PHP для этого:

if (isset($_POST['aaa'])) < echo '  '; > 

Когда страница перезагружается, она обновит на экране новые данные и очистит $_POST 😉

У меня был php-файл, который POST помещал в себя данные FORM, и я избегал POST после обновления, добавляя заголовок (‘Location: file.php’); в конце сценария php. Вуаля, страница обновилась сразу после POST и нет данных для повторной отправки (:

@M МХ, верно, это не очистка переменных POST . но это перезагружает страницу до такой степени, что вы можете увидеть измененный результат, получив предупреждение JavaScript, говорящее о необходимости пересылать данные поста для отображения всей страницы .

Как насчет использования $_POST = array(), который сводит на нет данные. Браузер по-прежнему будет запрашивать перезагрузку, но в суперглобале $_POST данных не будет.

Вот ссылка на аналогичный вопрос. Вы можете увидеть мой ответ. Почему POST [‘submit’] установлен при перезагрузке?

Основной ответ — посмотреть в post/redirect/get, но так как это проще увидеть на примере, просто проверьте ссылку выше.

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

 if ($_SERVER['REQUEST_METHOD'] == 'POST') < $_SESSION['postdata'] = $_POST; unset($_POST); header("Location: ".$_SERVER['PHP_SELF']); exit; >?> 

Данные POST теперь находятся в сеансе, и пользователи могут обновлять, сколько они хотят. Это не повлияет на ваш код.

@MarcoZen К файлу, который обрабатывает вашу форму. Во многих случаях тот же файл, который содержит вашу форму.

Скажем, я начинаю с формы входа, с отправки — мы перенаправляем на страницу, которая обрабатывает данные POST (в этом случае мы записываем через SESSION [postdata], а затем перенаправляем их обратно в форму входа? Да? Если учетные данные входа правильно — не должны ли они быть направлены на утвержденную страницу / домашнюю страницу. php и т. д.? Пожалуйста, поправьте меня.

unset($_POST); unset($_REQUEST); header('Location: . '); 

$_ POST должен заполняться только по запросам POST. Браузер обычно отправляет запросы GET. Если вы достигли страницы через POST, она обычно спрашивает вас, следует ли ей повторно отправлять данные POST при нажатии обновления. То, что он делает, просто то, что снова отправляет данные POST. Для PHP, который выглядит как другой запрос, хотя он семантически содержит одни и те же данные.

Да. Я заметил, что. Есть ли способ переопределить / очистить POST-запрос, отправляемый при обновлении?

Я вижу, что это старый поток, просто подумал, что я дам свои 2центы. Не уверен, что это будет соответствовать каждому сценарию, но это метод, который я успешно использовал в течение нескольких лет:

session_start(); if($_POST == $_SESSION['oldPOST']) $_POST = array(); else $_SESSION['oldPOST'] = $_POST; 

Не удаляет POST-значения из браузера, но насколько ваш php script ниже этих строк, больше нет переменных POST.

«Лучший» способ сделать это — Post/Redirect/Get

После отправки сообщения заголовок 302, указывающий на страницу успеха

У меня есть одна форма и отображение, где я «добавляю/удаляю/редактирую/вставляю/перемещаю» записи данных с помощью одной формы и одной кнопки отправки. Первое, что я делаю, это проверить, установлен ли $_post, если нет, установить его в никуда. затем я пробегаю остальную часть кода,

то на фактическом $_post Я использую переключатели и if/else на основе введенных данных и с проверкой ошибок для каждой части данных, необходимой для использования какой-либо функции.

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

Итак, вам просто нужно логически мыслить и сделать это идиотом для своих пользователей.

Задайте промежуточную страницу, на которой переменные $_POST изменяются в $_SESSION. На вашей фактической странице отключите их после использования.

Вы также можете передать URL-адрес начальной страницы, чтобы установить кнопку возврата назад.

Источник

Using unset for $_POST

My code has multiple $_POST variables. I like to clean things up and unset them after everything has been executed.

I don’t want to have to list each $_POST out individually. Is there a good way of unset all $_post values at once. I don’t want to unset my $_SESSIONS or other variables. Just the Post ones.

Any helpful hints is very much appreciated.

I tried using unset($_POST); — but it does not unset the values. Thanks

It is as simple as it gets. Try this:

PHP Tryit Editor v1.2, The value of variable ‘a’ before unset: Hello world! The value of variable ‘a’ after unset:

Unset session after sometime [How to Delete Data After Some Time]

i have a Simple Chat script of php it has no database it work fine. but it create and store all chats in a file msg.html i want to delete these chats after some time. How to delete these chats after some time about 30min.

 else < $f = fopen('msg.html',"w+"); >$nick = isset($_GET['nick']) ? $_GET['nick'] : "Hidden"; $msg = isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : "."; $line = "

else if (isset($_GET['all'])) < $flag = file('msg.html'); $content = ""; foreach ($flag as $value) < $content .= $value; >echo $content; > ?>

The best solution is to use a cron . You can execute a cleanup PHP script every X minutes, like so:

0,30 * * * * /path/to/php /path/to/cleanup_script.php

If you want to empty the file, that’s easy — you can just use file_put_contents($file, »);

If you want to delete specific messages you’ll need to add a timestamp to the start of each line (You can remove it when you output the chat) and parse it in your cleanup script.

You can obtain the path to php by running which php on your command line.

PHP unset() function, PHP unset () function. The unset () function is a predefined variable handling function of PHP, which is used to unset a specified variable. In other words, «the unset () function destroys the variables». The behavior of this function varies inside the user-defined function. If a global variable is unset inside a function, the unset …

Removing POST data so back button won’t display Document Expired

When my page does a post, I store all the $_POST data in a separate $_SESSION var. I know that a back button to this same page is by design to show the Document Expired message. My hope is to fool the browser into thinking that there was really never any $_POST data and so not to display the Document Expired message when coming back to it. I am forcing a complete refresh of the page so I am not worried about receiving old data, since I have it stored in the session.

I have tried to unset($_POST) hoping this will stay with the page. but the $_POST data must be cached / stored and returns with a refresh or back button. Is what I am trying to do possible? Any ideas?

* UPDATE * My solution / answer is posted below. It posts to a separate form, which redirects back to the original form for processing. Not sure why the down vote. It has been working great for months and I no longer receive Document expired messages. It also prevents duplicate posting.

You can achieve this using the post — redirect — get design pattern.
http://en.wikipedia.org/wiki/Post/Redirect/Get

A more standard way to implement this pattern is to display, validate and save the form on one page.

The following solution has these advantages :
1. All form related code is in one place. 2. Server side validation is simple

I have two pages, form.php and after.php.

if(isPosted()) < if(dataIsValid($postedData))< // dataIsValid should set $message to show to the user saveData($postedData); redirect('after.php'); die(); >> else < $postedData = $defaultValues; >showForm($postedData, $message); 

You can add the following to the beginning of your script to solve this issue.

header("Cache-Control: max-age=300, must-revalidate"); 

Simplest solution that comes to mind? Don’t directly do the post, catch the event and submit the form through AJAX. Then on success, redirect.

$('#some_form').submit(function() < $.post($(this).attr('action'), $(this).serialize(), function() < window.location = "/some/success/url.php"; >); return false; // Prevent the form submission & any other events triggered on submit >); 

Because the POST never got added to the browser history, you won’t have that issue.

However , note that the POST url is now different than the one you load; you can make it the same by checking whether a POST or a GET was done server-side, but either way, you have to do a bit of extra work to «remember» the results of the POST.

* UPDATE * Here’s my solution.

I am aware that with post-redirect-get the POST is usually back to the same page for processing before being redirected away from the form with a GET to another destination. However, I need to be able to return to the original page for re-editing (as in a document model where the user can SAVE work in progress). Therefore doing the POST to a second page and redirecting back to the original was my idea of getting rid of the «EXPIRED» message since the editing form would not have post data associated with it. I have extended this (not shown) to include $_FILE and other situations (e.g. using it with a href as well). Not sure why the downvote. This has been working great for months now and accomplishes the task. I no longer receive «Document Expired» messages. In addition, all $_POST processing is accomplished in the original file.

0) < // process get var_dump($_GET); >if (isset($_SESSION['post-copy'])) < // return post vars to $_POST variable so can process as normal $_POST = $_SESSION['post-copy']; // unset the session var - with refresh can't double process unset($_SESSION['post-copy']); // process post vars var_dump($_POST); >?> &help=me' enctype='multipart/form-data'> 
 if (isset($_POST)) < $_SESSION['post-copy'] = $_POST; >// retrieve the url to return to if (isset($_GET['redirect'])) < $url = $_GET['redirect']; >// if multiple query string parameters passed in get, isolate the redirect so can build querystring with the rest if (isset($_GET) && count($_GET) > 1) < $get = $_GET; foreach ($get as $key =>$val) < if ($key == 'redirect')< // remove from rest of passed get query string unset($get[$key]); >> if (count($get) > 0) < $url .= (strpos($url,"?")===false ? "?" : "&") . http_build_query($get); >> if ($url!=="") < header("Location: " . $url); >?> 

PHP unset() function, PHP: Tips of the Day. Get first key in a (possibly) associative array? Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key:

How can set post value and unset it by observer magento 2

I want to get data by current url so i have set post value, please see my code

if (currenturl = 'https://example.com/delhi.html') < $this->request->setPostValue('location','289'); > 

But it set for all pages, i want to unset it if another url open. Please anyone idea for that

$this->request->setPostValue('location',''); if (currenturl = 'https://example.com/delhi.html') < $this->request->setPostValue('location','289'); > 

Php — Removing POST data so back button won’t display, When my page does a post, I store all the $_POST data in a separate $_SESSION var. I know that a back button to this same page is by design to show the Document Expired message. My hope is to fool the browser into thinking that there was really never any $_POST data and so not to display the Document …

Источник

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