Nov
12

Using GET data with PHP include()

Programming/PHP

Earlier today I thought I’d edit the title-page wallpaper script, and make it print friendly error messages. Previously it would just die in a very unhelpful way when an error was encountered. It didn’t occur to me before-hand, but my custom error handling script was very antiquated. For one, it had to be called with GET information.

This works well for .htaccess redirects and error documents (which was why I designed it this way a year or so ago), but it is a bad way of calling the error functions from within a running script. For one, PHP won’t allow you to pass GET values in the filename:

include('error.php?code=404'); // will not work

Since I didn’t have the time to overhaul the entire script, I checked for an easy work around. PHP recommends you use URL wrapping instead.

include('http://www.lazymoon.org/error.php?code=404');

But I didn’t like this idea, because if my host disables URL wrapping I’ll be left with broken scripts. Not to mention it takes longer to process.

The easy solution, for those who are interested, is just to set the GET information manually before including the file.

$_GET['code'] = 404;
include(’error.php);

This does the job nicely.

Monday, November 12th, 2007 @ 11:43 PM • Next Related Post

Responses

There are 9 responses for this post.
Comments are open, you can write a comment below.

cutemonster
February 20th, 2008 @ 05:51 PM

man, thank you so much!!!

Emanuel
March 6th, 2008 @ 06:27 AM

Good one! To logic to make sence : )

April 20th, 2008 @ 02:44 AM

Very helpful, thanks!

April 30th, 2008 @ 06:55 AM

Thankyou very much =), i was totally owned in this one :P

Endres
June 5th, 2008 @ 09:52 PM

Well, it will work too, if you load in the second PHP file the variable.
Example
(main.php):
$code=”404″;
include(”error.php”);
(error.php):
echo “Error Code “.$code;

June 8th, 2008 @ 11:45 PM

Thanks for this, very useful little trick :-)

k3dt
July 16th, 2008 @ 09:33 PM

many thanks!

July 21st, 2008 @ 07:54 AM

Haha, nice!!! Reading that post was one of those… “DUH! Of course!” moments. Thanks ;)

Jorge Contreras
August 21st, 2008 @ 03:16 AM

Hey ! That’s exactly what I was looking for. Thanks a lot!

Respond