I am trying to implement error proofing to a log in script. But, I cannot get it to work? I have no idea what is going on, or why it doesn't work like I expect it to. I have tried everything, please advise.
This is the method I am calling:
public function i_exist($this_username)
{
//$host_array = null;
//$host_array = $this->collection->findOne(array("Username" => $this_username));
//if ($host_array['Username'] = $this_username)
//{
return true;
//}
//return false;
}
This is how I am calling it:
if (!empty($_POST['Username']))
{
$host = new Host();
$event = new Event();
if ($host->i_exist($_POST['Username']))
{
header("Location: http://www.drink-social.com/error.php?login=duplicate");
}
It is supposed to check the database and see if that username is already in use. But it never directs to the error page? I have even tried commenting everything out and returning true, and returning 1. Nothing?
Any advice?
When you call header(); you will also need to call exit(); otherwise the script continues running.
Related
I'm having some issues with a request from my boss.
I'm using the http://www.html-form-guide.com/ Registration forms he has created for use (I've attached the link just in case anyone want to use or look at it)
So I'm pretty new to PHP, but I've been gaining a crazy amount of knowledge.
Here is my problem - I need to make this form Register the user than Login Automatically. (This form has a Email confirmation system)
So I've managed to bypass the Email Confirmation and get the user to register, but I can't seem to figure out how to get auto login.
Here is what I've traced in the code:
function RegisterUser()
{
if(!isset($_POST['submitted']))
{
return false;
}
$formvars = array();
if(!$this->ValidateRegistrationSubmission())
{
return false;
}
$this->CollectRegistrationSubmission($formvars);
if(!$this->SaveToDatabase($formvars))
{
return false;
}
/*if(!$this->SendUserConfirmationEmail($formvars))
{
return false;
}*/
$this->SendAdminIntimationEmail($formvars);
$this->AutoLogin($formvars);// My call
return true;
}
This will pull in the name, email and password - put them in an array then send it off for validation and sanitation. I've placed a call function here.
After which I'll need to manually login with:
function Login()
{
if(empty($_POST['email']))
{
$this->HandleError("Email is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$email = trim($_POST['email']);
$password = trim($_POST['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
So I took the last portion of the login function and made:
function AutoLogin(&$formvars)
{
$email = trim($formvars['email']);
$password = trim($formvars['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
I did an echo $email; echo $password; exit; test and I can see that the email and password are appearing. But the "Session" (I think) is not starting or the Check Login is not getting the data.
function CheckLogin()
{
if(!isset($_SESSION)){ session_start(); }
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
Now I see the is a CheckLoginInDB which is:
function CheckLoginInDB($email,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$email = $this->SanitizeForSQL($email);
$pwdmd5 = md5($password);
$qry = "Select name, email, pagecode, welcome from $this->tablename where email='$email' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The email or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
$_SESSION['pagecode_of_user'] = $row['pagecode'];
$_SESSION['welcome_user'] = $row['welcome'];
return true;
}
What I can gather from this, its just a standard checking the database to see if this user exists and returning the results.
I've searching through stackoverflow and can't seem to see an answer to my problem.
I looked into Cookies, but I don't think that is something I really need here.
My questions are:
How can I make this bad boy start the session on registration?
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
Just in case here is the GetLoginSessionVar():
function GetLoginSessionVar()
{
$retvar = md5($this->rand_key);
$retvar = 'usr_'.substr($retvar,0,10);
return $retvar;
}
It's a pity I can't attached the file I'm working on, but if you need any further code snippets let me know and I'll be sure to Edit this straight away!
But the "Session" (I think) is not starting or the Check Login is not
getting the data.
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
It's not something wrong with the syntax, otherwise the code wouldn't even be compiled. Nevertheless I believe it's not the right idea.
You need to understand what's the problem before trying to fix it.
Debug the code. Use xdebug. If it's installed and active, you can use IDEs (e.g.: Visual Studio Code) to easily debug the code. Add breakpoints where you suspect there's something wrong.
If you don't want to use xdebug, you can add temporarily echoes or var_dumps to check if some areas of the code are processed and check some relevant values.
Also enable all errors reports and use a logger.
If the session is started after any output, there should be some warning.
Handle the errors and throw exceptions.
http://php.net/manual/en/function.error-log.php
http://php.net/manual/en/function.syslog.php
https://jtreminio.com/2012/07/xdebug-and-you-why-you-should-be-using-a-real-debugger/
session_start() works after output being sent
http://php.net/manual/en/function.error-reporting.php
You don't need to use the & in AutoLogin(&$formvars) if you're not changing the argument $formvars (you're just reading it).
You don't need to set session variables with all the user data. Create some structure (a class, an array, ...) with the user data outside those function and change those. AutoLogin should update that structure, something like this:
<?php
if (!$_SESSION) {
session_start();
}
$currentUser = array();
function getUserFromID($userID)
{
//TODO implement function
return $user;
}
function AutoLogin()
{
global $currentUser;
if(!empty($_SESSION['userID'])) {
return false;
}
$user = getUserFromID($_SESSION['userID']);
if (empty($user)) {
return false;
}
$currentUser = $user;
return true;
}
Maybe the session is not initialised before CheckLoginInDB is invoked (make var_dump($_SESSION); to check it). Use the $_SESSION only to save the user ID (or email) and read it to retrieve the user data.
The Overview
I've been experimenting some features which I've learn't using PHP, last night I was working on anonymous functions and for some strange reason when I var_dumped the function it kept returning null.
The Code
Below is the code I've written.
The findOrFail function,
public static function findOrFail($iD, $successCallback = null, $failCallback = null)
{
$db = new Database();
$db->select("users")->fields(["*"])->where(["id" => $iD])->execute("select");
if ($db->rowCount() == 1) {
if (is_callable($successCallback)) {
return $successCallback();
} else {
return true;
}
} else {
if (is_callable($failCallback)) {
return $failCallback($iD);
} else {
return false;
}
}
}
In test.php,
require_once "config.php";
var_dump(User::findOrFail(1, function () {
echo "Found.";
}, function ($iD) {
echo "Failed.";
}));
The Output
The ID 1 exsits so I expect the see when dumping string and the contents to be "Found." however I see this:
Found.NULL
What I have tried?
I looked at another question related to this issue and it said
that it was because of a buggy PHP version (5.3?). So I checked my
PHP version and it is 5.5.8.
I thought maybe because the default parameters ($successCallback and $failCallback) are set to equal null that that may be causing the error to occur. However some quick changes to the code (to remove the null) showed that it didn't fix anything.
So my question is, Why is it showing null? If anyone could shed some light on this issue it would be much appreciated.
Your anonymous functions don't return anything, they just call echo to print something. Use:
return "Found";
and
return "Failed";
I'm working on custom module and in my IndexController.php I'd written this function to add user to database
public function addAction() {
if($this->getRequest()->getParam('name', '') == ''){
$this->_redirect('etech/user');
//die; or exit;
}
$form = $this->getRequest()->getParams();
$user = Mage::getModel('test/test');
foreach ($form as $key => $val){
$user->setData($key, $val);
}
try{
$user->save();
}catch(Exception $e){
print_r($e);
}
$this->_redirect('etech/user', array('msg'=>'success'));
}
I want to prevent users from accessing this url directly as www.example.com/index.php/etech/user/add/. For this I'd made a check if($this->getRequest()->getParam('name', '') == ''){}. The redirect is working well except the code in there keeps executing and user sees a success message which should not be seen. For this, I'd used old fashioned exit or die to stop executing the code then it doesn't even redirect.
What is the magento way to handle it? Also, as I'm using getRequest()->getParams(), it return both parameters either in get or post. Isn't any way out to get only post parametrs?
It is correct to use $this->_redirect(), but you must follow it up with a return, ideally return $this;. You could also use exit or die, as you have been doing, but as I'm sure you know it would be better to let Magento do whatever it wants to do before redirecting you.
As long as you return immediately after $this->_redirect(), you won't have any issues.
Edit: And as for the request params question, I think you can call something like $this->getRequest()->getPostData() (that was false). The general convention is to use getParams() regardless of whether the data was sent via GET or POST, because technically your code shouldn't be concerned about that.
Edit #2:
If the general convention doesn't apply and you desperately need to restrict access to your page based on POST vs. GET, here's a handy snippet from Mohammad:
public function addAction()
{
if ($this->getRequest()->isPost()) {
// echo 'post'; do your stuff
} else {
// echo 'get'; redirect
}
}
I have a working Yii app on my local lamp stack. Now when I put the app on a lamp server the app reads the db and runs, but the app isn't successfully writing to the db. I'm getting no errors logs. Any thoughts?
Here's how I'm updating the db:
public function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
$model=$this->loadModel($uid);
$this->redirect($model->URL."?".$model->Unique_ID);
}
public function loadModel($uid)
{
$model=People::model()->findByPk($uid);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save();
} else {
$this->render('notice');
}
return $model;
}
The weird thing is, even when the db doesn't update the Login_Count and Last_Logged the user still gets redirected to their url, so the sql must be valid because the notice page never loads. Any thoughts?
Update + Solution
The problem ended up being that the mysql server had autocommit set to false. To override this at the app level add the following line to the config/main.php db array:
'db'=>array(
...
'initSQLs'=>array('SET AUTOCOMMIT=1',),
...
);
Yii: using active record with autocommit off on mysql server
The rendering of notice page doesn't stop your redirect. It might be rendered, but you won't be able to see it because of redirect. Try to refactor your code.
You're validating your model twice and the validation probably might be skipped since there's no data coming from App user.
You don't check if People model actually found.
There is CWebUser::afterLogin method which you can override to do this kind of stuff (update login count and last login date)
Maybe this way (quick fix) will work:
function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
if (null === ($model=People::model()->findByPk($uid))
throw new CHttpException(404);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->save()) {
$this->redirect($model->URL."?".$model->Unique_ID);
} else {
// echo CHtml::errorSummary($model)
$this->render('notice');
}
}
I'm newbie with webapps and PHP.
I'm trying to get a cookie that it's not created yet, I mean, when I try to load a page that looks for a non-existent cookie I get an error, I tried to get rid of this with a try/catch but not success. This this the code I'm trying:
try{
$cookie = $_COOKIE['cookiefoo'];
if($cookie){
//many stuffs here
}
else
throw new Exception("there is not a cookie");
}
catch(Exception $e){
}
How can I achieve this, any ideas, it would be appreciated it.
Use isset to prevent an any warnings or notices from happening if the key is non-existent:
if(isset($_COOKIE['cookiefoo']) && !empty($_COOKIE['cookiefoo'])) {
// exists, has a value
$cookie = $_COOKIE['cookiefoo'];
}
The same can be done with array_key_exists, though I think isset is more concise:
if(array_key_exists('cookiefoo', $_COOKIE) && !empty($_COOKIE['cookiefoo'])) {
// exists, has a value
$cookie = $_COOKIE['cookiefoo'];
}