Php variable accessed from class in another file empty - php

I am new to php and I am trying to program an app that uses php as backend. I don't really have an error in my code but I can't figure something out I have search but nothing has helped.there maybe be a solution but I can't find it.
I have 3 php file
Index.php
<?php
include "methods.php";
$user=new user();
if (isset($_GET["action"])) {
// code...
switch ($_GET["action"]) {
case 'login':
// code...
$user->login();
break;
default:
// code...
echo("error 404");
break;
}
} else {
// code...
echo("error 404");
}
?>
Methods.php
<?php
include "extra.php";
class user {
public function login() {
$input = new input();
$error = "fucked";
$validationresult = json_decode($input->validateinput(), true);
echo var_dump($validationresult);
$validated = $validationresult["validated"];
if ($validated) {
// code...
echo ("yes");
} else {
echo var_dump($validationresult);
// echo json_encode(($validationresult["error"]));
}
}
}
?>
extra.php
<?php
class input {
public $password;
public $status;
public $validated;
public function __construct()
{
// code...
}
public function validateinput () {
$password = $_GET["password"];
$this-> $status = "red";
$this->$validated = false;
echo($this-> $status);
return json_encode('{
"validated":'.$this->get_validate().',
"error":{
"status":"'.$this->$status.'",
"username":"ok",
"password":"cannot be more than 5"
}
}');
}
public function get_validate(){
return $this->$validated;
}
}
?>
As you can see in index.php I called $user->login();
From methods.php which echos JSON $input->validateinput() from file extra.php.
But
"validated":'.$this->get_validate().'
And
"status":"'.$this->$status.'
From extra.php
Is empty
I don't why it is empty and the internet confuses me more.
I am sorry for my grammatical mistakes as I am typing from a mobile phone and English isn't my first language.

Related

Class objects are passed by value?

I'm new to PHP. I'll like to check the scope of the variables I've used. In particular $model.
$model = new LoginModel();
$controller = new LoginController($model);
$view = new LoginView($controller, $model);
Attached below are codes I have written for logging in. A user would visit the page via GET /login.php then submits the form to POST /login.php?action=login. In this process the LoginModel is updated accordingly by LoginController.
I would like to use the $model that I have updated in later parts of the execution of the page. However, I noticed that $model is "reset" once the call returns from LoginController.login().
I'm not sure if it is because $model was passed by value in my case. Or if there is something else I'm doing wrong but I'm not aware of. Can anyone enlighten me on this?
<?php
class LoginModel {
public $username = "";
public $password = "";
public $message = "";
public $loginSuccess = false;
public function __construct() {
}
}
class LoginView {
private $model;
private $controller;
public function __construct($controller, $model) {
$this->controller = $controller;
$this->model = $model;
}
public function getUsernameField() {
return $this->makeInput("text", "username", "");
}
public function getPasswordField() {
return $this->makeInput("password", "password", "");
}
private function makeInput($type, $name, $value) {
$html = "<input type=\"$type\" name=\"$name\" value=\"$value\" />";
return $html;
}
}
class LoginController {
const HOME_URL = "http://localhost/";
private $model;
public function __construct($model) {
$this->model = $model;
}
public function login() {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === $password) {
$_SESSION['username'] = $username;
$model->username = $username;
$model->password = "";
$model->message = "Hello, $username!";
$model->loginSuccess = true;
header("Refresh: 3; URL=" + LoginController::HOME_URL);
} else {
$model->message = "Sorry, you have entered an invalid username-password pair.";
$model->loginSuccess = false;
}
}
public function handleHttpPost() {
if (isset($_GET['action'])) {
if ($_GET['action'] === 'login') {
$this->login();
}
} else {
// invalid request.
http_response_code(400);
die();
}
}
public function handleHttpGet() {
if (isset($_GET['action'])) {
// request for controller action
// No controller actions for HTTP GET
} else {
// display login page
}
}
public function redirectToHome() {
header("Location: " + LoginController::HOME_URL);
die();
}
}
$model = new LoginModel();
$controller = new LoginController($model);
$view = new LoginView($controller, $model);
if (isset($_SESSION['username'])) {
$controller->redirectToHome();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$controller->handleHttpPost();
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$controller->handleHttpGet();
}
?>
<html>
<body>
<?php if ($model->loginSuccess) { ?>
<h1>Login Successful, Redirecting...</h1>
<p><?= $model->message; ?></p>
<?php
} else { ?>
<form action="login.php?action=login" method="POST">
Username: <br />
<?php echo $view->getUsernameField(); ?> <br/><br/>
Password: <br />
<?php echo $view->getPasswordField(); ?><br/><br/>
<input type="submit" value="Log In"/>
</form>
<p><?= $model->message; ?></p>
<?php
}?>
</body>
</html>
Update: Solved. Thanks #RiggsFolly for pointing it out.
Well, I got the wrong$model.
public function login() {
....
$model->username = $username; //referenced the wrong variable
$this->model->username = $username //should have done this.
}
Also, Thanks #Fred -ii-
(sorry I left you out)
public function login() {
....
header("Refresh: 3; URL=" + LoginController::HOME_URL); //not the right way to concat
header("Refresh: 3; URL=" . LoginController::HOME_URL); //should have been this.
}
Only a simple statement
for because $model was passed by value
We have an object in $model and pass it to the constructor
$controller = new LoginController($model);
it will be bound as reference to
$controller->model = $model.
Now we have an reference of the model in the controller.
If you know do (if possible, lets say yes) this: unset($controller->model);
you dont have killed the $model instance, you have just removed the reference to $model that was set before.
But now the other way around:
#create an object
$model = new stdClass();
#create the holder
$b=new stdClass();
#bind the first obj
$b->model=$model;
#unset the first object
$model=null;
unset($model);
#oooh, what it is still there
print_r($b->model);
Here we have not unset($model) for real, because php knows that the instance is used later. So php goes and kills the reference between $model and the real object, but not the reference between $b->model and the real object.
In a way the reference has moved vom one ref-pointer to the next.
Last thing about
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function).
that comes from php documentaion.
When here is written passed by value it means, how it will work.
But in the real process, it will copied in the moment when it is manipulated.
so it is passed by ref but act like passed by value and only objects will be always an reference until clone.
To keep the most important Infos in this answer:
For one thing, header("Refresh: 3; URL=" + LoginController::HOME_URL);
you're trying to concatenate with a + which in PHP it's a dot that
needs to be used. You seem to be coming from a C background, hence the
error.
Thanks to Fred -ii-

