report error 404 by email with last accessed URL - php

I'm making a page 404 with button for user report that site have a problem. The idea is when user click on button, I receive a email with information of the last page accessed...
The problem is that I'm using the php variable '$_SERVER['HTTP_REFERER']' and this ever return a null value. I found this question (In what cases will HTTP_REFERER be empty) and I came to the conclusion that this variable is not the solution.
This is my .htacess
RewriteEngine on
ErrorDocument 404 http://example.com/erro.php
#ErrorDocument 404 /erro.php #this doesnt work... redirect doesnt work
On page erro.php I have code with function email that are working without problem, but I need some manner to take last accessed page that generate error.
On page erro.php I'm trying use:
echo $_SERVER['HTTP_REFERER']; // return null value
echo $_SERVER['REQUEST_URI']; // return page http://example.com/erro.php
I try use alternative with jQuery (https://stackoverflow.com/a/2415645/2761794):
On page erro.php
$(document).ready(function() {
var referrer = document.referrer;
alert(referrer); // return null value
});
Some suggestion to take last accessed URL on page erro.php for send by email?

As you are willing to work with mod_rewrite anyway and have PHP there is a slightly different approach.
First you could detect for a request that is for a file or directory that is not there and pass that to the PHP script with a rewrite.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Rewriterule ^(.*) /erro.php?error_path=$1 [R=301,L]
Depending on your exact setup you may need to tweak that last line perhaps to
Rewriterule ^(.*) http://example.com/erro.php?error_path=$1 [R=301,L]
I find that mod_rewrite is somewhat akin to voodoo and can sometimes need a little "try it out and see what works".
Then in your erro.php file:
<?php
$badfile = $_GET['error_path']; // the URL that 404'd
http_response_code(404); // send the 404 header code
// ... your other code
The end result for the visitor should be almost the same but you would have access to the data you need.
Much of the rewrite directive came from this question: htaccess errordocument 404 and pass url to path
For more on setting response codes in php: http://php.net/manual/en/function.http-response-code.php
mod_rewrite cheat sheet: http://www.cheatography.com/davechild/cheat-sheets/mod-rewrite/
The official doc on mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html

Related

Avoiding 302 redirect when setting up multiple 404 pages

My error page is a PHP file, the entirety of which is
<?php
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$parts = explode('/', $path_parts['dirname']);
if (in_array("abcde", $parts))
{
header('Location: https://example.com/vwxyz/abcde-error-page.php');
exit();
}
else
{
header('Location: https://example.com/vwxyz/error-404-page.php');
exit();
}
?>
I want users who go to a non-existent URL in the "abcde" directory to see a particular error page, and the URL should be https://example.com/vwxyz/abcde-error-page.php and the status code should be 302. This is working just fine.
I want users who go to any other non-existent URL (in the "vwxyz" directory, or anywhere else on example.com) to see https://example.com/vwxyz/error-404-page.php, but for a 404 status code to be returned, and the URL in their browser should still be whatever they erroneously typed in. Of course, that doesn't work with header('Location ... and I can't use file_get_contents or include because the result empties the shopping cart and logs out the user (if they were logged in).
I feel that there is a simpler way to have multiple 404 pages without editing the .htaccess file (though the argument will probably be made that that is indeed the simpler way). And it is vital that the main error page behave exactly like a normal error page, but that the other (for the "abcde" directory) be a redirect, and that that special error page for the "abcde" directory NOT be in that directory (the user gets redirected out of the directory and then shown the "error"page, which should NOT return a 404 status).
If I understand the question correctly it is pretty simple via a root .htaccess file.
# enable mod_rewrite and route the request
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^/abcde/?.*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /vwxyz/abcde-error-page.php [R=302,L]
# sets a custom 404 page
ErrorDocument 404 /vwxyz/error-404-page.php
First you need to switch the rewrite engine on, then perform 3 checks:
Does the URL begin with /abcde/
Is the URL not a file
Is the URL not a directory
If those things are all true then you want to route (with a 302) to /vwxyz/abcde-error-page.php
For any genuine 404 error you can just use the default ErrorDocument 404 ... syntax.
(OK this was 6 lines in .htaccess - twice as complicated as I guessed)

How to get the parameters from url without notice

So I was thinking of a way to remove the parameters from url when page is downloaded to client and respond different in each different value of the get parameter.
Let me take it clearer for you. Say I have this url: www.abc.com/?q=jsdfnjns. Ideally, I am thinking of shortening this url with goo.gl and then send it to the customer. When customer clicks on it, it will automatically go to www.abc.com clean url and set a cookie to the client with the q's value. I have seen it before in many affiliate links except that the initial url had no get parameters but value was actually a sub-folder e.g www.abc.com/jsdfnjns
So what's the way to actually get the value of a get parameter and manipulate it with php, while removed from the url without user's notice, or setting a cookie when parameter is given as a sub-folder. I suspect it must be some htaccess rules and php tricks but can't find a way.
With given url www.abc.com/jsdfnjns how can i redirect immediately to www.abc.com
and have the jsdfnjns saved ideally server-side in apache or in a user cookie ?
Is there any way to make it also happen with actual get parameters too ?
And a schematic:
www.abc.com/jsdfnjns convert it to -> goo.gl/sjbjsb -> when clicked, user is going to www.abc.com but somehow i get the jsdfnjns and respond in the main page different.
Hope my question is well defined, any ideas will be appreciated.
Thanks.
Firstly you need to set .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?q=$1 [QSA,L]
</IfModule>
index.php code:
session_start();
if(isset($_REQUEST['q'])) {
$_SESSION['q'] = $_REQUEST['q'];
header('Location:index.php');
die();
}
else{
if(isset($_SESSION['q'])) $q = $_SESSION['q'];
else $q = null;
//YOUR CODE
var_dump($q);
}

.htaccess create user friendly url and ridirect to it

i tryed to search everywhere for this problem but i didnt found nothing.
I want to make make a url seo friendly so i used this code:
RewriteEngine on
RewriteRule ^Homepage index.php [NC,L]
Then i want to redirect to it so i tryed to write this code:
RewriteRule ^index.php$ http://localhost/siti/socialmark/Homepage [R=301,L]
The error it's a loop of redirections, can someone help me?
SORRY FOR MY BAD ENGLISH!
The rewrite rules don't just make the URL string look different, it actually directs the user to the file at the end of the path even if you don't see it in the address bar. If Homepage is a directory containing index.php, even if that php file name doesn't appear in the URL, then it's causing a loop because it's directing you to a directory with an index.php.
The rule is executed every time that page loads. So, you're redirecting to a page which runs the redirect script, so it runs the rule to redirect again, and that causes the loop. What you want to do is create a condition that says "Don't run this code if the requested page is http://localhost/siti/socialmark/Homepage"
Something like this (you may have to adjust it)
RewriteBase /
RewriteCond %{REQUEST_URI} !=/siti/socialmark/Homepage
RewriteRule ^Homepage index.php [NC,L]
For more details, see the caveats and example here:
http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_l

Is it possible to build a RewriteRule regex with database values?

When my client adds a page to the site, the new pagename should be appended to a RewiteRule regex. So with, for instance fwrite(), I would like PHP to change that RewiteRule regex with values retracted from the database. If this could be done, are there any pitfalls in the process?
Edit: handling in a PHP script would be the solution, if there would'nt be more to it...
First domain/index.php?page=pagename is 301 redirected to "domain/pagename"
to warn the visitor this page is permanently moved - (this is the old
PUBLIC location of the URL and should give this 301). Then requests
like "domain/pagename" (the new public location), would be
silently,internally rewritten to domain/index.php?page=pagename where
verification takes place and a 404 is given when not valid. But just
the key, the "page" part of ?page=pagename, is static and can be
verified and will give a 404 directly from within the .htaccess . Now,
requests like domain/index.php?page=crap will first nicely give a 301
like the valid domain/index.php?page=pagename does, and only when
arrived in the index.php can be identified as crap. So there is still
a need to get the pagenames from the database to inside the .htaccess.
This is a sample of the .htacces content to give some background to this problem:
ErrorDocument 404 http://localhost/testsite/404.php
RewriteEngine on
RewriteBase /testsite/
## block craprequests without extension like domain/crap > 404
# The requests domain/pagename that do not go to existing pages, will now be redirected with a 302 to index.php?page=pagename and only then give a 404 through the errorcheck in the code.
# This should be done here, with a RewriteCond regex with database content
RewriteCond %{REQUEST_URI} !404.php$
RewriteRule .* 404.php [R=404,L]
## block-direct-queries ##
RewriteCond %{QUERY_STRING} !marker=1$
RewriteCond %{QUERY_STRING} page=(.*)
RewriteRule ^.*$ %1? [R=301,L]
## strip-extensions ##
RewriteCond %{QUERY_STRING} !.
RewriteCond %{REQUEST_URI} !404.php$
RewriteRule ^([\w+%*\d*\+*\-*]+)\.(php[\s]{0,3}|htm[\s]{0,3}|html[\s]{0,3})$ $1 [R=301,L]
## put-querystring
RewriteRule ^([\w\-_]+)\/?$ index.php?page=$1&marker=1 [L]
I'm sorry to keep repeating this back to you, but there just isn't a need for storing the page name in the .htaccess. This can all be done much more simply in PHP.
The only rewrite rule you need is this:
RewriteCond %{REQUEST_URI} !^/?index\.php$
RewriteRule .* /index.php [L,QSA]
Now, in PHP, you can do something like this:
// The important point here is that $_SERVER['REQUEST_URI'] contains the actual
// path the user typed into their browser, which is what you are interested in
if (strtolower(basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) === 'index.php') {
// The user directly requested index.php
if (!empty($_GET['page']) || value_of_page_is_crap()) {
// The user requested a bad page
header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
} else {
// Redirect to correct URL
header("{$_SERVER['SERVER_PROTOCOL']} 301 Moved Permanently");
header("Location: http://{$_SERVER['HTTP_HOST']}/{$_GET['page']}");
}
exit;
}
// The request is allowed to continue
$requestedPage = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);
The .htaccess will route every single request blindly through PHP, where much more precise logic than mod_rewrite's clunky PCRE-based rules can be used.
The PHP script examines the URI the user typed into their address bar in the browser. If they directly requested index.php, it will check whether $_GET['page'] contains a sensible value and if it does, redirect them to the correct URL, if not respond with a 404. If the user did not request index.php directly, the script can continue. I have added an example line to show how you could extract the value of the page they requested, but how you continue on from here is up to you.
This will most likely be possible (although writing permissions may be an issue). However wouldn't it be a better way to route all requests from the client through the index.php file and let PHP handle the routing.
This way you will be maximum flexible and you don't have to do "hacky" stuff.
EDIT
All forms of redirect can be done from PHP. E.g. an example of a 301 redirect:
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: http://example.com/new/path'); // note the full address
exit();
Please see the manual for more information about the use of header().

