Redircting to a page in PHP [duplicate]

夙愿已清 提交于 2019-12-14 04:24:23

问题


I am trying to make a redirect to page based on its referrer. the layout is like

<?php
$URL_REF = $_SERVER['HTTP_REFERER'];
if($URL_REF == "url of my site") {
    header("Location: url of another site"); 
    exit();
}
else    {
    header("Location: my home page"); 
    exit();
}

?>

I am getting the error : Cannot modify header information - headers already sent by.

I have to modify my php.ini to output_buffering = On but I can't do this as I have a shared hosting account in hostgator. can anyone suggest me what options now I have? can I do it by changing my code? If yes, than what changes?


回答1:


<?php
function custom_redirect() {
$URL_REF = $_SERVER['HTTP_REFERER'];
if($URL_REF == "url of my site") {
    header("Location: url of another site"); 
    exit();
}
else    {
    header("Location: my home page"); 
    exit();
}
}
add_action('init','custom_redirect');
?>

Try hooking your function to INIT HOOK




回答2:


Hi actually header("Location: url of another site"); will not support in wordpress. Instead of this you can use

<?php wp_redirect( 'http://www.example.com', 301 ); exit; ?>

and for home page just use <?php wp_redirect( home_url() ); exit; ?> this will solve your problem of redirection.




回答3:


try using javascript instead

<?php
$URL_REF = $_SERVER['HTTP_REFERER'];
if($URL_REF == "url of my site") {
   ?>
   <script type="text/javascript">window.location = "http://www.yoururl.com";</script>
   <?php
}
else    {
    ?>
     <script type="text/javascript">window.location = "http://www.anotherlocation.com";</script>
    <?php
}

?>

check the reference here




回答4:


Header Information already sent is a wordpress's common error, like as you mentioned you want to redirect the web site then you have to options to follow.

  1. Create a wordpress Template file do not call header in that file

    <?php /* Template Name:Redirect*/ ?> <?php //get_header();?> <!-- Do not un comment this function -->Write your code here Write your code here Write your code here Write your code here <?php get_footer();?>

  2. Or you can redirect with java script's window.location function

    <script>document.write(location.http://google.com); </script>



来源:https://stackoverflow.com/questions/19827795/redircting-to-a-page-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!