how to handle a long URL with multiple $_GET?
i have a long url with multiple $_GET value, it looks like this : index.php?Category=music&Id=3211&Delete=yes and in the php file, i have a if condition like this :
if(isseet($_GET['Category']) && isset($_GET['Id']) && !isset($_GET['Delete'])){
echo 'Valid page';
}elseif(if(isseet($_GET['Category']) && isset($_GET['Id']) && isset($_GET['Delete'])){
echo 'delete !';
}开发者_Go百科
as you see, this is a very complicate if condition, when i have around 20 similar condition like this. and i want to know if we have some simple ways to do this, for example a SWITCH thank you
// if switch is true, check if all are set; if it's
// false check for none to be set. Defaults to true
function array_all_set($keys, $vector, $switch=true)
{
foreach($keys as $key)
if($switch == !isset($vector[$key]))
return false;
return true;
}
And now use it like this:
if(array_all_set(array("Category", "Id"), $_GET)
&& array_all_set(array("Delete"), $_GET, false)) {/* stuff */}
I know it's not much of an improvement with just 3 values, but for 20 values like you said, it's all about adding values to that array.
First of all, using code like this:
if(isseet($_GET['Category']) )
//do something...
That's wrong! you need to sanitize your input. But, I'll assume you already know that. Back to your problem, you should use a fairly more complex structure to handle your request variable, like for instance a dictionary, and then use it to validate your requests. An idea would be something like this:
class RequestDictionary
{
private $dictionary;
public function RequestDictionary()
{
foreach ( $_GET as $key => $value )
{
$this->dictionary[$key] => clean_var($value);
}
}
public function hasKeys($keys = array())
{
foreach ( $keys as $key )
if ( !isset( $this->dictionary[$key] ) )
return false;
return true;
}
}
And then, in your PHP pages you should make a method in your page to validate the requested Url, like this one:
function Validate()
{
$requestDict = new RequestDictionary();
return $requestDict->hasKeys(array('category', 'id', 'whatever'));
}
Your code should be very simplified. Remember that whenever you are coding many times the same snippet, something is not being abstracted. Sorry for the ultra-long answer, but I had to place most of the class so you may see it well,
Hope I can help! David
精彩评论