Php перенаправить все post

PHP – перенаправление и отправка данных через POST

Как говорили другие, вы можете использовать cURL, но тогда PHP-код становится клиентом, а не браузером.

Если вы должны использовать POST, тогда единственный способ сделать это – создать заполненную форму с помощью PHP и использовать hook.onload для вызова javascript для отправки формы.

вот пример обходного пути.

function redirect_post($url, array $data) < ?>   function closethisasap() 
$v) < echo ''; > > ?>

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

сохранить сообщение и сделать временную переадресацию:

function post_redirect($url)

Затем всегда проверяйте переменную post_data :

if (isset($_SESSION['post_data'])) с if (isset($_SESSION['post_data']))

Там будут некоторые отсутствующие компоненты, такие как apache_request_headers () не будут отображать заголовок содержимого POST и т. Д.

Он будет включать расширение cURL PHP.

$ch = curl_init('http://www.provider.com/process.jsp'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John"); curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL $resp = curl_exec($ch); 
/** * Redirect with POST data. * * @param string $url URL. * @param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123) * @param array $headers Optional. Extra headers to send. */ public function redirect_post($url, array $data, array $headers = null) < $params = array( 'http' =>array( 'method' => 'POST', 'content' => http_build_query($data) ) ); if (!is_null($headers)) < $params['http']['header'] = ''; foreach ($headers as $k =>$v) < $params['http']['header'] .= "$k: $v\n"; >> $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if ($fp) < echo @stream_get_contents($fp); die(); >else < // Error throw new Exception("Error loading '$url', $php_errormsg"); >> 

Обратите внимание, что вы также можете использовать массив для параметра CURLOPT_POSTFIELDS. Из документов php.net:

Полные данные для отправки в HTTP-режиме «POST». Чтобы опубликовать файл, добавьте имя файла с помощью @ и используйте полный путь. Это может быть либо передано как строка с urlencoded, как «para1 = val1 & para2 = val2 & …», или как массив с именем поля в качестве ключа и данных поля как значение. Если значением является массив, заголовок Content-Type будет установлен в multipart / form-data.

Альтернативно, установка переменной сеанса перед перенаправлением и проверка ее в целевом URL-адресе может решить эту проблему для меня.

Вы должны открыть сокет на сайт с помощью fsockopen и смоделировать HTTP-Post-Request. Google покажет вам множество фрагментов, как имитировать запрос.

Я боюсь, что вам понадобится CURL для этой задачи. Хороший простой способ сделать это здесь: http://davidwalsh.name/execute-http-post-php-curl

Я использовал следующий код для сбора данных POST, который был отправлен из form.php, а затем связал его с URL-адресом, чтобы отправить его BACK в форму для исправлений валидации. Работает как шарм и фактически преобразует данные POST в данные GET.

Старый пост, но вот как я справился с этим. Используя метод newms87:

if($action == "redemption") < if($redemptionId != "") < $results = json_decode($rewards->redeemPoints($redemptionId)); if($results->success == true) < $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete'; // put results in session and redirect back to same page passing an action paraameter $_SESSION['post_data'] = json_encode($results); header("Location:" . $redirectLocation); exit(); >> > elseif($action == "redemptionComplete") < // if data is in session pull it and unset it. if(isset($_SESSION['post_data'])) < $results = json_decode($_SESSION['post_data']); unset($_SESSION['post_data']); >// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page. else < $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml'; header("Location:" . $redirectLocation); >> с if($action == "redemption") < if($redemptionId != "") < $results = json_decode($rewards->redeemPoints($redemptionId)); if($results->success == true) < $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete'; // put results in session and redirect back to same page passing an action paraameter $_SESSION['post_data'] = json_encode($results); header("Location:" . $redirectLocation); exit(); >> > elseif($action == "redemptionComplete") < // if data is in session pull it and unset it. if(isset($_SESSION['post_data'])) < $results = json_decode($_SESSION['post_data']); unset($_SESSION['post_data']); >// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page. else < $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml'; header("Location:" . $redirectLocation); >> 

Да, вы можете сделать это на PHP, например, в

$postParams = array( 'email' => $request->get('email'), 'agree_terms' => $request->get('agree_terms'), ); $subRequest = Request::create('/register', 'POST', $postParams); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false); 

Обходной путь, который отлично работает:

На исходной странице начните открытие сеанса и назначьте столько значений, сколько захотите. Затем выполните перемещение с помощью «заголовка»:

И затем, на большой странице:

Нет необходимости в Javascript или JQuery. Удачи!

  • Предупреждение «Excel нашел нечитаемый контент» при открытии файлов Excel, сделанных с помощью PHPExcel
  • Загрузка изображений с использованием php, но без обновления страницы
  • Uploadify: определение максимальной ширины и высоты изображения
  • значение радио кнопки в php
  • регулярное выражение для получения подстроки через php
  • Любой способ идентифицировать обновление F5 в PHP?
  • Условная помощь PHP
  • XML как хранилище для API / Сохранение данных из формы в XML-файле
  • Результаты поиска Google с помощью php
  • Удержание захвата или атаки?
  • Как получить имя действия в контроллере Symfony2?
  • Хранение арабских слов с использованием Apache Solr 3.6.1
  • Получение переменной GET «?» В laravel
  • Рекурсивный поиск массивов PHP
  • Javascript Преобразование PHP Json в массив javascript

Источник

Редирект после POST запроса

Каждый веб-разработчик знает, что после POST сабмита формы желательно сделать редирект, чтобы предотвратить повторную отправку данных, когда пользователь захочет обновить страницу. В основном это критически необходимая операция, так как данные формы могут сохраняться в базе данных или участвовать в платёжной транзакции. И тогда данные не только продублируются, но и спишутся лишние деньги.

