Reputation: 545
I'm trying to learn the object oriented side to php and keep hitting brick walls. One which is probably simply fixed but I can't figure out is why a variable variable passed back from a class function via URL will not echo to my page.
require_once('db.php');
require 'userclass.php';
$user = new user();
if(isset($_POST['submit'])){
if($user->login($_POST['username'], $_POST['password'])){
echo("poo");
}
}
include('db.php');
session_start();
class User{
public function login($username, $password){
$uname = $username;
$pass = $password;
header("location:index.php?uname=".$uname);
}
}
I think it might be something to do with my if condition logic?
Please point out any othwer stupidities on my part or non-common practices, I'd rather learn as much as possible while I'm at it rather than have just one solution. :)
Thanks!
Upvotes: 0
Views: 146
Reputation: 12889
Your class is defined with a capital letter. Use it.
$user = new User();
Your method does not return a value, and also tries to perform a redirect?
Your code that checks for a successful login is expecting a boolean value. You need to return true;
(or false). The code you have listed also doesn't contain any logic that checks if the username or password is valid, although I suspect this is intentional at this stage, since you are testing.
Why is there a redirect seemingly in the middle of nowhere?
When you want to redirect you also need to kill the script and prevent any further page output, otherwise the redirect will not happen.
public function login($username, $password){
if ($username == 'testuser' && $password == 'testpass') {
return true;
}
header("Location: index.php?uname=$uname");
die();
}
Other little niggles:
require
and require_once
are both statements and not functions. You are mixing a bracketed and non-bracketed syntax. It's preferable that you don't use brackets for statements.
You are passing $_POST['username']
straight back out in the Location header. While newer versions of PHP protect against header injection, it's a pretty bad idea to do this.
Upvotes: 2
Reputation: 2664
When you call $user->login(...)
it will send a header to go to another page.
It also does not return any valid value like true/false
...
Add a returned value and remove the header and I think that will solve your problem...
Upvotes: 0
Reputation: 3008
if($user->login($_POST['username'], $_POST['password'])){
would require some kind of return value for it to evaluate, and thus echo "poo";
would never happen, because you are then directed to a different page ?uname=, where $_POST is not set.
Login would need to return true IF certain conditions were met, and then I think the header location should probably be inside the index.php (if you are redirecting after a successful login.
Upvotes: 0