Get URL headers in PHP - php

So, let's say I'm a client entering this URL on my blog website: https://blogbyme.com/post?id=1.
I want the server to see that URL and customize the page based off what post it is.
The main question is - when the request is made, how do I grab the id header's value to send the correct blog post?
Right now I've got this far.
if (!function_exists('getallheaders')) {
function getallheaders() {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
and that's still not working.

Use the superglobal of PHP $_GET:
echo $_GET["id"];
I want the server to see that URL and customize the page based off what post it is. The main question is - when the request is made, how do I grab the id header's value to send the correct blog post?
You can get the full request URI from:
$_SERVER["REQUEST_URI"]

Related

Redirect with PHP and skip specific parameter

Since I've started using friendly URLS in my website, I'm redirecting every page to the new version, only if the registered user has a "username" in his profile.
So, I'm redirecting from:
https://tribbr.me/post.php?id=850
with:
header("Location:/".$if_username."/post/".$post_id."?".$_SERVER['QUERY_STRING']); exit();
To keep all GET parameters.... but the problem is that this header request, obviously with $_SERVER['QUERY_STRING'] is adding the post id too to the URL, and when redirected, this is the final URL:
https://tribbr.me/TribeMasters/post/850?id=850
Is it possible to just skip the id=850 parameter to the URL redirection? Since it is a duplicated parameter: post/850 and id=850 are the same.
Thanks for helping me :)
#DE_'s answer is best. But If you are not familiar with Regex, This is an alternative way.
function removeGetParam($param){
$params = $_GET;
// removing the key
unset($params[$param]);
// joining and returning the rest
return implode(',', array_map(function ($value, $key) {
return $key.'='.$value;
},$params, array_keys($params))
);
}
$filtered_params = removeGetParam('id');
header("Location:/".$if_username."/post/".$post_id."?".$filtered_params);
David Walsh did a good article on this
https://davidwalsh.name/php-remove-variable
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
return $url;
}

How to redirect to correct URL without knowing input URL

Basically how stack overflow does it.
So if the old URL is : /product-old-url_152 and then it changes to /product-new-url_152, then the following URLs would all redirect here:
/product-old-url_152
/product-some-other-url_152
would both redirect to:
/product-new-url_152
What's the best way of doing this?
EDIT: 152 is the ID of the post in the database.
One way to do this:
Extract the id from the requested URL
if (preg_match('/product-(.*)_(\d+)$/', $_SERVER['REQUEST_URI'], $matches)) {
$old = $matches[1];
$id = $matches[2];
lookup the new URL in the database
$slug = fetch_slug_from_database($id);
and send a redirect to the client, if the URL changed
if ($slug !== $old) {
header("Location: /product-$slug-$id");
exit;
}
}

Determine whether a cookie was set

Is there a straightforward way to test whether a cookie has been set during the current request? I'm writing an extension to existing code, so I can't modify the current code to add something like $_COOKIE['something'] = $someValue;. Unfortunately, only setcookie is called, without the event being logged in any other way. I need to know before the client receives the headers, because I need to set the cookie if the existing code hasn't already done so.
Have you tried using isset?
if( ! isset($_COOKIE['something'])) {
$_COOKIE['something'] == $somevalue;
}
Here's my "brute force" solution for now. I'm hoping to find a better method, though. Note that headers_list() gets the headers that are going to be sent to the browser as part of the response, not the headers that were sent by the browser during the request.
foreach (headers_list() as $header) {
list($k, $v) = explode(': ', $header, 2);
if (strtolower($k) != 'set-cookie') {
continue;
}
$name = explode('=', $v, 2)[0];
if ($name == $cookieName) {
return true;
}
}
return false;

Redirect post request to get using PHP

I need a PHP script that gets a POST request and redirects it to another page as a GET request with all parameters in the URL.
Is this possibile?
You can use the function http_build_query() to generate the GET query string from $_POST.
Afterwards attach it to the redirect URL and use header() with Location for the redirect, for example:
$newURL = 'http://example.com/script.php?' . http_build_query($_POST);
header("Location: {$newURL}");
$URL = "http://thatpage.com/thatpage.php?";
foreach($_POST as $key=>$value) {
$URL +="$key=$value&";
}
then open that $URL page
you need to parse the $_POST variable in order to create a complete GET URL
This question could help you to parse the $_POST array
PHP Parse $_POST Array?
Something like:
foreach($_POST as $k => $v)
{
$getString .= $k . '=' . $v . '&';
}
should format the POSTed variables in the proper format.

Find real link form redirect 301,302

I see some service sort link(tinyurl,goo.gl,bit.ly ...)
I use php function get_headers do get header and find real link from sort links
this is mycode
function get_furl($url)
{
$furl = false;
// First check response headers
$headers = get_headers($url);
// Test for 301 or 302
if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
{
foreach($headers as $value)
{
if(substr(strtolower($value), 0, 9) == "location:")
{
$furl = trim(substr($value, 9, strlen($value)));
}
}
}
// Set final URL
$furl = ($furl) ? $furl : $url;
return $furl;
}
But some time ,Script was got header time out.Help me code get real link faster.
Geat thanks
You can't do it any faster. Timeouts happen sometimes, and you need to take care of that.
By the way, the strlen() is unnecessary.

Categories