Nested if, not exiting - create a function to call functions - php

I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}

A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.

If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.

If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.

Related

PHP user-defined function issue with if clause

I have created this emptyFields function in my functions.php file and I am using require_once to require functions.php in my validation.php file.
function emptyFields($n, $e, $p, $cp) {
$r;
if ( empty($n) || empty($e) || empty($p) || empty($cp) ) {
$r = true;
} else {
$r = false;
}
return $r;
}
Now, I am using this if clause in the validation.php file to check for any empty fields.
if (emptyFields($name, $email, $pwd, $cpwd) !== false) {
header("location: signup.php?errorid=emptyfields");
exit();
}
Note: Before forwarding input to the emptyFields function, I also use the inputSanitize function which is as follows.
function inputSanitize($n) {
$n = addslashes($n);
$n = htmlspecialchars($n);
$n = trim($n);
}
Apart from the above if clause, I also have other if clauses for email validation, password match etc.
THE PROBLEM: No matter what, It always executes this emptyFields function even when the input is properly provided. The next if clause in line, checks email format using another function, but it never gets executed. From my signup.php file, I input data and I get this query-string so I am assuming that only the emptyFields function gets executed.
location: signup.php?errorid=emptyfields
I have tried using multiple elseif but nothing changes. I have checked the form inputs' names to see whether there is any error in taking input from form but everything seems fine there too. I am using XAMPP.
Any help on this will be greatly appreciated. Thank you.
try below instead of you own, remove the "else" condition which create the conditional tree and slow down when you execute alot of code.
function emptyFields($n, $e, $p, $cp) {
$r = false;
if ( empty($n) || empty($e) || empty($p) || empty($cp) ){
$r = true;
}
return $r;
}

codeigniter returning false from models

