I want to check which URL someone is currently on. For example:
if(url=index.php?p=contact) {
echo the code i want to run,
}
else {
do nothing
}
So basically, I want to run a block of code when the user is on index.php?p=contact
The current requested URI path plus query is available in $_SERVER['REQUEST_URI'] and the filename of the processing script in $_SERVER['SCRIPT_FILENAME'].
If you need to check the complete path, see Gumbo's answer. If index.php is only accessible by navigating to that name directly (that is, you know if index.php is being executed the user must've gone to index.php, and you're not using something like URL rewriting), it probably makes much more sense to just check:
if($_GET['p'] == 'contact')
within index.php. If the condition is being reached, index.php is executing and clearly that's the page the user is on
This is what I did (to make it as I want with .htaccess); works for me since I do not have allot of pages to check. I used PHP_SELF:
<?php
if (htmlentities($_SERVER["PHP_SELF"]) === "/.../index.php") { // echo $_SERVER["PHP_SELF"] to see your path ..
header("Location: ./"); // I am using .htaccess, so I only want the page name and exclude ".php" in the address-bar (URL)
die();
} else if (htmlentities($_SERVER["PHP_SELF"]) === "/.../page2.php") {
header("Location: page2"); // I am using .htaccess, so I only want the page name and exclude ".php" in the address-bar (URL)
die();
}
?>
Related
I've had a previous question answered on how to add a / to my url and redirecting it internally. The answer I got worked great, see here but i've stumbled on a new problem.
When you recover your password you are forced to change it:
if (logged_in() === true) {
if ($current_file !== 'changepassword.php' && $user_data['password_recover'] == 1) {
header('Location: changepassword.php?force');
exit();
}
}
When you're on the index page, and are forced to change your password, the URL goes from mysite.com//index/ to mysite.com//index/changepassword/?force which obviously does not exist.
When I use ?force without changepassword.php it gets a "this page has an this page has redirect loop" warning, although it did work for other things like ?success.
Base href="/" also doesn't have any effect.
Any ideas?
My guess of your problem is that you replace a "terminating" .php with /. So /index.php turns into /index/. If you now redirect to changepassword.php?force, you will end up with /index/changepassword/?force.
But as the script changepassword.php likely is located at the same level as index.php, you have to use a host relative redirection, instead of a path relative redirection:
header('Location: /changepassword.php?force');
Please note the leading / in the location target.
I have several folders on my domain, within each folder contains an index.php file that checks to see if the database connection passes or fails, if it fails, the page is redirected to a top level file (outside of all folders) called offline.php. This part works great. The basic format I'm using to redirect if the db is offline is:
if ( !$dbconnect ) {
header("Location: https://www.test.com/offline.php");
}
Then, within the offline.php page, I need to check to see which folder brought the user to the offline.php page, and display a unique message to the user - based on the folder that brought them to the offline.php page.
For example:
test.com/test1/index.php redirects to offline.php, the message would say 'test1 brought you to this page'
test.com/test2/index.php redirects to offline.php, the message would say 'test2 brought you to this page'.
In multiple browsers I've tried the following code, which always results in 'unknown uri':
$url = 'https://' . $_SERVER['HTTP_REFERER'] ;
if ( strpos($url,'test') !== false ) {
echo 'test';
} elseif ( strpos($url,'test1') !== false ) {
echo 'test1';
} elseif ( strpos($url,'test2') !== false ) {
echo 'test2';
} else {
echo 'unknown uri';
}
Suggestions?
EDIT
Due to the unreliable nature of HTTP_REFERER I've decided to put all of the conditions within the index.php page and forget about the offline.php page. A HUGE thank you to everyone who offered suggestions!
Why would you use redirects at all? They are heavy on the server, slow and just plain old unnecessary. Use a switch statement and have 1 controlling page instead of multiple folders and pages.
If you use the following code on your offline.php page, you can see all of the $_SERVER variables available (referring URL is in there)
echo '<pre>',print_r($_SERVER),'</pre>';
From there, you can take $_SERVER['HTTP_REFERER'] use a select case, or if then statement and accomplish your goal.
Based on some of your questions in the comments and people pointing out the use of $_SERVER['HTTP_REFERER'] being unreliable, you could do something like this instead.
On your index.php page with the dbconnect check, you could modify it to be something like this. header("Location: https://www.test.com/offline.php?org=".urlencode($_SERVER['REQUEST_URI']));
Then, on the offline.php,
$page = urldecode($_GET['org']);
$org = explode('/',$page);
echo $org[1] to get the first value after the slash, $org[2] would get the next value etc..
having a problem here with WordPress. I want to redirect the page to a specific .php file inside a folder (php/adminpage.php) whenever $_SESSION variable is equals to 1. Let's say the session variable is 1:
<?php
if ((isset($_SESSION['login']) && $_SESSION['login'] == '1')) {
header ("Location: php/adminpage.php");
?>
But the browser returns "Not Found". Any ways to get it to work?
UPDATE [SOLVED]: Using the full path works. Thanks to #andrewsi. Working code:
<?php session_start();
if ((isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: wp-content/themes/euro/php/adminpage.php");
}
?>
You're using a relative path:
header ("Location: php/adminpage.php");
That will look for a folder below where the current file is, and look for adminpage.php in there.
But WordPress does some funny things with page names and .htaccess, so your current page might not be where you expect it to be; it's generally always better to use a full path, which is a lot less ambiguous:
header("Location: /wp-content/themes/euro/php/adminpage.php");
And don't forget to exit after calling it, too, so code execution stops on the page from which you are redirecting.
Is this an actual URL location?
header ("Location: php/adminpage.php");
To my eyes it seems like a file system path. Because is your local setup at this URL:
localhost
And then this would be the location of that file?
localhost/php/adminpage.php
Also, I would clean up your code like so:
<?php
if (array_key_exists('login', $_SESSION) && isset($_SESSION['login']) && intval($_SESSION['login']) == 1)) {
header("Location: php/adminpage.php");
}
?>
By using array_key_exists you prevent unset index errors & by using intval you are assured there is a numerical value in place.
I have the following code in my index.php page:
<?php include("/includes/widgets.php") ?>
And in my widgets.php page:
<?php
header("Location: /");
?>
What I want to achieve with this is to redirect it if the user visits it, but allow it for including.
But I get the following error:
The webpage has a redirect loop
How can I fix/prevent the redirect loop, but still redirect the user and not the server.
Place the widgets.php file in a folder not accessible to HTTP clients. I.e on apache webserver, either put it above your document root (into it's parent) or use .htaccess file to block users from it.
e.g.
deny from all
I think I know what you need :)
Change code index file to next
define("IS_INDEX", true);
include("/includes/widgets.php"
Change code for widgets.php to next
if (!defined("IS_INDEX")) {
header("Location: /");
exit();
}
The issue is you are redirecting back to the same page, which then redirect again, and again, and again.
An easy fix would be to wrap the redirect in an if, and only redirect if they aren't already on the index page; but this is just patching what looks like an architectural problem.
Something like:
if (ltrim($_SERVER['REQUEST_URI'], '/') != 'index.php')
header('Location: index.php');
One way is to check if __FILE__, which is the file loaded, regardless of included or not matches up with the file requested which is in $_SERVER['REQUEST_URI'] (or $_SERVER['PHP_SELF']).
I use this on our development site in a page that is usually included to get the output as debugging.
if(basename($_SERVER['PHP_SELF'])===basename(__FILE__)){
//do some debugging
}
Typically you wouldn't use basename, but this is on a non-public facing development site and the file has a pretty unique name so I'm not worried about the file being included with another file with the same name or anything.
One possible way is to add a parameter to the redirection, e.g.
if (!$_REQUEST['redirect'])
header("Location: /ìndex.php?redirect=1");
That way redirection can happen only once.
Another way is to stop redirection if the user already is on the /. I´d suggest to combine both.
I have a php page which should be included in otherpage but no directly. Lets assume it as 1.php and the other page as 2.php
1.php
<?php
if($_SERVER['REQUEST_URI'] == "/1.php"){
header("Location:2.php");
}
else
{
//some code here
}
?>
2.php
<?php
include("1.php");
?>
this worked well on localhost/1.php and have been redirected to localhost/2.php
but this had made a problem with localhost/1.php?somegetmethod=data I found that anyone can access this page by typing ?something=something at the end of 1.php url. How to change the code which can redirect all url which starts with localhost/1.php
you could check if a substring is at a given position like this
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0) {
this checks if the REQUEST_URI starts with /1.php (= is at position 0)
Use $_SERVER['PHP_SELF'] instead of $_SERVER['REQUEST_URI'].
try it:
if($_SERVER['SCRIPT_NAME'] == "/1.php")
$_SERVER['REQUEST_URI'] contains URI of requeted page, in yoour case it's 1.php?somegetmethod=data.
Change code like:
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0){
header("Location:2.php");
}else{
//some code here
}
What you often see, for instance in MediaWiki, WordPress and many other such applications, is this:
1.php
if ( !defined( 'YOURAPPCONSTANT' ) ) {
// You could choose to redirect here, but an exit would make just as much
// sense. Someone has deliberately chosen an incorrect url.
echo "Cannot directly call this file.";
exit( 1 );
}
2.php
define('YOURAPPCONSTANT', 'It is defined');
include('1.php');
That way, 2.php is the entry of your application, regardless of the url used to reach it. I think this is a much safer and more flexible way, and it is used so often for a reason.