Tuesday, September 21, 2010

$_GET, $_POST, $_REQUEST, $_FILE Made Easy

This may not be a new invention or secret but am gonna share it any way:

INSTEAD OF ALL THESE;
$day = (isset($_REQUEST['birth_day'])) ?$_REQUEST['birth_day'] : NULL;

YOU CAN NOW WRITE JUST THIS;
$rq = new requesthandler;
$day = $rq->get('birth_day');


USING THIS CLASS;

class requesthandler {
function get( $data )
{
return (isset( $_GET[$data])) ? $_GET[$data] : NULL;
}

function post( $data )
{
return (isset( $_POSt[$data])) ? $_POST[$data] : NULL;
}

function request( $data )
{
return (isset( $_REQUEST[$data])) ? $_REQUEST[$data] : NULL;
}

/*
* @param:
* $data = $_FILES['file']['name']
* @ret:
* Array
*/
function files( $data )
{
return (isset( $data)) ? $data : NULL;
}
}


Always remember though to unset your classes to free the object from memory. its not that required but its a good practice when you are going on larger projects. use this to unset
unset( $rq );

Wednesday, September 15, 2010

Dealing with errors while using headers in php (Headers Already Sent...)

OK, So am on this new project and am using a lot of headers (it was necessary) and I started to get the headers already sent issue. if you are a good PHP programmer you will immediately advice I get "echo" and all other similar things out of my code but you know sometimes its very important. check the code below. its not part of the codes I was writing its just an example for y'all to see how it's necessary sometimes;

if (is_resource($sql)) {
echo "your search came through with these results";
} else {
header ("Location: something.php?msg=error");
}
?>

In the above example you are displaying success on the same page and error on another page "something.php" with these parameters "msg=error" which is just how this application is to run.
In this example you may have the headers already sent error because you are echoing before a header is called into your code.

here is how to do it safely to avoid the header things;


ob_start();
if (is_resource($sql)) {
echo "your search came through with these results";
} else {
header ("Location: something.php?msg=error");
}
ob_end_flush();
?>

by using ob_start(); you now turn buffering on which prevents other types of output other than the headers found in your code. find a better explanation on Open Buffer Functions in PHP here
http://www.php.net/manual/en/function.ob-start.php

here is something to consider; by calling ob_end_flush(); you are closing all buffers which means outputs from your echo will start to give you bugs again. so whatever you do if you are going to use headers and echos just make sure you ob_start() at the very begining of your code and ob_end_flush() at the end.

Sessions however is a different thing and they usually require staying on top. so you may wnat to put ob_start() second should you ever use the two.

some kinda experience this was huh? well I shared it anyway... how was yours like?