A Multifunctional Jump Function Encapsulated by PHP Supporting HTML JS PHP Redirection

  • 2021-07-01 06:48:32
  • OfStack

The PHP jump, which redirects the browser to the specified URL, is a very common feature. This function also has 1 some detail requirements, such as how many seconds to wait for jumping, whether to use JavaScript to realize jumping, and so on. The following jump method takes many considerations into account and is parameterized, which can be used in specific projects.


<?php   
/**   
 *  Redirects the browser to the specified  URL   
 *   
 * @param string $url  To redirect  url   
 * @param int $delay  How many seconds to wait before jumping    
 * @param bool $js  Indicates whether to return the  JavaScript  Code    
 * @param bool $jsWrapped  Indicate return  JavaScript  Is it possible to use the  <mce:script type="text/javascript"><!-- 
  Label for packaging    
 * @param bool $return  Indicates whether to return the generated  JavaScript  Code    
 */    
function redirect($url, $delay = 0, $js = false, $jsWrapped = true, $return = false)     
{     
  $delay = (int)$delay;     
  if (!$js) {     
    if (headers_sent() || $delay > 0) {     
      echo <<<EOT     
  <html>     
  <head>     
  <meta http-equiv="refresh" content="{$delay};URL={$url}" />     
  </head>     
  </html>     
EOT;     
      exit;     
    } else {     
      header("Location: {$url}");     
      exit;     
    }     
  }     
    
  $out = '';     
  if ($jsWrapped) {     
    $out .= '<script language="JavaScript" type="text/javascript">';     
  }     
  $url = rawurlencode($url);     
  if ($delay > 0) {     
    $out .= "window.setTimeOut(function () { document.location='{$url}'; }, {$delay});";     
  } else {     
    $out .= "document.location='{$url}';";     
  }     
  if ($jsWrapped) {     
    $out .= ' 
// --></mce:script>';     
  }     
    
  if ($return) {     
    return $out;     
  }     
    
  echo $out;     
  exit;     
}    
?>


Related articles: