Kenny Kenny - 3 months ago 6x
PHP Question

When there is nothing to be $_REQUEST

I would like to do the following but fail.

$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>";

Original code:

$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>";

When there is a user_id to be $_REQUEST, the code works fine. But just fail when there is nothing to be $_REQUEST. Would you please help?

Thanks very much!


First, note that you code is vulnerable to SQL injection attacks. This is very serious. You should be using parameterized queries or escaping the $user_id variable.

Also note that your code may be vulnerable to someone setting the $user_id themselves, thus possibly getting admin privileges when they shouldn't. This is because you are using $_REQUEST and those values can be set by the request in manners you might not anticipate. Alternatively, you can store the user_id in $_SESSION.

As far as the check for $user_id, it should be:


You might also want to trim the $user_id.

If you are using PHP < 5.5:

$user_id= trim($user_id);

If you are using PHP >= 5.5


Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.