Here is my code:
$order_newest = $order_votes = $order_featured = $order_frequent = '';
if ( isset($_GET['o']) || isset($_COOKIE['qanda_questions_order']) ) {
// To read from the cookie
if ( !isset($_GET['o']) ) {
$_GET['o'] = $_COOKIE['qanda_questions_order'];
} else {
setcookie("qanda_questions_order", $_GET['o'], 2147483647);
}
switch ($_GET['o']) {
case 'newest':
$order_newest = 'order_active';
break;
case 'votes':
$order_votes = 'order_active';
break;
case 'featured':
$order_featured = 'order_active';
break;
case 'frequent':
$order_frequent = 'order_active';
break;
default:
$order_newest = 'order_active';
break;
}
} else {
$order_newest = 'order_active';
}
As you see, I've initialized a supergobal on this line:
$_GET['o'] = $_COOKIE['qanda_questions_order'];
Is doing that a right thing? Or only should supergobals be used as passed parameters in the URL (get method) ?
Also can I write this logic more better? (seems Unprofessional to me a little bit)
Opinions vary, but in my opinion it is really bad practice to modify superglobals that are pre-filled by PHP. I always treat them as "read-only" variables (with the exception of $_SESSION
) myself, even though there's nothing stopping you from writing to them. I would personally use a variable for this:
if (isset($_GET['o']) || isset($_COOKIE['qanda_questions_order'])) {
$order = isset($_GET['o']) ? $_GET['o'] : $_COOKIE['qanda_questions_order'];
setcookie("qanda_questions_order", $order, 2147483647);
switch ($order) {
// etc.
}
}