Redirection HTTP/1.1 301 Moved Permanently - php

I have the following files. The objective of this is to redirect to the correct news. For example:
localhost/tostadotv/esto-es-una-noticia-28.html
If I intentionally modify the url, for example:
localhost/tostadotv/esto-es-una-noticia-modificada-incorrecta-28.html
I should redirect myself to the correct news:
localhost/tostadotv/esto-es-una-noticia-28.html
However, it redirects me to this:
http://localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/esto-es-una-noticia-28.html
Where this error? Could you please help me thanks. Excuse my english I'm from Argentina I do not speak English
.htaccess
RewriteEngine On
RewriteRule ^.*-([0-9]+)\.html$ noticia.php?id_not=$1 [L]
noticia.php
<?php require_once("lib/connection.php"); ?>
<?php require_once("lib/functions.php"); ?>
<?php
fix_category_product_url();
?>
functions.php
function fix_category_product_url() {
$proper_url = get_proper_category_product_url(1);
if ( SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function get_proper_category_product_url($id) {
$product_id = $_GET['id_not'];
$query = sprintf('SELECT titulo FROM noticias WHERE id_not = "%d"', mysqli_real_escape_string($GLOBALS['DB'], $product_id));
$restit = mysqli_query($GLOBALS['DB'], $query);
$noticia = mysqli_fetch_array($restit);
$proper_url = make_category_product_url($noticia['titulo'], $product_id, $id);
return $proper_url;
}
define('SITE_DOMAIN', 'localhost');
function _prepare_url_text($string) {
$NOT_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = iconv('UTF-8','ASCII//TRANSLIT',$string);
$string = preg_replace($NOT_acceptable_characters_regex, '', $string);
$string = trim($string);
$string = preg_replace('#[-_ ]+#', '-', $string);
return $string;
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if ($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}

As said in the comments, the final solution for the asker was to add http:// to the defined SITE_DOMAIN constant.
Before
define('SITE_DOMAIN', 'localhost');
After
define('SITE_DOMAIN', 'http://localhost');
But there's more to it than just that. Let's focus on the following two functions:
function fix_category_product_url(){
$proper_url = get_proper_category_product_url(1);
if(SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url){
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}
The idea here is that $proper_url actually ends up getting a value from make_category_product_url() because its result is returned by get_proper_category_product_url(). It makes sense because make_category_product_url() has more parameters and uses the other to get their values.
What's funny about this is that the else block of the second function doesn't always return a path, but rather a URL. The problem here is that such URL is given without a defined protocol, but starts with the domain name instead. This value is therefore mistaken as a path.
Now take a look at the first function: it ultimately redirects the user using header('Location: '.$proper_url);. As we discussed earlier, $proper_url is not always a path, so the protocol should be added somewhere in the code whenever a URL takes place instead of a path. That's where the actual solution comes in: adding http:// where SITE_DOMAIN is defined is one way to do this, because this constant is only used when a URL takes place. There are many other ways to do this, but this one is completely valid.

Related

how to php only allow only special parameter in url or redirect to other

I need help to write function which help me clean out any unusual ( not allow in array list) then redirect to right url
eg my original is /modules.php?aaa=111&bbb=2
the var aaa and bbb is alow using on urls ,
if some one ads other var to url incase you mess up or want to overhead the server they will redirect back to original one.. but cut all invalid param out.
eg: /modules.php?aaa=111&notgood=999&bbb=2
will redirect back to
modules.php?aaa=111&bbb=2
the &notgood=999 or any other will be strip out..
$goodvar = array("aaa","bbb");
$requesturi = $_SERVER['REQUEST_URI'];
if /// Need help : if other query not in the list of good var will be clean out of requesturi to build NEWrequesturi
{
header("Location: ".$NEWrequesturi,TRUE,301); exit; die();
}
thanks very much
kind regards
<?php
$good_var = ["aaa", "bbb"];
$query_params = explode(".php?", $_SERVER['REQUEST_URI'])[1];
$all_query_data = explode("&", $query_params);
$data_set = [];
foreach ($all_query_data as $query_value) {
$param = explode("=", $query_value);
$data_set[$param[0]] = $param[1];
}
$paased_args = array_keys($data_set);
if (empty(array_diff($paased_args, $good_var))) {
echo "Url is good";
// do whatever you want when url is good
} else {
echo "Url tempered";
//url has been tempered do as you wish
}

Server request uri page and related pages

I'm nearly done with finding a way to show a .html file on certain pages only.
In this case i want test.html to be shown on http://www.example.com/categories/AnyPageThatExcistsInCategories
I figured out the following code works on /categories.
<?php if ($_SERVER['REQUEST_URI'] == '/categories/') { include 'test.html';} ?>
I only need the golden tip on how to get it also working on pages like /categories/ThisCanBeAnything and categories/ThisCanBeAnything/AndThisAlso etc etc
server config is nginx.
thank you
You could see if the request uri begins with the string '/categories/':
<?php
$request_uri = '/categories/foo';
if (strpos($request_uri, '/categories/') === 0 )
{
include 'your.html';
}
Substitute the value of $request_uri above with $_SERVER['request_uri']. Under the assumption that you have this logic in a front controller.
Further:
<?php
$request_uris = [
'/categories/foo',
'/categories/',
'/categories',
'/bar'
];
function is_category_path($request_uri) {
$match = false;
if (strpos($request_uri, '/categories/') === 0 )
{
$match = true;
}
return $match;
}
foreach ($request_uris as $request_uri) {
printf(
"%s does%s match a category path.\n",
$request_uri,
is_category_path($request_uri) ? '' : ' not'
);
}
Output:
/categories/foo does match a category path.
/categories/ does match a category path.
/categories does not match a category path.
/bar does not match a category path.
In use:
if(is_category_path($_SERVER['REQUEST_URI'])) {
include 'your.html';
exit;
}
You may want to not match the exact string '/categories/', if so you could adjust the conditional:
if(
strpos($request_uri, '/categories/') === 0
&& $request_uri !== '/categories/'
) {}
Progrock's example will work just fine, but here is another example using a regex match instead of strpos, in case you're curious!
<?php
if (preg_match("/\/categories\/.*/", $_SERVER['REQUEST_URI'])) {
include 'test.html';
}
?>

PHP Redirect if language parameter is not in URL

I have a url such as: http://localhost/project and when the user goes there, I want to redirect to http://localhost/project/en. How do I accomplish this?
You can do this programmatically or using something at the web server level (e.g. mod_rewrite with Apache). Since you've mentioned PHP explicitly, I'll provide you the following.
In a folder called 'project' at your document root, create an index.php with the following:
<?php
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://localhost/project/en" );
exit(0);
?>
Here's a link that shows this style and other methods (including mod_rewrite) to handle this:
http://www.phatz.com/301redirect.php
There are many ways. You should be using virtual hosts and rewrite uri to prepare your URL properly, but if you don't want to bother with those and want a method that "just works" exactly for the problem you presented, then try this:
$explode = explode('/',$_SERVER['REQUEST_URI']);
if (count($explode) == 1)){
header('Location: http://localhost/project/en');
}
Edit after comments
Try this, but beware that I haven't tested it, as I don't have my prod. environment here, but it should work. If not, comment :)
$explode = explode('/',$_SERVER['REQUEST_URI']);
$endsWithSlash = FALSE;
end($explode);
if (empty($explode[key($explode)])){
unset($explode[key($explode)]);
$endsWithSlash = TRUE;
}
if (end($explode) != 'en'){
$url = 'http://localhost';
$url .= $_SERVER['REQUEST_URI'];
if (!$endsWithSlash){ $url .= '/'; }
$url .= 'en';
header('Location: '.$url);
}

Form submit response 301 or 302

I have a form on my site and every time I submit this form..I get a 301 perm, then a 302 redirect, then another 302 redirect. My data is not submitting because of these redirects. I'm having no luck finding these redirects. There is no .htaccess file that is causing this in the root of the directory.
Where do I look to get rid of the redirects? Any tips would be appreciative.
My developer tools on submit goes to 301, 302, 302.
Here is the start of my form.
<form action="index.php?view=ticket_submit" method="POST" name="QContact" runat="vdaemon">
When this submits I have a case statement look for ticket_submit. It's not even getting to ticket_submit because of the var_dump and exit methods. It just goes back to the root index.php file.
private function ProcessView($type){
$ticket = new Ticket();
$ticket->CurrentUser = $this->CurrentUser;
$ticket->TicketUser = $this->CurrentUser;
$ticket->setBlankTicketHTML();
$title = 'New ROI';
$prior_count = count($this->Containers);
$_SESSION['vdaemon'] = '1';
if($_SESSION['al'] == 't' && $type['view'] == ''){
$type['view'] = 'summary';
}
switch($type['view']){
case 'ticket_edit':
$ticket->ticketid = (int)$this->Request['ticketid'];
$ticket->TicketUser = array();
$ticket->fillTicket();
if(($this->CurrentUser['userid'] != $ticket->TicketUser['userid']) && ($_SESSION['al'] == 't' || $_SESSION['al'] == 'r')){
$ticket->setViewTicketHTML();
$title = "Error: You can only Edit items you have created.";
$_SESSION['vdaemon'] = '0';
} else {
$ticket->setEditTicketHTML();
$title = 'Edit ROI';
$_SESSION['vdaemon'] = '1';
}
break;
case 'ticket_submit':
var_dump('test');
exit();
$ticket->ticketid = (int)$this->Request['ticketid'];
$ticket->TicketUser['useremail'] = $this->Request['useremail'];
$ticket->saveTicket(0);
$_SESSION['vdaemon'] = '0';
if($_REQUEST['viewquick'] == 'quick'){$quick = 'ticket_quick_view';}else{$quick = 'ticket_filed';}
if($_REQUEST['edit'] == 'yes') {
echo 'works';
}else {
header("Location: ?view=".$quick."&ticketid=".$ticket->ticketid);
echo 'workss';
}
exit;
break;
I ended up fixing it and this is what the cause was.
Three things needed to be fixed.
The first thing was that I needed to fix a reference to a vdaemon library. The path was all screwed up. After that I got rid of a header redirect in two places. One was in a separate folder and one was on my index.php which I totally missed (thought I checked it). It was doing 302 redirects because the headers were there but in different folders throughout the server and on the index.php.
Next time I'll know what to look for. Thanks for everyone's efforts here. :)
Make sure you look for this code first when dealing with these errors
header("Location: http://www.foo.com");

why is my header("Location: $_SERVER['HTTP_REFERER']"); PHP function not working?

It works when I input
header("Location: http://www.google.com");
but it doesn't work when I have
header("Location: $_SERVER['HTTP_REFERER']");
I want to redirect the page to whatever page it came from.
Try it: :)
if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
echo "No referrer.";
However, for determining which page user came from, I'd rather use session variable, which gets reset at every page:
session_start();
echo "Previous page:", $_SESSION['loc'];
$_SESSION['loc']=$_SERVER['PHP_SELF'];
ps: This only works for local pages, you cannot track other websites.
You might try:
header("Location: {$_SERVER['HTTP_REFERER']}");
I've had problems with variable expressions which contain quotes in strings without braces.
You also need to look out for $_SERVER['HTTP_REFERER'] simply not being set. Some user agents don't set it, some privary tools mask it, and you need to handle people coming to your page without a referrer.
Here is a simple solution.
check and see what $_server['http_referer'] is giving you and if its set then you can redirect and if not put a fall back url something like :
if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != ""){
$url = $_SERVER['HTTP_REFERER'];
}else{
$url = "YOUR INDEX PAGE OR SOMETHING";
}
header("Location: ".$url);
This is a browser feature, and any polite browser will send the
correct header (although various 'security' tools will override this
with a fake referer).
It's browser specific so not every browser/security software combination will send it to the server. You're better off setting a session variable on each page load to determine which page the user came from (or something similar with a bit more logic)
header("Location: $_SERVER[HTTP_REFERER]");
Without the single quotes. This is the fastest way to access and concatenate array values without extra concatenating code.
Simply you can use
if(isset($_SERVER['HTTP_REFERER'])){
header("Location:".$_SERVER['HTTP_REFERER']."");
}
One of the mistakes that occure sometimes is, that NO OUTPUT must happen before header('Location: ' ....)
This is not working (shows the output, but doesn't redirect):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
echo $res; // <--- OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is working (does redirect properly):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
//echo $res; // <--- NO OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is also working, but doesn't make sense ():
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
if ($res == true) header("Location: {$referer}");
echo $res; // <--- OUTPUT COMES HERE, AFTER header('Location: ' ....)
}
(For better understandig, hope this may help)

Categories