2016-07-16 41 views
1

我想要做以下但失败。

$user_id = $_REQUEST['user_id']; 

if (/* nothing to be requested*/) { 
    echo "<button>Log In</button><button>Sign Up</button>"; 
} else { 
    /* logged in, check if the user is an admin or not */ 
    if (/* he is admin */) { 
    echo "<button>Admin</button><button>Logout</button>"; 
    } else { 
    /* then he is just a normal user */ 
    echo "<button>Logout</button>"; 
    } 
} 

原始代码:

$user_id = $_REQUEST['user_id']; 
if (!$user_id) { 
    echo "<button>Log In</button><button>Sign Up</button>" 
} else { 
    $check_sql = "SELECT admin from users where user_id = {'$user_id'}"; 
    $result = mysqli_query($con, $check_sql); 
    $rows = mysqli_fetch_array($con, $result); 
     if ($rows['admin'] == 1) { 
     echo "<button>Admin</button><button>Log Out</button>"; 
     } else { 
     echo "<button>Log Out</button>"; 
    } 
} 

当有是$ _REQUEST为user_id,代码工作正常。但是当没有什么是$ _REQUEST时就会失败。你能帮忙吗?

非常感谢!

+0

把这个:如果(空($ user_ID的)) – bfahmi

+0

的使用,如果(空($ user_ID的)){} – JYoThI

+0

利用这一点,如果(isset($ user_ID的)!) – rajeev

回答

1

首先,请注意,您的代码容易受到SQL注入攻击。这非常严重。您应该使用参数化查询或转义$user_id变量。

http://php.net/manual/en/security.database.sql-injection.php

另外请注意,您的代码可能会受到别人设置$user_id自己,当他们不应该因此可能获得管理员权限。这是因为您使用的是$_REQUEST,这些值可以通过请求以您可能无法预料的方式设置。或者,您可以将user_id存储在$_SESSION中。

http://php.net/manual/en/ini.core.php#ini.request-order

http://php.net/manual/en/reserved.variables.session.php

至于支票$user_id,它应该是:

if(empty($user_id)) 

您可能还需要修剪$user_id

如果使用PHP < 5.5:

$user_id= trim($user_id); 
if(empty($user_id) 

如果使用PHP> = 5.5

if(empty(trim($user_id)) 

检查一个变量是否被认为是空的。一个变量是 ,如果它不存在或者其值等于FALSE,则认为它是空的。 如果变量不存在,则empty()不会生成警告。

http://php.net/manual/en/function.empty.php

+0

非常感谢Josh K,注射攻击事件将是我的下一步。再次感谢! – Kenny