Accessing variable inside a static function class

I have a login.php and authenticate.php
I want to access a variable inside the authenticate.php inside a class.
I want to get the error message from authenticate class to my login.php
This is my class inside Authenticate.php
Class Authenticate {
public $invalidUserErrMsg = "sdfs";
static public function LDAPAuthenticate() {
//connection stuff
} else {
$msg = "Invalid username / password";
$this->invalidUserErrMsg = $msg;
}
}
static public function invalidUserErr() {
echo $hits->invalidUserErrMsg;
return $this->invalidUserErrMsg;
}
}
This is how I'm printing inside login.php
<?php
$error = new Authenticate();
$error->invalidUserErr();
?>
Class Authenticate {
public $invalidUserErrMsg = "sdfs";
public function LDAPAuthenticate() {
if($hello) {
echo 'hello';
} else {
$msg = "Invalid username / password";
$this->invalidUserErrMsg = $msg;
}
}
public function invalidUserErr() {
return $this->invalidUserErrMsg;
}
}
<?php
$error = new Authenticate();
echo $error->invalidUserErr();
?>
Don't echo the variable within the class but echo the method on login.php. There is no need to make it a static function if you are going to instantiate the object anyway.
Check out this page on the static keyword
For accessing static function you need
<?php
$error = new Authenticate::invalidUserErr();
?>

PHP - What is wrong? Learning MVC - Beginner

Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}

Creating multilanguage homepage translating

Okay, so i got class file, in which i got function -
var $text;
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
}
If i am translating via index.php like this - > echo $index->translate('search'); it translates ok, but if i am translating something in class file for example -
if ($country_rows > 0)
{
$_SESSION['country'] = $_GET['country'];
}
else
{
$_SESSION['country'] = $this->translate('all_countries');
}
}
if ($_SESSION['country'] == '')
{
$_SESSION['country'] = $this->translate('all_countries');
}
it doesn't show up.
In index.php header i got included -
require_once('class.index.php');
$index = new index;
$index->get_country();
$index->languages();
What could be the problem, and how can i fix it, so i can translate everything inside class file too? will appreciate your help!
1st guess:
no session started?
session_start();
2nd guess:
assuming that you use $this->translate() in another class, you should initiate the object first, in the following example I pass translate class to var $index;
<?
include_once('class.index.php');
class myClass {
var $index;
public function __construct() {
$index = new index();
$index->get_country();
$index->languages();
$this->index = $index;
}
public function yourFunction() {
echo $this->index->translate('all_countries');
print_r($this->index);
}
}
?>

_forward() in Zend does not work?

Here is a code:
public function loginAction()
{
$form = new Application_Form_Login();
$this->view->form = $form;
if($this->_request->isPost())
{
self::$dataForm = $this->_request->getPost();
if($this->form->isValid(self::$dataForm))
{
return $this->_forward('authorization');
} else
{
$this->form->populate(self::$form);
}
}
}
public function authorizationAction()
{
if($this->_request->isPost())
{
$auth = Zend_Auth::getInstance();
$authAdapter = new Application_Model_User($this->user->getAdapter(),'user');
$authAdapter->setIdentityColumn('USERNAME')
->setCredentialColumn('PASSWORD');
$password = md5(self::$dataForm['password']);
$authAdapter->setIdentity(self::$dataForm['username']);
$authAdapter->setCredental($password);
$result = $auth->authenticate($authAdapter);
echo 'ok';
/*
if($result->isValid())
{
//$this->_forward('authorized', 'user');
echo 'ok';
}*/
}
}
Any idea why it does not work? I didn't get any error just blank page.
Shouldn't you be calling if($form->isValid(self::$dataForm)) ?
As far as I understand it is a bad idea to use the $this->_forward() as it calls the dispatch loop again.
Personally I would place the authorization code into a model class and pass it the username & password from the form.

Categories