Php header redirect get

How to get the headers from the last redirect with PHP’s curl functions?

If I execute a cURL request that is set to follow redirects and return the headers, it returns the headers for ALL of the redirects. I only want the last header returned (and the content body). How do I achieve that?

4 Answers 4

$url = 'http://google.com'; $opts = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HEADER => true); $ch = curl_init($url); curl_setopt_array($ch, $opts); $response = curl_exec($ch); $redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $response = explode("\r\n\r\n", $response, $redirect_count + 2); $last_header = $response[$redirect_count]; if ($status == '200') < $body = end($response); >else < $body = ''; >curl_close($ch); echo '
'; echo 'Redirects: ' . $redirect_count . '
'; echo 'Status: ' . $status . '
'; echo 'Last response header:
' . $last_header . '
'; echo 'Response body:
' . htmlspecialchars($body) . '
'; echo '

';

Of course, you’ll need more error checking, such as for timeout, etc.

@George Edison — That’ll work, I’m sure, but with the code I posted you keep all the headers plus the content in one neat array.

@m1tk4 — After re-reading, I see what you’re getting at. I don’t believe (but don’t know for sure) that any webserver will send a body with a redirect response (tested with IIS and Apache only). Otherwise it’s something that would need to be checked for in actual, non-demo, code.

Источник

PHP, How to Redirect/Forward HTTP Request with header and body?

I have a PHP page, main.php which is on server 1. I have a PHP page main.php (same page, different code) on server 2. main.php is a WebService. I would like to forward the full HTTP request made to server 1, to server 2, so that when a user sends an HTTP request to main.php (server 1), it would get the response from main.php on server 2. I would like the request made to server 2 to be exactly like the original request to server 1. I take the Http Request data via:

$some_param = $_REQUEST['param'] $body =file_get_contents('php://input'); 
$server1_url = "11111"; $server2_url = "22222"; 

The motivation for this is, i have a production server and a staging server, i would like to direct some traffic to the new server to test the new functionality on the staging server. How do i redirect the request with all the data or «cloning» the full request, sending it to the new server and returning the new response? Thanks for your help! p.s i tried using php curl, but i dont understand how it works, also i found all kinds of answers, but none forward the Requests params and the body. Again thanks!

what does proxy have anything to do with this? also i dont see any applicable answer on the question you quoted, do you? thanks.

3 Answers 3

If you have access to the Apache server config you can create a virtualhost with the following settings:

ProxyPreserveHost Off ProxyPass / http://remotesite.domain.tld/ ProxyPassReverse / http://remotesite.domain.tld/ ProxyPassReverseCookieDomain remotesite.domain.tld proxysite.tld 

You’ll need to enable mod_proxy and mod_proxy_http for this. Substitute remotesite.domain.tld to the site you forward to, and proxysite.tld to the forwarder.

If you don’t have access to the server config files, you can still do in php, by manually setting up curl and forward everything.

 curl_setopt($ch, CURLOPT_URL, $site . $request); curl_setopt($ch, CURLOPT_HEADER, TRUE); $headers = getallheaders(); /* Translate some headers to make the remote party think we actually browsing that site. */ $extraHeaders = array(); if (isset($headers['Referer'])) < $extraHeaders[] = 'Referer: '. str_replace($proxyDomain, $remoteDomain, $headers['Referer']); >if (isset($headers['Origin'])) < $extraHeaders[] = 'Origin: '. str_replace($proxyDomain, $remoteDomain, $headers['Origin']); >/* Forward cookie as it came. */ curl_setopt($ch, CURLOPT_HTTPHEADER, $extraHeaders); if (isset($headers['Cookie'])) < curl_setopt($ch, CURLOPT_COOKIE, $headers['Cookie']); >curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); if ($logHeaders) < $f = fopen("headers.txt", "a"); curl_setopt($ch, CURLOPT_VERBOSE, TRUE); curl_setopt($ch, CURLOPT_STDERR, $f); >curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $response = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $header_size); $body = substr($response, $header_size); $headerArray = explode(PHP_EOL, $headers); /* Process response headers. */ foreach($headerArray as $header) < $colonPos = strpos($header, ':'); if ($colonPos !== FALSE) < $headerName = substr($header, 0, $colonPos); /* Ignore content headers, let the webserver decide how to deal with the content. */ if (trim($headerName) == 'Content-Encoding') continue; if (trim($headerName) == 'Content-Length') continue; if (trim($headerName) == 'Transfer-Encoding') continue; if (trim($headerName) == 'Location') continue; /* -- */ /* Change cookie domain for the proxy */ if (trim($headerName) == 'Set-Cookie') < $header = str_replace('domain='.$remoteDomain, 'domain='.$proxyDomain, $header); >/* -- */ > header($header, FALSE); > echo $body; if ($logHeaders) < fclose($f); >curl_close($ch); ?> 

