简体   繁体   English

php重定向无法正常工作

[英]php redirect doesn't work properly

I got a simple redirect on my homepage, which reacts to the user being on a smartphone or tablett. 我的主页上有一个简单的重定向,它对智能手机或平板电脑上的用户做出反应。 The Class is working and gives back a true when the side is opened on a smartphone. 该类正在工作,并在智能手机上打开侧面时返回true。

Therefore if i write an echo in the if-statement it gets echoed. 因此,如果我在if语句中写回声,它就会被回显。 But the redirection doesn't work and i can't make a sense of it. 但重定向不起作用,我无法理解它。 Anyone any clue what i missed here? 任何人都知道我错过了什么?

include ('includes/Mobiledetecter.php');                 
$detect = new Mobiledetecter;                                  
                                 //
if($detect->isMobile() or $detect->isTablet()) {           
    header('Location: http://www.example.com/');
} 

Exit immediately after setting the header if there is nothing else to do: 如果没有别的办法,请在设置标题后立即退出:

if($detect->isMobile() or $detect->isTablet()) {           
    header('Location: http://www.example.com/');
    exit;
} 

Also consider that headers only work if you haven't already sent output to the browser, either explicitly (eg: echo ) or implicitly (eg: by having anything including blank space before the <?php tag that contains this header) 也可以考虑,如果你尚未向输出到浏览器标题只有工作,无论是明确的(如: echo )或隐含地(例如:通过使包括前空格什么 <?php包含此头标记)

Make sure your code is right at the very top of your Script before any output and also that your opening php tags has no white-space character(s) before it. 在任何输出之前确保你的代码在脚本的最顶层,并且你的开始php标签之前没有空白字符。 In essence, your script should look something like this: 从本质上讲,您的脚本应该如下所示:

<?php // NOTICE THAT THERE IS NO SPACE BEFORE <?php & NO ECHO BEFORE header(...)

    include ('includes/Mobiledetecter.php');                 
    $detect = new Mobiledetecter;                                  
                             //
    if($detect->isMobile() or $detect->isTablet()) {           
        header("Location: http://www.example.com/");
        exit;
    } 

Further to what everyone else is correctly saying that you can't both echo and do a server-side redirect, here's a way to say something and then redirect: 除了其他人都正确地说你不能同时回应并进行服务器端重定向之外,这里有一种说话然后重定向的方法:

include ('includes/Mobiledetecter.php');                 
$detect = new Mobiledetecter;                                  
                                 //
if($detect->isMobile() or $detect->isTablet()) {           
     echo "Redirecting you to the example website";
     echo "Click <a href='http://www.example.com/'>here</a> if you are not redirected within 5 seconds";        
     echo "<script> setTimeout(function () { window.location.href='http://www.example.com/'; }, 3000);</script>"
     exit;
} 

在标题之前尝试ob_end_clean函数: http//php.net/manual/fr/function.ob-end-clean.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM