users can visit pages with an unwanted URL - php

I use this structure for my post URL in my Wordpress website.
Domain.com/%post_id%/%postname%
if you delete the /%postname% part you will go to the same page?
i mean
Domain.com/post_id/postname = domain.com/post_id
Is there any way that when a user visit domain.com/post_id gets redirect to Domain.com/post_id/postname ?

Sure.
I suggest adding an action hook to an early event, maybe wp?
add_action("wp", function() {
if((is_single() || is_page()) && preg_match("!^/\d+/?$!", $_SERVER["REQUEST_URI"])) {
http_response_code(301);
header("Location: " . get_permalink());
exit;
}
});
This will run on every request and check whether that request is a) a page or post AND b) the REQUEST_URI (=local part of the URL) starts with a slash, followed by numbers, followed by an optional final slash, and nothing else. If these two conditions are met, it will return a HTTP 301 response code ("Redirect Permanent") with a Location header indicating the correct URL.
Put it into your functions.php.
It's interesting that WordPress will automatically redirect /123/postti to /123/posttitle, but it won't to the same for /123. /123/ will be redirected to /123. The code snippet I posted will take care of /123 and /123/, while wordpress takes care of those with a partial title.

Related

localhost redirected you too many times using mod_rewrite

if( isset($_COOKIE['user']) && !empty($_COOKIE['user']) ){
header("Location: ./");
}
This is my code for login page. What I want to achieve is whenever someone is logged in [if a cookie named user exists], the user should be redirected to the homepage. I am using mod_rewrite to write URLs.
The problem I am facing is that whenever the cookie exists, and I go to localhost/project/login/, it shows ERR_TOO_MANY_REDIRECTS:
However when I use localhost/project/login.php it works fine.
header("Location: ./");
./ is a relative URL. Consequently if you send back Location: ./ in the HTTP response then the browser will interpret this as relative to whatever is currently displayed in the browser.
So...
When requesting localhost/project/login/ (note the trailing slash), the browser will redirect back to localhost/project/login/ (the same URL - redirect loop).
When requesting localhost/project/login.php, the browser will redirect to localhost/project/ (your home page I assume).
To always redirect back to the homepage (/project/) from any URL-path depth then you would need to at least specify a root-relative URL in the Location header. For example:
header('Location: /project/');
(Or, you mess around calculating the current path depth from the request in order to construct a relative URL-path. But if you are going to do that then you might as well calculate the absolute URL of the homepage - or have this stored - which is arguably preferable.)

How to disable author query in WordPress

In wordpress, when you hit url like the following:
http://www.example.com/?author=1
If the author ID is valid then they will be redirected to the author URL, for example:
http://www.example.com/author/username
Then the hacker start attacking the username. How could I disable (?auther=xx) query in url?
for example redirect the request to another page like 404 (not found) page
I believe that dingo-d has it right, above, referring to the 301 redirect. I have installed 301 redirects on several Wordpress sites to accomplish this. I redirect [domain]/?author=* with a wildcard to my 404 page. I have watched my activity logs before and after implementing this. The malicious login attempts immediately switch from valid user names to the generic "admin."
Add the following filter to your functions.php file;
add_action('template_redirect', 'disableAuthorUrl');
function disableAuthorUrl(){
if (is_author())) {
wp_redirect(home_url());
exit();
}
}
This will check all incoming requests to see if the page requested is an author page, and if so, redirect to the homepage, or wherever else you choose.

how to redirect wrong entered url

