Jump to content

[SOLVED] PHP and mod_rewrite link validation


amin7b5

Recommended Posts

I don't know if this has been asked here before, I couldn't find it. I just set up apache's mod_rewrite to take my old links which were "http://localhost/index.php?display=var" and allow the new links as "http://localhost/services" or "http://localhost/contactus".

 

My content files are not in a database. They are simply in a 'content' directory. They are then 'required' in the index.php based on what $display is set to.

 

The problem is that a user could type in a bogus url such as "http://localhost/badurl" and get a page of mess because the 'require $display' couldn't get a file. I would like them to just see a 404 style error.

 

What's the best way to do this? Is there a way for PHP to look in the 'content' directory and if $display doesn't match a file it would bring up a 404 file? I know there's a way to do this, I just don't know how to phrase my code.

 

Thanks in advance for any help!

As ure not opening files, but instead including them, u cant add a errordocument rule in htaccess for 404 errors. Instead u can make it script based. Consider the following:

 

<?php
$page = $_GET['page'];
$myPages = array('contact', 'about', 'services'); //your list of pages
if(!in_array($page, $myPages)){ //if $page is not in array $myPages
      header('Location: error.php'); //redirect to the error page
}
?>

Just saw that u wanted a way to look in the content directory for the pages, so to automatically filling your $myPages array use this code instead:

 

<?php
$page = $_GET['page'];
$folder = 'content';
$myPages = array();
$handle = opendir($folder);
while(($pages = readdir($handle)) !== false) {
if($pages == '.' or $pages == '..'){ continue; }
$myPages[] = $pages;
}
closedir($handle);
if(!in_array($page, $myPages)){
      header('Location: error.php');
}
?>

 

Its not a good practice anyway to read folder contents everytime the script is run, as it will only decrease the script's time, but for a few files it shouldnt be much of a problem.

If they try to include a page that doesn't exist, put this in like, an else:

 

<?php

header("HTTP/1.0 404 Not Found");

include("/var/www/html/site.domain.com/err/404.php");

?>

 

But put in your 404 document.  Figure out the path to it. @_@

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.