Can't access post or get from a php page after redirecting

I'am redirecting about 100 hmtl pages to a single PHP page (example.php) using .htaccess. It is working perfectly.
I've pagination on that page (example.php) but I am using the original HTML page URL (example.html?page=2&limit=20)
so example.html, example1.html, example2.html, example3.html are all redirecting to example.php.
The address bar is still showing ".html" URL but due to .htaccess redirection the example.php is rendering.
when is click on a pagination link (example.html?page=2&limit=20) the browser address bar shows correct .html URL and query string.
I've tried to get the values of page, and limit using $_GET and $_REQUEST in (example.php) but i am not successful.
Please help me in reading the (example.html?page=2&limit=20) query string parameeters .
Edit Code ported from comments:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.*)$
RewriteRule ^page-(.*)$ size-content.php?sef=$1 [L]
Add the QSA flag, which means "query-string append" to be sure the existing query string is ported into the rewritten URL.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.*)$
RewriteRule ^page-(.*)$ size-content.php?sef=$1 [L,QSA]
.htaccess modify your server configuration.
if you are making redirection then you change your request.
Try mod_rewrite if you are using Apache of course.
RewriteEngine On
RewriteRule ^example\.html\?(.*) example.php?$1
Mod rewrite is module to Apache. It is not allowed on most free hostings.
Yasir - you can resolve this problem by two ways:
1) Re-write rules for .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.).html(.)/(.)$
RewriteRule ^page-(.).html(.)/(.)$ size-content.php?sef=$1&page=$2&limit=$3 [L]
This rule will handle: page-example.html?page=2&limit=20
I hope - you will easily understand the above rule.
Note: Keep one thing in your mind that every link should be in same pattern if you change rule in htaccess.
2) You can resolve this problem on your "size-content.php"
Suppose page-example.html?page=2&limit=20
$_GET['sef'] = example.html?page=2&limit=20 [according to you .htaccess]
Now you can parse this string via explode function
Thanks

Categories