0

For the sake of learning no-framework php from scratch, I wrote an admin.php file which have the following code:

<?php

$not_auth_msg = "<h1>Not Authorized</h1>";
if($_GET['username'] == "admin") {
    $pass = md5($_GET['password']);
    if($pass != "21232f297a57a5a743894a0e4a801fc3") {
        exit($not_auth_msg);
    }
} else {
    exit($not_auth_msg);
}

?>

<!doctype html>
<html>
<head>
  <!-- link to bootstrap -->
  <!-- jquery script -->
  <!-- etc -->
</head>
..
..
..
</html>

Authorization works OK, but php 5.4's built in server replies "PHP Notice: Undefined index: username in ..." for each static file (bootstrap, jquery etc.), and the worse thing - the static files do not load!

What am I doing wrong?

hakre
  • 193,403
  • 52
  • 435
  • 836
user2057574
  • 779
  • 2
  • 8
  • 12

3 Answers3

2

Change the if with

if(isset($_GET['username']) && $_GET['username'] == "admin") {
...

}

That will solve your problem. When your not providing username that key is not set in $_GET and error notification if your php.ini file must be ALL i.e. notifications will be displayed/rendered.

  • So now I don't get an exception but the static files are not being loaded as before @user2129388 – user2057574 Mar 03 '13 at 18:30
  • 1
    It is because your using `exit()` in else block which will not render anything beyond that line of code. Put your `PHP` code after `` that will fix the issue. – user2129388 Mar 03 '13 at 18:37
  • I found the problem, it wasn't related to php's code location, I just had an extra "/" char in my path (see right after the php extension): admin.php/?username=admin&password=admin As for the exceptions, I'm using your answer and it works, thanks. @user2129388 – user2057574 Mar 03 '13 at 18:45
1

The notice is caused when you try to access an non-existant element in an array. In your case, the $_GET superglobal didn't actually have a 'username' element (meaning, you didn't pass a username through the url).

You can change your code to test for the existance of the element before you actually check its contents:

if(array_key_exists('username',$_GET) && $_GET['username'] == "admin") {
  ...
}

This works because PHP uses shortcut boolean evaluation - meaning the right side of that expression is not going to be evaluated if the left half turns out to be false.

Hazzit
  • 6,782
  • 1
  • 27
  • 46
0

see this line

if($_GET['username'] == "admin")

whenever you have empty / no value for $_GET['username'] you will get this error..you need to adjust your code so that you handle that case too, something like

if(!isset($_GET['username'])){

your code....to handle this index error
}else{

normal cose
}
Zaffar Saffee
  • 6,167
  • 5
  • 39
  • 77