Just wondering if it is necessary to use else {return false;} in my codeigniter model functions or if () {} is enough and it returns false by default in case of failure?
controller:
if ($this->model_a->did()) {
$data["results"] = $this->model_a->did();
echo json_encode($data);
}
model:
public function did()
{
//some code here
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
in your controller -- test the negative condition first - if nothing came back from the method in your model
if ( ! $data["results"] = $this->model_a->did() ) {
$this->showNoResults() ; }
else { echo json_encode($data); }
so thats saying - if nothing came back - then go to the showNoResults() method.
If results did come back then its assigned to $data
However - in this situation in the model i would also put ELSE return false - some people would say its extra code but for me it makes it clearer what is happening. Versus methods that always return some value.
I think this is more of a PHP question than a CodeIgniter question. You could easily test this by calling your model methods and var_dump-ing the result. If you return nothing from a method in PHP, the return value is NULL.
As much i have experience in CI returning false is not a plus point, because if you return false here then you need to have a condition back in controller which is useless you should be doing like this will save you at least some code of lines
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
so returning an array will save you from many other errors, like type error.

if statement running regardless of true false

I have tested each method individually with default values and it all seems to work. There is something going on when they are all mixed together.
Here is the code and i'll do my best to write it in an easy to follow way:
Starting with the controller:
if ($active['newcliq'])
{
$newcliqid = $this->create_m->create_keyword($cliq, $cliqid);
if (!$newcliqid) {
echo json_encode(array('success' => false));
} else {
$this->logic_m->change_active($newcliqid, $cliq);
}
}
$active['newcliq'] is true or false and pulled from userdata('active')
Of course, the next thing it runs is create_keyword($cliq, $cliqid) seen below:
$this->db->insert('cliq', $insert);
$newcliqid = $this->db->insert_id();
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
Again, I have checked it all manually, and I know that $newcliqid is returning the correct insert_id and the overall function is returning the correct value.
So $newcliqid is returned to the controller and goes runs logic_m->change_active seen below:
if (!$this->logic_m->cliqidcheck($cliqid)){
$cliqid = 6;
}
The above line is what is giving me problems. No matter what value, $cliqid is ALWAYS set to 6. Whether cliqidcheck returns true or false.
Here is cliqidcheck($cliqid)
public function cliqidcheck($cliqid)
{
if ((ctype_digit($cliqid)) AND ($this->checkcliqidexist($cliqid)))
{
return true;
} else {
return false;
}
}
I have tested cliqidcheck with manually entered values and it always returns the correct value. In addition, i've flat out removed the cliqidcheck from the change_active model and it works perfectly.
I also echo'ed the variable $newcliqid in the controller and found the correct value.
I am hoping this is just a simple problem that I'm overlooking. Thanks for the help! Please let me know if more info is required.
Instead of verbal explanations, wouldn't be it better to post either the debugging code
var_dump($cliqid);
$tmp = $this->logic_m->cliqidcheck($cliqid);
if (!$tmp) {
$cliqid = 6;
}
var_dump($tmp, $cliqid);
die;
and it's output.
Even without posting it here it will convince you that if statement actually never "running regardless of true false"
Setting full error reporting also helps (with finding typos and such)
ini_set('display_errors',1);
error_reporting(E_ALL);
Also a note on excessive code. This statement
if (condition)
{
return true;
} else {
return false;
}
can (and should, in my opinion) be shortened to
return (condition);
Same goes for insert id. Why not to make it just
return $this->db->insert_id();
without all that windy
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
which is actually a mere tautology

PHP Check Function

I have a check function:
function checkCandidateEmail($email)
{
$email = $_POST;
if($email)
{
$candemail = (SQL);
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
return $canEmailCheck;
}
}
I have started to create a function but I am getting NULL
function checkCandidateEmail($email)
{
$email = $_POST; // being immediately overwritten - redundant argument.
if($email) // Since $email isn't an optional argument, you'll get a PHP warning if it is missing, making this check confusing.
{
$candemail = (SQL); // Evaluating a constant? this will be bool
if(isset($candemail['email'])) // Since $candemail is a bool and not an array, this will never return true
{
return TRUE;
} else {
return FALSE;
} // this entire if/else block can be simplified to this: return (isset($candemail['email']));
return $canEmailCheck; // this is an undefined variable and will never get returned anyway because of the above return statements.
}
}
Please, elaborate more on your questions next time. I am not sure what you attempt to compare, if the $_POST with the SQL query or the argument passed with the SQL query. I assume the former.
If the email from that SQL table row equals the submitted email, returns TRUE. Else, returns FALSE. Really simplified version. Now it also checks if the user provided an email:
function checkCandidateEmail()
{
if (!$_POST['email']) echo "Error, please provide an email";
else
{
$candemail = (SQL); // Return a row from a query
return $candemail['email'] == $_POST['email'];
}
}
If an argument is passed, compares that against the database. If none is passed, compares the submitted $_POST['email'] against the database.
function checkCandidateEmail($email=null)
{
$candemail = (SQL); // Return a row from a query
if (!$email) $email = $_POST['email'];
return $candemail['email'] == $email;
}
NOTE: In both cases you have to substitute SQL for the right string and function depending on your database.
NOTE 2: Make sure that your query returns an email, as this simple code does not check if both strings are empty.

$_SESSION never getting set

I'm working on an assignment on a PHP course, and I'm stucked at the last part of it.
The assignment is to create a simple login form and use a session as well as hardcoded usernames and passwords (i.e. no db).
What I have problems with is the class that handles the login, and sessions especially. There's a lot of code and I didn't know what I could remove and therefore I've put it on Pastebin instead, hope that's alright.
Thing is that the unit tests that's built into the class passes except for nr. 4, the one that's checking that the user is logged in. The problem seems to be that $_SESSION[$this->loginSession] doesn't get set, and this is what I need help with.
The variable $loginSession is declared in the beginning of the class, and should be set to "isLoggedIn" when a user types a correct username and password, but that doesn't happen (no error message).
My class is:
<?php
class LoginHandler {
private $loginSession;
public function IsLoggedIn() {
if($_SESSION[$this->loginSession] == "isLoggedIn") {
return true;
}
else {
return false;
}
}
public function DoLogin($username, $password){
if ($username != null && $password != null){
switch ($username){
case "hello";
if ($password == "1234"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
case "hello2";
if ($password == "12345"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
}
}
else {
return false;
}
}
public function DoLogout(){
unset($_SESSION[$this->loginSession]);
}
public function Test() {
$this->DoLogout();
// Test 1: Check so you're not logged in.
if($this->IsLoggedIn() == true){
echo "Test 1 failed";
return false;
}
// Test 2: Check so that it's not possible to login with wrong password.
if ($this->DoLogin("hello", "4321") == true){
echo "Test 2 failed";
return false;
}
// Test 3: Check that it's possible to log in.
if ($this->DoLogin("hello", "1234") == false){
echo "Test 3 failed";
return false;
}
// Test 4: Check that you're logged in
if ($this->IsLoggedIn() == false){
echo "Test 4 failed";
return false;
}
return true;
}
}
?>
I hope it's enough to include the class and not all the other files, otherwise I'll put them up.
Now I see it :-)
$_SESSION[$this->loginSession] == "isLoggedIn";
== should be =
== compares while = sets
You need to start the session. session_start(); Place it at the very top of the documents (only one time on a page load) you are using.
$this->loginSession is never set so it's NULL
$_SESSION[null] is not possible as far as i know
change your code to
private $loginSession = 'testing';
and it should work
Why do you put semicolon in your case instruction case "hello";There should be a colon. case "hello": { ...instructions}

Categories