Saturday, September 19, 2009

PHP: Simple register_globals workaround

Working with an old php4 project in php5 can expose some bad programming practices and create bugs. The first problem is relying on register_globals. I don't want to turn this on because it injects variables into the page scope. I also don't want to update the whole project to not rely on it.

The simple way around this is to write something that injects the variables into the project scope. This function will read all the variables from the url and inject them into the project scope. You should never rely on register_globals, but if you don't want to update old code this is an easy workaround.

function register_globals()
{
  //if register_globals is on then return
  if(ini_get("register_globals")) return;

  //inject URL vars into scope
  foreach($_REQUEST as $key=>$item)
  {
    $GLOBALS[$key] = $item;
  }
}

Labels: , , , , , , , ,

Wednesday, July 22, 2009

PHP: Error logging

Work with other languages has exposed me to new ways of logging errors and/or debugging code on web pages. I'm not sure how most php developers log errors or debug code so I can only guess it was similar to the way I would do it. By that I mean using echo in the middle of some HTML. It gets the job done, but it's kinda ugly.

I've since started using a cleaner method of logging errors. It's not as robust as a class, but it's better than throwing code out on a page. I've started using the error_log function wrapped in another function to control when it should output the error to a log.


function debug($allow_debug, $msg)
{
if($allow_debug)
{
error_log($msg."\n", 3, '/path/to/phperror.log');
}
}

When the function is used I pass a boolean that states wither I want the error passed out to the log. Typically I would set a variable at the top of the script and pass it into each instance of debug.

error_log takes three parameters. The first is the message that I want to pass out to the log. The important part on this input is the line return. That way each error starts on a new line. The second is the type of message I'm logging. The third is the location of the log file. Make sure it has the correct permissions so PHP can write to it.

You can view more information on error_log here.

Labels: , , , , , , ,

Wednesday, February 13, 2008

PHP: Code snippet

I found this on a page written in japanese. Great for streaming files through php and not reveling their source.
http://phpspot.org/blog/archives/2008/02/phpdlphp.html

header('Content-Type: application/octet-stream');
header('Content-Disposition: filename=dl.zip');
header('Content-Length: '.filesize('dl.zip'));
echo file_get_contents("dl.zip");
?>

This will also post the size of the file so you know how long it will take for it to download.

Labels: , , , , , , ,