duanpu8830 2012-08-02 13:10
浏览 38
已采纳

PHP类和返回变量

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.

index.php

require_once('db.php');
require 'userclass.php';
$user = new user();

if(isset($_POST['submit'])){
    if($user->login($_POST['username'], $_POST['password'])){
        echo("poo");
    }
}

userclass.php

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!

  • 写回答

3条回答 默认 最新

  • dongyu7074 2012-08-02 13:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)