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.
Related
On my website i am using quite amount for GET parameters in url for loading specific page. And some of available actions involve calling another GET parameter in order to do something (..&act=something). PHP file with this actions is included at the top of the page. Below of this inclusion i have some code that checks if URL is valid, otherway header will head you to the correct one.
Lets say i have added a player as a friend.
Requested URL will be for example:
?id=3&request=clan&act=add&target=5.
So going by this url i am supposed to go in case: 'add' part and later being redirected by that header. However what i have is that this header is ignored. Instead, i am redirected by checking part. What is more odd, added friend appears in my friend list. Why does this happenes?
<?php
if (isset($_GET['act'])) //this code is included
{
switch ($_GET['act'])
{
case 'add':
//do something
header('Location: /index.php?id='.$cuid.'&request=clan§ion=members');
break;
}
}
//some other code
if ($_GET['request'] == 'clan')
{
if ((!isset($_GET['section']) || ($_GET['section'] == '')) && ($c_guid != 0))
{
header('Location: /index.php?id='.$cuid.'&request=clan§ion=info');
}
}
?>
Outputting a header does not actually stop your script! All the other code is running as well. You need to explicitly exit if you do not want any further code to be executed.
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 am trying to figure out how to allow PHP index only if it matches the URL I put in, something like this:
Example if you put in URL site.com/myfile.php I want to show message like 404 Error or something
But if you put site.com/myfile.php?=123 to show the page content.
I think it might be considered bad practice to send someone to a 404 when the page that they are accessing does actually exist, it's only a variable that they are missing.
Firstly, I'd expect to see something like
site.com/myfile.php?variablename=123
instead.
If you absolutely wanted to, you could at the top of your file then add a:
if(!isset($_GET['variablename']){
header('location:404.php');
}
Where 404.php is your 404 file that you'd like the user to see.
Hope that helps?
You could run a conditional looking for the request info, i would make it specific like using a ?page_id=123
<?php
if ( $_REQUEST AND isset($_REQUEST['page_id']) )
{
// SHOW PAGE CONTENT
}
else
{
// RETURN 404
}
?>
You would have to test the $_GET parameters.
if (!$_GET) {
echo "404 Error"; //or redirect using header();
} elseif ($_GET['key'] == 'value') {
//code here
}
I see you are using ?=123, I'm not 100% on if that will work, but it's easier (IMO) to have a key=>value association in the URL.
This should be enough for what you need. If there are other requirements let us know.
if(!isset($_GET)){
//do whatever you want to validate the get input provided.
} else {
header("HTTP/1.0 404 Not Found");
}
Well first of all this ?=123 might be an issue because when ?=123 is passed then it should be stored somewhere, it could be like this ?uid=123 and then you retrieve it in a variable through the get method and then check its value and accordingly redirect the user.
You can do something like this
if(isset($_GET['uid']))
{
refresh(to whatever location you want);
}
else
refresh(to some other location);
but if you want the error 404 something then its not possible according to me, because the values will be sent to a page that exists and if the page exists then the server cannot give a "not found" error.
By simply comparing a string.
if (#$_GET['secret'] != 'mysecret'){
header('location: noaccess.php'); //redirect the user to access denied page.
die(); // terminate the script. A
}
// The rest of the page
Or to keep everything in one file:
if ((isset($_GET['secret'])) && ($_GET['secret'] == 'mysecret')){
// Show the page
} else {
// Show an error message
}
site.com/myfile.php?secret=mysecret
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();
}
?>