2012-10-10 83 views
0

我正在使用標頭功能根據特定條件定位到另一個頁面。我正在監視一個郵箱,並且代碼將根據發件人地址重定向到另一個頁面。除一個標題外,所有標題都在運行如果發件人不屬於任何現有的羣組,我想將其重定向到new.php。但它不是重定向。我無法弄清楚爲什麼。請幫幫我。php重定向到另一頁

<?php 
session_start(); 

$server = '{server}INBOX'; 
$username = '[email protected]'; 
$password = 'password'; 
require_once '../swift/lib/swift_required.php'; 
include('connection.php'); 


$connection = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error()); 

$_SESSION['connection']=$connection; 

$result = imap_search($connection,'UNSEEN'); 
if($result) { 

    rsort($result); 

    foreach($result as $email_number) 
    {   

     $header = imap_headerinfo($connection, $email_number); 

     $fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host; 

     $query = "select * from usergroup where email='$fromaddr'"; 
     $_SESSION['fromaddr']=$fromaddr; 

     $result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error()); 


     while($line=mysql_fetch_array($result1,MYSQL_ASSOC)) 
     { 
      $email=$line['email']; 
      $group=$line['group']; 

      if(mysql_num_rows($result1) == 1){ 

       if($group == 1){ 
        header("Location: facilitator.php"); 
       } 
       elseif($group == 2){ 
        header("Location: learner.php"); 
       } 

      } 
      elseif (mysql_num_rows($result1) == 0) { 
       header("Location: new.php"); 
      } 

     } 
    } 

} 
elseif (!$result) 
{ 
    echo "No unread messages found"; 
} 


?> 
+1

請編輯並修復您的縮進。弄清楚你的嵌套是很麻煩的。 –

回答

3

它看起來好像是在while循環內嵌套該重定向。由於沒有行,因此條件mysql_fetch_array()將立即返回FALSE並跳過整個塊,包括您希望遵循的重定向。

mysql_num_rows()的測試移至while循環之外。

// Test for rows and redirect BEFORE entering the while loop. 
if (mysql_num_rows($result1) === 0) { 
    header("Location: new.php"); 
    // Always explicitly call exit() after a redirection header! 
    exit(); 
} 
// Otherwise, there are rows so loop them. 
while($line=mysql_fetch_array($result1,MYSQL_ASSOC)) 
{ 
    $email=$line['email']; 
    $group=$line['group']; 

    if($group == 1){ 
    header("Location: facilitator.php"); 
    } 
} 

實際上,你可能不需要while循環可言,這取決於你期望如何抓取幾行。如果您只希望每個電子郵件有一個組,則放棄循環,然後撥打$line = mysql_fetch_array()一次。但是,如果您期望多行但想要在遇到$group == 1處遇到的第一行時重定向,那麼您的邏輯起作用。然而,在這種情況下,由於您只做重定向而沒有其他操作,因此您可能只需將該條件放入您的查詢中:

// Test the group in your query in the first place. 
$query = "select * from usergroup where email='$fromaddr' AND group = 1"; 
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error()); 

if (mysql_num_rows($result1) === 0) { 
    // you didn't match a row, redirect to new.php 
} 
else { 
    // you had a match, redirect to facilitator.php 
} 
1

輕鬆一:

變化:

elseif (mysql_num_rows($result1) == 0){ 

到:

else { 

else if條件可能是假的 - 這樣你就不會在那裏得到和因此重定向不會發生。

+0

Nop。它不工作。 – faz