My current url is http://domain.com/example.php/link=eg But if someone plays with url and puts url as http://domain.com/example.php/abcdefgh97654 - anything, my all functions all links from that page become inactive.
I tried using <?=HTTP_SERVER;?> before all links in my php files but as my website has user registration and sign in, when user signs in and clicks on any menu (link from php script). It throws on index.php page. But if user logs in again it works perfectly. In short user needs to log in twice to work everything perfect.
Basically I want two solutions one I want to redirect www dot
domain dot com/example dot php/abcdefgh97654 - anything (wrong url
page) to errorpage (I already done this in htaccess) but does not
work for above type.
List item
And want to solve two time log in problem.
If anyone has solution for this will be appreciated.
For you to do this, you have to know what values are supposed to be passed via $_GET variable to your page. Then you can create filter for the values and user header(); function.
Here is my suggestion:
<?php
$var=$_GET['val']
//get expected length if you need.
if(strlen($var)>9 or strlen($var)) {
$redirect=true;
}
//if you know what you are expecting
$vals=array('val1', 'val2, 'val3');
if(!in_array($var, $vals)){
$redirect=true;
}
//continue or replace your filters in this manner and asign your value to $redirect
if($redirect==true) {
header("Location:url"); // do this before anything else is printed to the page or else it will say headers already sent.
}
?>

php / expression engine - redirect all URLs from one URL segment to another URL segment

I have an expression engine site that I recently redid and, while the titles of each article or page on the site did not change, the routes to them did. So, for example, where before I had:
site.com/site/code_single/name-of-page
I now have
site.com/main/code-item/name-of-page
How would I set up a redirect (either with expression engine tags or with PHP / .htaccess) so that all URLS matching site/code_single got redirected to their corresponding titles in site/main/code-item?
A single line of .htaccess really is the simplest solution here I think.
RedirectMatch ^/site/code_single/(.+)$ /main/code-item/$1 [L,R=301]
if you need a php solution you could call this function before any other code is executed(at the top of your main index.php.
I use this to reroute codeigniter urls without keeping duplicate urls alive what would happen if you use the routes.php
For those wondering why? Google loves 301 redirects and hates double content. Codeigniter has a nifty feature to make your own "routes" so you can use your own url where you need it. The problem is, the original "unwanted/ugly" url still is accessible and if google finds this out, your page takes a nosedive in seo ranking.
Having found that out I tried to uncover any sort of 301 redirect function in codeigniter only to hit a brick wall everytime, and .htaccess redirects failed time over time(and i'm not the only one, stackoverflow is full with it)
So that is why I decided to write this, with keeping speed in mind so as little "fancy manipulation" as possible to get the job done.
You'll have to add these lines at the very top of your first index.php file of codeigniter
require ('myobjects_x.php');
redirecttoHTTPS();
I have called the below file myobjects_x.php and saved it in my base directory where the first index.php file of codeigniter is.
/* Codeigniter 301 reroute script written by Michael Dibbets
* Copyright 2012 by Michael Dibbets
* http://www.facebook.com/michael.dibbets - mdibbets[at]outlook.com
* Licenced under the MIT license http://opensource.org/licenses/MIT
*/
function redirectToHTTPS()
{
// remove this if you don't need to redirect everyone to https
if($_SERVER['HTTPS']!=="on")
{
$redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header( "Status: 301 Moved Permanently" );
header("Location: $redirect");
exit(0);
}
// get the request url
$uri = urldecode($_SERVER['REQUEST_URI']);
// check for unwanted trailing slashes.
// if they exist redirect our visitor.
// we want urls without trailing slashes so we don't need to to check the same url twice
if($uri !== '/')
{
$slash = substr($uri, strlen($uri)-1, 1);
if($slash === '/')
{
$uri = substr($uri, 0, strlen($uri)-1);
$redirect= "https://".$_SERVER['HTTP_HOST'].''.$uri;
header( "Status: 301 Moved Permanently" );
header("Location: $redirect");
exit(0);
}
}
// if we have double slashes in our url for whatever reason replace them with single slashes
if(strpos($uri,'//') !== false)
{
$uri = str_replace('//','/',$uri);
$redirect= "https://".$_SERVER['HTTP_HOST'].''.$uri;
header( "Status: 301 Moved Permanently" );
header("Location: $redirect");
exit(0);
}
$urilistcount = 0;
//Just keep copy pasting this. In the orig you do the url without domain to check.
// The code checks the begin of the url, and if it matches it'll append anything that was
// behind the part you wanted to check. for example
// $urilist[$urilistcount]['orig'] = '/pressrelease/82/something';
// $urilist[$urilistcount]['good'] = 'http://www.domain.com/hereweare';
// $urilistcount++;
// will cause /pressrelease/82/something/we-have-something-to-say to reroute to
// http://www.domain.com/hereweare/we-have-something-to-say
//
// So make sure that your "top level" that's likely to match to a lot of sub pages
// is placed last in the array, and that the sub pages you want different reroute urls for route first
// When an route is encountered, processing stops at that point.
// Copy paste from here and add below it
$urilist[$urilistcount]['orig'] = '/pressrelease/82/something';
$urilist[$urilistcount]['good'] = 'https://www.domain.com/media/pressrelease/31/somewhereinteresting-with-an-title-in-url-for-seo';
$urilistcount++;
// End copy and paste
for($c=0;$c < $urilistcount;$c++)
{
if(strpos($uri,$urilist[$c]['orig'])===0)
{
$tmpx = strlen($urilist[$c]['orig']);
$tmpy = strlen($urilist[$c]['good']);
if($tmpx != $tmpy)
{
$tmpz = substr($uri,$tmpx);
// special check to replace dashes to underscores
// only when this word appears in the string to append.
if(strpos($tmpz,'/iamadash-')===0)
{
$tmpz = str_replace('-','_',$tmpz);
}
// add the extra variables to the good url.
$urilist[$c]['good'] .= $tmpz;
}
header("Status: 301 Moved Permanently" );
header("Location: " . $urilist[$c]['good']);
exit(0);
}
}
unset($urilist);
}
// filter out bad urls character/strings that cause codeigniter to break
function CIsafeurl($string)
{
return str_replace(array('&','‘','’ ','&','=','+','*','%','’',';','\'','!',',',':',' ','(',')','[',']','?','--','/'),array('-','','','-','','','','','','','','','','','-','','','','','','-','-'),$string);
}
Thanks - think I found a good solution online that involves having EE dynamically generate a list of URLs for 301 redirect:
http://www.blue-dreamer.co.uk/blog/entry/expressionengine-301-redirects-made-easier/
There's an add-on called Detour Pro that allows you to create 301 and 302 redirects within a simple admin panel in EE (it even provides metrics on each redirect you establish). It's worth a look if you have a lot of them to manage and want to avoid doing it in htaccess - particularly if not all of redirects have been mapped out and you need the client (within reason) to be able to create such redirects themselves.

PHP Header() redirect shows old URI briefly before redirecting to new

Right now, I am using a custom PHP solution to force WWW to be appended to my script URLs, since I am using WordPress' .htaccess rules to "clean up" index.php. The force WWW .htaccess rules are not compatible with WordPress' index.php cleanup rules.
With my script, you can browse to "http://scripturl.com/whatever" - my script then has a case for request URI "/whatever" and then does some action (or compiles the respective template) for that view.
I have added a series of checks prior to any any switches being called, which makes sure that the HTTP host from the REQUEST matches the HTTP host from a defined variable in my script. This enforces the addition of the "www".
My PROBLEM - is that (seemingly when only using IE) - when I enter a url, say "http://myscript.com/whatever", my script transforms the url to "http://www.myscript.com/whatever", as expected, and then redirects the header to the new URL. HOWEVER, if I change the URI request from "whatever" to "somethingelse", the page goes to "http://www.myscript.com/somethingelse" as expected, but for a brief second, "whatever" blinks in the url before the script redirects to "http://www.myscript.com/somethingelse".
To clarify: start with request "www.myscript.com/sam". request loads.
Change /sam to /bob -> page changes to "www.myscript.com/bob" but "/sam" flashes in the url bar briefly before /bob loads.
It just doesn't feel "clean". I feel like my code might be doing an extra header jump or something. I have contrasted this to wordpress, by going to "www.wordpressurl.com/valid-page", then changing the URI to "www.wordpressurl.com/another-valid-page" - I don't see "/valid-page" flash in the URL bar when attempting to access "/another-valid-page", and vice versa.
Here is my code:
// Requested URL built from url in address bar
$requested_url = is_ssl() ? 'https://' : 'http://';
$requested_url .= $_SERVER['HTTP_HOST'];
$requested_url .= $_SERVER['REQUEST_URI'];
// Correct url built from predefined variable
$correct_url = is_ssl() ? 'https://' : 'http://';
// "Correct" script url
$user_home = #parse_url('http://www.myscript.com');
if ( !empty($user_home['host']) )
$correct_url .= $user_home['host'];
else {
die('malformed url');
}
$correct_url .= $_SERVER['REQUEST_URI'];
// If URL in address bar is not proper, perform redirect (preserve URI)
if ($correct_url != $requested_url) {
hc_redirect($correct_url, 301);
}
// Get page from request, handle accordingly
$page = $_SERVER['REQUEST_URI'];
switch ($page) {
/* Index */
case '/':
echo "Index queried <br />";
break;
...
Why does the old URI flash in the navbar before the new URI is loaded (from the redirect)? Like I said, this only appears to happen in IE - but WordPress does not have this same behavior (in IE or any other browser), so I know there must be something wrong with my code, an "extra step" which is happening without my knowledge. I'm somewhat new to PHP.
Any thoughts?
Edit: hc_redirect, and other used funcs: http://pastebin.com/fVNEckEg
Your script continues to output data after you redirect, the browser waits for the data and only then redirects. If you don't need to continue execution of the script after you send the redirect header, stop the script's execution. For example:
// If URL in address bar is not proper, perform redirect (preserve URI)
if ($correct_url != $requested_url) {
hc_redirect($correct_url, 301);
die();
}

Categories