Extra space/indent prepended to string being printed from php - php

I'm working on a REST api that people can download and throw on their server and use with little to no programming knowledge. https://github.com/evanstoddard/REST-Easy.
I'm using ajax for the setup page and php returns a string for ajax to see and decide whether to move on to the next step or tell the user to fix an error. It seemed to be working fine and then all of a sudden it won't go past the first step.
In my javascript I have the return value from php printed in my log. The first step is for the user to enter mysql server information such as the server url, username, and password. If a connection is created 'success' is returned. I appear to be getting ' success'. With a space or indent in there.
I commented out a lot of code I was working on before this error had occurred and the error is still there. I also added an extra indentation to my if block to check the return and the script succeeded so somewhere an extra bit is being added.
I don't really want to post my code here because there is A LOT of it and there are a bunch of moving parts which probably isn't the best way to go.
Here's a quick rundown of how this works:
User input(html form)->ajax->data handling php script->class_database.php(prints success->ajax->html
Applicable code:
Html:
<form onsubmit="stepTwo('#stepOneForm'); return false;" id="stepOneForm">
<input type="hidden" name="task" value="1" />
<input type="text" class="inputText" id="serverURL" name="serverURL" placeholder="MySQL Server:" /><br />
<input type="text" class="inputText" id="serverUsername" name="serverUsername" placeholder="Username:" /><br />
<input type="text" class="inputText" id="serverPassword" name="serverPassword" placeholder="Password:" /><br />
<input type="submit" class="blueButton" value="Connect" />
</form>
Javascript(AJAX):
function setupForm(form){
//console.log('Form function called.');
var formData = $(form).serialize();
$.ajax({
type: "POST",
url: "data/data_setup.php",
data: formData,
success: function(result) {
console.log(result)
function showAndTell(hide, show){
$(show).slideDown(600);
$(hide).delay(300).slideUp(600);
}
function showMessage(message, type, holdMessage){
var messageContainer = "#messageContainer";
var messageText = "#messageText";
var messageImage = "#messageImage";
var errorImage = "<img src='images/error.png' alt='Error' height='60px' width='60px' />";
var successImage = "<img src='images/success.png' alt='Error' height='60px' width='60px' />";
if (type === 'error'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(errorImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
else if(type === 'success'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(successImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
}
if(result === 'success'){
showAndTell('#stepOne', '#stepTwo');
showMessage('Successfully connected to MySQL database.', 'success');
}
else if (result === 'badaccess') {
showMessage('Unsuccessful. Please recheck information.', 'error');
}
else if (result === 'nserver') {
showMessage('Please enter a server URL.', 'error');
$('#serverURL').css('background', '#ffdadb');
}
else if (result === 'nserverusername') {
showMessage('Please enter a server username.', 'error');
$('#serverUsername').css('background', '#ffdadb');
}
else if (result === 'ndatabase') {
showMessage('No database with that name. Create it? Yes | No', 'error', true);
}
else if (result === 'database') {
showMessage('Successfully connected to that database.');
showAndTell('#stepTwo', '#stepThree');
}
else {
showMessage('Unknown error. Please try again later.', 'error');
}
}
});
}
PHP data handling script:
<?php
//Include rest class
require_once('../../classes/class_rest.php');
//Get variables
$task = $_POST['task'];
$database_server = $_POST['serverURL'];
$database_username = $_POST['serverUsername'];
$database_password = $_POST['serverPassword'];
$rest_name = $_POST['restName'];
$username = $_POST['username'];
$password = $_POST['password'];
$confPassword = $_POST['confirm'];
$emailAddress = $_POST['emailAddress'];
$api_name = $_POST['apiName'];
$database_name = $_POST['databaseName'];
$table_prefix = $_POST['tablePrefix'];
if ($task == 1){
if($database_server == ''){
print('nserver');
}
else if($database_username == ''){
print('nserverusername');
}
else{
connectSQL($database_server, $database_username, $database_password);
}
}
else if ($task == 2){
if($rest_name == ''){
print('nrest');
}
else{
databaseDoesExist($rest_name);
}
}
else if ($task == 3){
if($username == ''){
print('nuser');
die();
}
if($emailAddress == ''){
print('nemail');
die();
}
if(!$confPassword == $password){
print('nconf');
die();
}
insertUser($username, $emailAddress, $password);
}
else if ($task == 4){
}
else if ($task == 5){
}
else if ($task == 6){
}
else if($task == 9){
createInitialDatabase();
}
else if($task == 10){
createConfigFile();
}
?>
Function in class_database.php:
//Validates sql information
function connectSQL($server, $username, $password){
//Create sql connection
$con = mysqli_connect($server, $username, $password);
//Checks if connection was successful
if (mysqli_connect_errno($con)){
//Print 'badaccess' for ajax
print('badaccess');
}
//Run if connection successful
else{
//Print 'success' for ajax
print('success');
//Adds session variables for other sql commands later on
$_SESSION['server'] = $server;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
}

Few comments to your handling script:
* make sure there's no white space before the opening <?php and as well, nothing after the trailing ?> which, btw, can be omitted as well (did you know?).
* what about so called BOM in case of UTF-8 codified source codes? You may wanna choose an editor or editor setting that doesn't write BOM at the beginning of UTF files.
* instead of, print('badaccess'); you might use die('badaccess'); – it will print the argument and stop the script execution.
* at require_once (and directives alike) it's recommended to omit the parenthesis
* consider rewriting long if...else statement dealing with $task to one switch().

it's easy to unintentionally leak a space from php code (space before in any included file), try ob_start() at the begining of "PHP data handling script" and ob_end_clean() just before "print('success')" at connectSql

After the ?> in one of my classes, there was an indent and that's what was causing my problems... programming sucks sometimes.

Related

Strange Password_Hash Issue

So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>

How do I display the error messages in signup form?

How do I display the error messages (you did not complete all of the required fields and this username is already taken) without going to a new page to display them (like using die instead of echo), while still not continuing the process? In other words, I don't want the user to be sent to a new page to see "you did not...," I want the error to show either below or above the on this page, but I want the error message to disallow the data from being added to the database(the next command, or a couple commands down).
//if submit is clicked
if (isset($_POST['submit'])) {
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
} ?>
//if submit is clicked
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
elseif(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
else{
echo "code to submit values to database"
}
} ?>
Maybe you wanna use something like this javascript function to check for empty fields and not matching passwords (change variable names accordingly please as I took this from a little project I made):
function signup(){ //Call it on button click
var u = _("username").value;
var e = _("emailAddress").value;
var p1 = _("password").value;
var p2 = _("passwordConfirm").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Please, fill in every single field in the form...";
} else if(p1 != p2){
status.innerHTML = "The passwords do not match...";
} else if( _("terms").style.display == "none"){
status.innerHTML = "You must view our Terms & Conditions in order to proceed...";
} else { } //Redirect to a page or use Ajax to do other functions your site may need.
Notice var status = _("status");, this is where the messages will be shown on your page, you may want to add something like <span id="status"></span> to your HTML code.
Similarly to check for an available username or email on your database, you can try the following Ajax and Javascript function:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_con.php"); //database connection file
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']); //checks the texfield doesnt have any funny unusual characters
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1"; //change table name accordingly to yours
$query = mysqli_query($db_con, $sql);
$uname_check = mysqli_num_rows($query);
//This is just some extra conditions if you wish to add
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
//This if statement will check if the username is ok to use or is taken.
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
//////////// Javascript function, these can be on the same php file.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("usernamesats").innerHTML = 'Checking Availability...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("usernamesats").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Notice that for you to see the warnings your username textfield must look like this: <label>Username:</label>
<input id="username" type="Text" onBlur="checkusername()" maxlength="16">
This onBlur="checkusername()" will call the JS function.
and also add somewhere after the texfield this <span id="usernamesats"></span> to display the warnings. This should all do the trick. Oh and you may want to add the Ajax file:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
somewhere in your js folder (if you have one).
Sorry if this may be a bit long and confusing but it did the work for me, I'm sure there are other ways to do it, just thought these seemed easier to understand for me.
Check this website http://www.developphp.com/list_php_video.php for more info, there are some great tutorials there to get you started with PHP and MySQL, most of this code was done following the tutorials there :) Good Luck!

Using .Post() to pass a JQuery Variable to PHP

I am trying create an email subscription input box using JQuery, but for some reason, the inputted email addresses are not inserting into the MySql database, can anyone help me?
Here is the code I have in my newsletter.js file:
jQuery(function($){
var validateRegexps = {
email: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
"default": /.{4}/
}
if ($("#newsletter form").length == 0) return
var defaultMessage = $("#newsletter").attr("data-default")
var subscribedMessage = $("#newsletter").attr("data-subscribed")
var newsletterForm = $("#newsletter form")
/* newsletter code */
function newsletter(send) {
var subscribe = true
newsletterForm.find('input[type="submit"]').val(subscribe ? "Sign Up" : "Unsubscribe")
var email = newsletterForm.find('input[name="email"]')
var check = true
if (email.val() == defaultMessage || email.val() == subscribedMessage) {
email.val("")
if (!send) check = false
}
if (check) {
if(validateRegexps["email"].test(email.val())) {
// valid mail
email.removeClass("error")
if (send) {
$.post("php/newsletter.php",{add: email.val()}, function(data) {
email.val(subscribedMessage)
});
email.val("sending")
}
} else {
// invalid mail
email.addClass("error")
}
}
return false
}
function restore(e) {
var jqEl = $(e.currentTarget)
if (jqEl.val() == "") {
jqEl.val(defaultMessage)
}
return true
}
function signUp() {
return newsletter(false)
}
function signUpAndSend() {
return newsletter(true)
}
newsletterForm.find('input[name="email"]').focus(signUp).focusout(restore)
newsletterForm.change(signUp)
newsletterForm.submit(signUpAndSend)
});
Here is the code in my newsletter.php file:
require("config.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
$subsql = "INSERT INTO subscribe(email) VALUES(".$_POST['add'].");";
mysql_query($subsql);
And here is the code in my other php page to display the input box:
<div id="newsletter" data-default="youremail#yourdomain.com" data-subscribed="Thank you for subscribing.">
<form action="#" method="POST">
<input type="text" name="email" value="youremail#yourdomain.com" />
<input type="submit" value="submit" />
</form>
<h2>Sign Up to Our Newsletter!</h2>
</div>
Any help is greatly appreciated. Thank you very much in advance!!!
Hmm! Looking at your code does not directly point to any errors but the most obvious issue seems to be in the INSERT query that the email address isn't enclosed in single-quotes. Please draft your query like:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
Hopefully the above INSERT should work fine. If the issue still exists though, try finding out if the query might be generating any errors:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
mysql_query($subsql);
if (mysql_error()) {
echo mysql_error();
}
If no errors are found and the issue still exists, it might make sense to look into other basics, like:
Is $_POST['add'] available in "newsletter.php"?
Is MySQL connection correctly established in "newsletter.php"?
Is there any JavaScript issue that the POST request isn't send at all or perhaps send with an empty email address?
Hope this helps!

I can't return MySQL data

here is my JS code:
$.ajax({
url: 'login.php',
type: 'POST',
data: {
loginName: $("#loginName").val(),
loginPass: $("#loginPass").val()
},
dataType: 'json',
success: function(data){
if(data.success){
$("#Message").fadeIn(function(){
$(this).html(data.message);
});
}
else
{
$("#Message").fadeIn(function(){
$(this).html(data.message);
});
}
}
});
and here is PHP:
<?php
$data = array();
$data['success'] = true;
$data['message'] = "Here is the message";
echo json_encode($data);
?>
If i have this its be all right, but if i edit the php file to this:
<?
include "db.php";
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "" && $_POST['loginPass'] == "")
{
#$v = mysql_query("SELECT * FROM users WHERE name LIKE '$registerName'");
#$p = mysql_num_rows($v);
if ($p == 0){
#$v = mysql_query("INSERT INTO users VALUES('','$registerName','$registerPass')");
$data['message'] = "Byly jste úspěšně zaregistrováni.";
$data['success'] = true;
}
else
{
$data['message'] = "Tento uživatel je tu již zaregistrován.";
$data['success'] = false;
}
echo json_encode($data);
}
?>
The ajax do nothing... its just send data but nothing to the alert... :(
and i control this mysql events and its works if i use just php...
Firstly i would like to welcome back little Bobby Tables
Now down to business, look at the following line of code closely:
if($_POST['loginName'] == "" && $_POST['loginPass'] == "")
Next on the agenda, Your error suppression is incorrect, you should control your errors using error_reporting on your config file, and use an error_handler to log the errors for your application.
You should also note that your only responding with a result if certain conditions are met, I would advise you to respond regardless of what data or post method, supply an error message for every possibility, As in development stages this would make things a lot easier.
This is how i would write the code:
include "db.php"; //error_reporting(0);
$data = array();
$user_info = array_map("mysql_real_escape_string",$_POST);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($user_info['loginName']) && !empty($user_info['loginPass']))
{
$v = mysql_query(sprintf("SELECT * FROM users WHERE name LIKE '%s'",$user_info['loginName']));
if(mysql_num_rows($v) > 0)
{
//Update Here
//Output Success here/ json_encode
exit;
}
}
}
//Output Error here/ json_encode
Why are you supressing errors? It's not even being done correctly:
#$v = mysql_query("SELECT * FROM users WHERE name LIKE '$registerName'");
For one, there's no point in supressing errors on an assignment - an assignment will always succeed. Putting the # on the other side would be useless as well. You'd have absoultely no indication if the query blew up on you. You're not checking if it failed at all. The code should be:
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error());
}
Have you checked if your POST data is coming through properly? As it stands now, if neither of those POST fields is set, then your ajax response block is completely bypassed and the script will output nothing.

PHP and Function Errors

I was looking to see what would be the best way to handle errors from functions. Is the "DIE" method appropriate?
ie. php function calls another, for example:
function login(){
$result = verifyDetails("bob", "password123");
if($result == "accepted"){
echo "Welcome bob";
}else{
echo "Error!! \n";
echo $result;
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
die("cannot be empty");
}
if($user == "bob" && $pass == "password"){
return "accepted";
}else{
die("username or password incorrect");
}
}
does the "DIE" method return the message or does everything come to a standstill?
thanks in advance
UPDATE
what if the output is not known?
for example. in the above example I have placed "accepted" as the only correct answer.
What if the return is a name or id number.. then you cant really separate the error and correct returns.
thanks again.
UPDATE / Possible Solution
function login(){
$result = verifyDetails("bob", "password123");
if($result[0] == "SUCCESS"){
echo "Welcome bob";
}else if($result[0] == "ERROR"){
echo "Error!! \n";
echo $result;
}else{
echo "Unknown Error!!";
}
}
function verifyDetails($user, $pass){
$msg = array();
if(empty($user) || empty($pass)){
$msg[0] = "ERROR";
$msg[1] = "cannot be empty"
return $msg;
}
if($user == "bob" && $pass == "password"){
//say $customerID is extracted from a db
$msg[0] = "SUCCESS";
$msg[1] = $customerID
return $msg;
}else{
$msg[0] = "ERROR";
$msg[1] = "username or password incorrect"
return $msg;
}
}
ideas & suggestions on the above "possible" solution are welcome
UPDATE
Check Shikiryu update 2 answer below for a cleaner version using arrays
die() just echo your message and stop the script because die() is an alias of exit().
In your case, since the password isn't password but password123, the script will stop just displaying "username or password incorrect".
But as I can see here, you want a return "cannot be empty";, so that it'll display :
Error!!
username or password incorrect
(and optionally the rest of the html which die() won't)
Update 2 (ugly way) :
function login(){
$result = verifyDetails("bob", "password123");
if(isset($result['success']){ // verifyDetails return true?
echo $result['success'];
}else{
echo "Error!! \n";
echo $result['error']; // Display the error verifyDetails throws
// You may want to check if $result['error'] exists.
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
return array('error'=>"cannot be empty");
}
if($user == "bob" && $pass == "password"){
return array('success'=>"Welcome bob");
}else{
return array('error'=>"username or password incorrect");
}
}
die terminates the execution of the PHP script at the line it is called. Therefore, your message would no be returned.
You might want to simply use return instead of die;
Yes, you could use die() to debug.
does the "DIE" method return the message or does everything come to a standstill?
Yes, it returns the error message and yes, the script will stop continuing.
Well the only acceptable way in your case is return FALSE
if these functions are really methods of some class, use class variable to store actual errors.
if these functions belongs to no class, I wouldn't use them at all, but write it in plain code
if($user == "bob" && $pass = "password"){
echo "Welcome bob";
}else{
echo "incorrect username or password");
}
updated answer
Well there is nothing to invent. Just follow the way PHP goes:
Make your function return either value or FALSE
however, for the validation purpose you have to make it this way:
function validSomething($val){
return (bool)rand(0,1);
}
$err = array();
if (!validSomething($var)) {
$err[] = "Whatever error";
}
i.e. function returns only boolean values and actual error message being added by application logic.
However, in your example user-defined functions are totally misused.

Categories