And of course the script must be in the root directory of a (sub)domain. And you should have a .htaccess that rewrites everything to it:

RewriteEngine On RewriteRule .* index.php 

This does not work for me. The script forwards to the $site, instead of keeping the proxy domain in the URL.

The script works very well. Just one thing if it helps someone. The original server was redirecting page to another, lets say from http to https. As script sets headers for content after fetching via curl, I had to add one more line to avoid redirect loop. if (trim($headerName) == ‘Location’) continue; Please check if you can update the answer. Thanks.

One more thing, to get data from another server even if it redirects, I had to use curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); to get data and display.

I tried to forward an xmlrpc GET request to an old joomla 1.5 site, that supports xmlrpc. However, despite the suggested code completes successfully (i.e. I see 200 OK in headers.txt), the response is: XML error: Invalid document end at line 1, column 1. I will appreciate any input/ideas on how to resolve the error.

this is the solution i have found (there might be better)

 public static function getResponse ($url,$headers,$body)

I have used the code by Rehmat and Calmarius and made a few changes so now it handles multiple fields with same name like

and to upload files too, including multiple files that use the same field name.

sanitizePostFields($_POST); $files = $this->sanitizeFiles($_FILES); if ($files) < $post = array_merge($post, $files); >curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); /* // this is enough if not uploading files curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($_POST) ); */ > curl_setopt($ch, CURLOPT_URL, $this->site . $request); curl_setopt($ch, CURLOPT_HEADER, TRUE); $headers = getallheaders(); /* Translate some headers to make the remote party think we actually browsing that site. */ $extraHeaders = array(); if (isset($headers['Referer'])) < $extraHeaders[] = 'Referer: '. str_replace( $this->proxyDomain, $this->remoteDomain, $headers['Referer'] ); > if (isset($headers['Origin'])) < $extraHeaders[] = 'Origin: '. str_replace( $this->proxyDomain, $this->remoteDomain, $headers['Origin'] ); > /* Forward cookie as it came. */ curl_setopt($ch, CURLOPT_HTTPHEADER, $extraHeaders); if (isset($headers['Cookie'])) < curl_setopt($ch, CURLOPT_COOKIE, $headers['Cookie']); >curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); if ($this->logHeaders) < $f = fopen("headers.txt", "a"); curl_setopt($ch, CURLOPT_VERBOSE, TRUE); curl_setopt($ch, CURLOPT_STDERR, $f); >//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $response = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $header_size); $body = substr($response, $header_size); $headerArray = explode(PHP_EOL, $headers); /* Process response headers. */ foreach($headerArray as $header) < $colonPos = strpos($header, ':'); if ($colonPos !== FALSE) < $headerName = substr($header, 0, $colonPos); /* Ignore content headers, let the webserver decide how to deal with the content. */ if (trim($headerName) == 'Content-Encoding') continue; if (trim($headerName) == 'Content-Length') continue; if (trim($headerName) == 'Transfer-Encoding') continue; //if (trim($headerName) == 'Location') continue; /* -- */ /* Change cookie domain for the proxy */ if (trim($headerName) == 'Set-Cookie') < $header = str_replace( 'domain='.$this->remoteDomain, 'domain='.$this->proxyDomain, $header ); > /* -- */ if (trim($headerName) == 'Location') < $header = str_replace( $this->remoteDomain, $this->proxyDomain, $header ); > > header($header, FALSE); > echo $body; if ($this->logHeaders) < fclose($f); >curl_close($ch); > private function sanitizePostFields($post, $fieldName = '') < if (empty($post)) < return false; >if (!is_array($post)) < return false; >$result = []; foreach ($post as $k => $v) < if (is_string($v)) < $result[($fieldName ? "[]" : $k)] = $v; > elseif (is_array($v)) < $result = array_merge( $result, $this->sanitizePostFields($v, $k) ); > > return $result; > private function sanitizeFiles($files) < if (empty($files)) < return false; >if (!is_array($files)) < return false; >$result = []; foreach ($files as $k => $v) < if (empty($v['name'])) < continue; >if (is_array($v['name'])) < // more than one file using the same name field[] $nFields = count($v['name']); for ($i = 0; $i < $nFields; $i++) < if (empty($v['tmp_name'][$i])) < continue; >$curl_file_upload = new CURLFile( $v['tmp_name'][$i], $v['type'][$i], $v['name'][$i] ); $result["[]"] = $curl_file_upload; > > else < $curl_file_upload = new CURLFile( $v['tmp_name'], $v['type'], $v['name'] ); $result[$k] = $curl_file_upload; >> return $result; > > $proxy = new proxy(); 

Источник

php redirect – How to, Examples, Issues & Solutions

php redirect is a convenient way to redirect https requests to another page. Learn about correct syntax, response code , common errors using session data and time delayed redirection.

php redirect to another page on same or different website is handled by php headers. php header() sends a raw HTTP header which is used to redirect php pages to other locations along with several other function

php header syntax :

header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void

header is the header string which is ‘Location:’ for php redirect and it sends headers back to browser.

replace parameter is TRUE by default, but can be FALSE if you want to send multiple headers and don’t want to replace send header with first.

response code – default response code is 302,

browsers and search engines treat these response code differently, search engines take a 301 as permanent move to new page and update page rank, this can help in maintaining same search ranking for the page. Browsers use 30x code to determine how long or what to cache for these pages. It makes sense to specify the status code explicitly for php redirects depending on the requirements.

Setting up php redirect header

A php header redirect can be setup as in following example with default parameters.

or by specifying custom parameters

header(“Location: http://example.com”,TRUE,301);
exit;
?>

The url can be relative to the root domain if it is being redirected to same site

the exit function after the redirect is to ensure the further execution of php script stops and exists.

Relative urls in php redirect

The redirect urls can be constructed using php environment variables as in following example:

$url = ‘http://’ . $_SERVER[‘HTTP_HOST’]; // Get server
$url .= rtrim(dirname($_SERVER[‘PHP_SELF’]), ‘/\\’); // Get current directory
$url .= ‘/relative/path/to/page/’; // relative path
header(‘Location: ‘ . $url, TRUE, 302);

php redirect using session data

session data can be used to redirect based on valid user credentials. However care needs to be taken that search bots and other bots may not looks at the session data and may end up fetching your pages.

if (!isset( $_SESSION[“authorized-user”]))
header(“location. /”);
exit();
>

Header already sent error in php redirect

This is very common error and sometime difficult to debug. The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error.

Like following example, there should not be any output of even a space before the headers are sent.

Even a Byte Order Mark can cause this issue when the text encoding is utf8-BOM, this can be fixed by saving again with encoding as utf8 without BOM in text editors.

Internal server error in php redirect

The directive Location is sensitive to the placement of colon, The colon : should always be placed next to Location as Location: , any space between Location and : can result in malfunction and internal server error.

This is NOT correct, notice the placement of colon,

Correct way is :

Replace php redirect header

the headers can be replaced with another entry as long as nothing is sent to browsers

header(“location: page1.php”);
header(“location: page2.php”); //replaces page1.php
exit;
?>

In the following example, headers are not replaced as browser follows the first redirect and then prints the message. No header already sent message here as browser has already redirected before coming to second redirect.

header(“location: page1.php”);
echo “moving to page 2”
header(“location: page2.php”); //replaces page1.php
?>

php redirect with time delay

As you can’t send anything before php headers, to delay a redirect and display a message, you will have to user refresh function instead of Location

The following examples redirects to page after 5 seconds and displays a message during the 5 sec. delay.

Redirecting using other methods

following examples avoid headers already sent issues.

1. php redirect using ob_start() and ob_end_flush() php functions

ob_start(), output buffer keeps everything in buffer without sending or displaying until it is flushed

ob_start(); //this has to be the first line of your page
header(‘Location: page2.php’);
ob_end_flush(); //this has to be the last line of your page
?>

2. Redirect using javascript

This simple example does the redirection using javascript.

Источник

Читайте также:  Функция фильтр в питоне
Оцените статью