*Terms and Conditions apply

ASP page include (w/ PHP comparison for reference)

by David Dolphin on Mar.15, 2010, under Meh

I’ve had to do a project in ASP for college. It’s taken me a while to wrap my head around the following construct in ASP, the idea is that you include a file from a HTTP GET variable, with path parsing (to ensure you don’t leave your application open to attack). This allows you to have a common header and footer and change the body of the page as necessary.

Make sure you’re handling your 404’s correctly. In this example 404.{asp,php} doesn’t actually exist, so it will naturally 404. Maybe not the prettiest, but this is a bit of a hack.

This is the code in PHP:

<?php
$MyFile = $_GET['page'];

if ($MyFile == "")
	$MyFile = "homepage";

$MyFile = str_replace('.', '', $MyFile);
$MyFile = str_replace('/', '', $MyFile);
$MyFile = str_replace('\\', '', $MyFile);

$MyFile = 'pages/' . $MyFile . '.php';

if (file_exists($MyFile)) {
	include($MyFile);
} else {
	header( 'Location: http://doma.in/404.php');
};
?>

And this is the equivilant ASP:

<%
Dim MyFile
MyFile = Request.QueryString("page")

If MyFile="" Then
	MyFile = "homepage"
End If

MyFile = replace(MyFile,".","")
MyFile = replace(MyFile,"/","")
MyFile = replace(MyFile,"\","")

MyFile = "pages/" & MyFile & ".asp"

Dim FileSystemObject
Set FileSystemObject=Server.CreateObject("Scripting.FileSystemObject")
If FileSystemObject.FileExists(Server.MapPath(MyFile))=true Then
	Server.Execute(MyFile)
Else
	Response.Redirect("404.asp")
End If

Set FileSystemObject=nothing
%>

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...