2011-07-04 64 views
0

對於使用此代碼這一刻:

if ($_GET['page'] == 'index' 
    and file_exists('./intl/tpl/' . $_GET['page'] . '.tpl') 
    or !file_exists('./intl/tpl/' . $_GET['page'] . '.tpl') 
    or !$_GET['page']) { 
//code 
} elseif ($_GET['page'] == 'multi' 
      and file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) { 
//code 2 
} 

等等...

問題1:此代碼是否 「好」?不需要任何轉義或什麼?

問題2:頁=註銷好好嘗試的工作,所以我創建logout.php它看起來像:

<?php 
require_once "./intl/config.php"; 
SessionDelete('logged_in'); 
SessionDelete('username'); 
SessionDelete('userid'); 
if ($user_admin != null) { 
    SessionDelete('inadmin'); 
    if (SessionGet('s_order') != null or SessionGet('s_page_show_all') != null) { 
     SessionDelete('s_order'); 
     SessionDelete('s_page_show_all'); 
    } 
} 
header('Location: '.$config['indexurl'].'index.php'); 
?> 

也許之前的會議中刪除不需要的會話啓動並有可能做到這一點與網頁=註銷? ?

+4

使用'&&'而不是'和'和'||'而不是'或' – pltvs

+0

我會爲此創建2個問題。有很多要討論你的第一個問題......從我可以看到你的代碼是次優的 – smcphill

+0

即時通訊這相當於使用更強硬的'和''或' – dynamic

回答

0

的代碼肯定可以改進:

  1. 重新排序測試,這樣就不會產生E_NOTICE錯誤
  2. 加上括號,使運算符優先級立即明顯
  3. 使用&&||布爾運算符(作爲加維的評論說)

這樣做,你會有:

if (empty($_GET['page']) || 
    !file_exists('./intl/tpl/' . $_GET['page'] . '.tpl') || 
    ($_GET['page'] == 'index' && file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) { 
//code 
} 
} elseif ($_GET['page'] == 'multi' && file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) { 
//code 2 
} 

然後,把它改寫了一些更要明確爲什麼你在做你做了什麼。這也可以讓你編寫更簡單的代碼。簡單很好。

// This way it's obvious that 'index' is the default page 
$page = !empty($_GET['page']) ? $_GET['page'] : 'index'; 

if (!file_exists('./intl/tpl/' . $page . '.tpl')) { 
    $page = 'index'; // comment here saying that if a non-existing page is requested, we display the index instead 
} 

$template = './intl/tpl/' . $page . '.tpl'; 

// At this point, we know that $page has a value, and we know that $template exists, so: 
switch($page) { 
    case 'index': 
     // code 
     break; 
    case 'multi': 
     // code2 
     break; 
} 

至於第二個問題:是的,你需要先啓動會話,然後才能修改或銷燬它。