Но речь не о деньгах, а о правильном редиректе…

Практически все веб-приложения при редиректе POST запроса возвращают статус 302 Found. Например, в php редирект делают так: header(‘Location: /new/location’);. Без дополнительных параметров или если отдельно не указан другой статус, функция вернёт именно 302 Found.

Теперь обратимся в официальным документам. В RFC 2616 сказано следующее:
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Если статус 302 получен в ответ на запрос отличный от GET или HEAD, юзер-агент НЕ ДОЛЖЕН автоматически редиректить запрос до тех пор, пока он не будет подтверждён пользователем, так как это может нарушить условия запроса.

Там же в заметках написано, что несмотря на это, многие юзер-агенты пренебрегают этим правилом и интерпретируют 302 статус как 303. А пошло это ещё со времён HTTP/1.0, в котором 303 статуса ещё не было.

Т.е. для редиректа POST запроса нужно использовать статус 303 See Other, который специально для этого и предназначен. В php редирект будет выглядеть, например, так: header(‘Location: /new/location’, true, 303);

В RFC в заметке к статусу 303 написано:
Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303

Многие пре-HTTP/1.1 юзер-агенты не понимают 303 статус. Если совместимость с такими клиентами важна, то вместо него можно использовать 302 статус, так как большинство таких агентов реагируют на 302 статус также как на 303.

И получается два варианта:
1. По прежнему использовать 302;
a. есть вероятность нарваться на юзер-агента, который чтит спецификацию и выдаст предупрежление.
б. так как такое поведение не стандартно, можно нарваться на вообще непредсказуемый результат.

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

Во втором случае, можно анализировать версию протокола, запрошенную клиентом, и выдавать 302 для старых клиентов. В теле ответа писать ссылку на новый УРЛ. Тогда пользователь старого агента, сможет хотя бы кликнуть на ссылку.

Источник

PHP – Redirecting a form with POST variables.

On more than one occasion, I’ve come across novice PHP developers looking for ways to redirect the user and their submitted form variables to an external website.

More often than not, they’ll ask if they can somehow attach POST variables to a header redirect.

After this fails and they finally realize that another solution is needed, they’ll usually attempt to use an HTTP library such as cURL.

Unfortunately, cURL will not help in this case.

Hold up!

If the site in question has an API, then you should definitely access that instead of playing around with redirects.

If they do have an API, then you should be able to interact with it using cURL.

The solutions below are for websites that willingly accept POST data from users that are entering their site for the first time. For example, PayPal and some of the other online merchants.

If the site does not officially accept such requests and you’re trying to glue all of this functionality together, then don’t be surprised to find out that your application suddenly breaks overnight because a form field was renamed or they added a captcha.

If the site currently requires a captcha before the form submission is accepted, then you will be out of luck. That is a completely different “issue” that is not covered here.

cURL.

In this case, the problem with cURL is that the request is sent via the server.

In other words, the request will not come from the user’s browser.

Therefore, the user’s browser and the external website will be completely oblivious to one another.

As far as they’re concerned, they’ve never met each other before. This is because cURL is acting as a middleman between the user and the external website.

It grabs the data from the user before forwarding it on. This means that if you forward the POST data via cURL, the website in question will fail to recognize it as a request from your user.

This can be a major issue if your user needs to carry out further actions after the form is submitted.

For example, if the user needs to enter their credit card details or click on a confirmation button, then using cURL is going to be cumbersome at best.

If the site relies on JavaScript or some other form of client-side processing, then using cURL is going to become even more complicated as cURL cannot process JavaScript or interact with browser plugins.

“I don’t really care about redirecting the user. I just want to forward the POST data.”

If you’re OK with not redirecting the user to the website in question, then a once-off cURL request might be the perfect solution for you.

If the site accepts and accommodates POST requests without forcing the user to jump through hoops, then you could forward the data on like so:

//The names of the POST variables that we want to send //to the external website. $postVars = array('name', 'email', 'dob'); //An array to hold the data that we'll end up sending. //Empty by default. $postData = array(); //Attemp to find the POST variables that we want to send. foreach($postVars as $name) < if(isset($_POST[$name]))< $postData[$name] = $_POST[$name]; >> //Setup cURL $ch = curl_init(); //The site we'll be sending the POST data to. curl_setopt($ch, CURLOPT_URL, "http://example.com"); //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our POST data. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); //Tell cURL that we want to receive the response that the site //gives us after it receives our request. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Finally, send the request. $response = curl_exec($ch); //Close the cURL session curl_close($ch); //Do whatever you want to do with the output. echo $response;

You can then parse the $response variable and inform the user whether they were successful or not.

I need to make sure that the user is redirected.

In certain cases, you will need to redirect the user to the site in question.

With online merchants such as PayPal, this is a must as the user will be prompted to enter their payment details once they’ve landed on the site.

If you don’t need to process the form data before it is sent, then simply adding the external site’s URL to your form’s action attribute should do the trick:

The benefit of this is that you don’t even need to redirect the user. They just submit the form and the data goes directly to the site that is waiting to accept it.

I need to process the form data before the user leaves.

If you need to process the form data before the user leaves your website, then you will need to take the following steps:

  1. Process the user’s form submission.
  2. Bring the user to another page that has an “invisible form”. This “form” should be created using hidden fields. The fields should contain data from the form that they previously submitted.
  3. Automatically submit the “invisible form” using JavaScript. That or you can prompt the user to submit it again by asking them to confirm their details.

The “invisible form” might look something like this:

 
"> "> ">

The problem with the code above is that the user needs to have JavaScript enabled for it to work. As a fail-safe, you could add a visible submit button to the form. One that says something such as “Click here if the site is taking too long to redirect!” or “Confirm Submission”:

  "> "> ">  

Источник

Читайте также:  Rectangle example
Оцените статью