0

This is a dodgy question...

When requesting a page, the output of the page depends on the parameters passed. Soo:

http://localhost/test/php?key=value

AND

http://localhost/test/php?key=other_value

will produce different outputs.

There are a lot of these parameters and sometimes they are set, sometimes they are not.

I have this code block, that I keep copying over and over:

if ( !isset( $PARAMS["type"] ) ){
    $message = urlencode("No Type Parameter Defined In File {$_SERVER["PHP_SELF"]}");
    header( "Location: /admin/pages/{$PARAMS["page"]}?m=$message" );
    exit;
}

Now this code block is repeated in some cases about 6 times!

So I thought I could write a function:

function redirect_on_fail( $var ){
    if ( !isset( $var ) ){
        $message = urlencode("No Type Parameter Defined In File {$_SERVER["PHP_SELF"]}");
        header( "Location: /admin/pages/index?m=$message" );
        exit;
    }
}

OBVIOUSLY this will not work

Because I will have to call redirect_on_fail( $PARAMS["type"] ); and if it is not set, it wont be passed to the function...

Because I need to test whether the variable exists in the Pages Scope...

So I could just do this, I suppose:

function redirect_on_fail( $message, $redirect_to ){
    header( "Location: /admin/pages/$redirect_to?m=".urlencode($message) );
    exit;
}

But then in the page I'm doing:

if ( !isset( $PARAMS["type"] ) ){
    redirect_on_fail( "No Type Parameter", $redirect_to );
}

and that defeats the point...

So is there a way around this?

4

3 回答 3

1

我认为 gunnx 是在正确的轨道上。这是一些示例代码。只需根据需要更改$params数组中的值。

<?php

$params = array('foo', 'bar', 'baz');
foreach ($params as $param) {
  if (!isset($PARAMS[$param])) {
    $message = urlencode("No {$param} Parameter Defined In File {$_SERVER['PHP_SELF']}");
    header( "Location: /admin/pages/index?m=$message" );
    exit;
  }
}
于 2012-05-22T13:10:49.097 回答
1

$_GET是一个全局变量。您可以轻松地执行以下操作:

function redirect_on_fail(){
    if(!isset($_GET['type'])){
        // redirect
    }
}

因此,您始终可以在redirect_on_fail()任何定义的地方调用该方法。

于 2012-05-22T13:11:34.263 回答
1
function redirect_on_fail () {
  $args = func_get_args();
  $params = array_shift($args);
  foreach ($args as $arg) {
    if (!isset($params[$arg])) {
      $message = urlencode("No $arg Parameter Defined In File {$_SERVER['PHP_SELF']}");
      header("Location: /admin/pages/index?m=$message");
      exit;
    }
  }
}

// Call it like:
redirect_on_fail($_GET, 'required_key', `another_required_key`);
// Basically takes an array as the first argument, then the required keys as
// subsequent arguments, and redirects the user if any of them are not set.
// Pass as many required key names as you like.
于 2012-05-22T13:13:30.330 回答