Blerta Idrizi
Blerta Idrizi

Reputation: 29

Allow PHP page only if set the correct url

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.

Upvotes: 0

Views: 174

Answers (6)

Gilly
Gilly

Reputation: 9692

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

Upvotes: 0

CAO
CAO

Reputation: 131

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.

Upvotes: 0

Altimus Prime
Altimus Prime

Reputation: 2327

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");
}

Upvotes: 0

H2ONOCK
H2ONOCK

Reputation: 981

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?

Upvotes: 2

Sterling Archer
Sterling Archer

Reputation: 22395

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.

Upvotes: 1

Clay McIlrath
Clay McIlrath

Reputation: 612

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
}
?>

Upvotes: 1

Related Questions