PHP - Return array from function - php

I am submitting a form, using the following function (prize.php):
loadmodule('validate'); //This just loads the validate.php function.
$validate = new Validate;
if($_POST)
{
$validateForm = $validate->validateForm();
switch($validateForm)
{
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
}
die($error);
}
This is the function to validate the form (validate.php):
function validate()
{
global $userdata;
if(!is_array($userdata))
return 1; // User not logged in - return error code one.
//If no error, lets show a success message.
$prize = "100";
$text = "dollars";
return array("code"=>"100","prize"=>"$prize","type"=>"$text");
}//If won
}
The above code returns:
Notice: Undefined variable: error in /home/.../public_html/pages/prize.php on line 27
Although, it shouldn't throw an error there, since the die($success) should be triggered by the code 100.
What am I doing wrong?

$error = '';
$stop = false;
switch($validateForm){
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
}
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
first guess is that the if($validateForm['code'] == "100"){ is ment to be outside the switch.
$validateForm = $validate->validateForm();
returns an array.. later on your're doing a if ($validateForm==1) in the switch.. when $validateForm is an array.
you might have better luck with a simple is_array() if statement than the whole switch

Related

LAravel 505 error

This has been giving a
404 page error not found
and i don't know why.
public static function getGeneration($currentParent, $rootParent){
// dd($rootParent);
$user = User::where("username", $currentParent)->first();
$generation =[];
$x = 0;
$bool = true;
while ($bool) {
if($x==0){
$generation[$x] = (User::where("username", $user->sponsor_username)
->firstOrfail())
->sponsor_username;
}else{
$generation[$x] = (User::where("username", $generation[$x-1])
->firstOrfail())
->sponsor_username;
}
if( $x > 0 ){
if($news = $generation[$x] == $rootParent){
dd($news);
$bool = false;
}
}
$x++;
}
return $generation;
}
what this method basicaly does is go through a database and find out who brought a particular user into a system, because is user has a sponsor_username against it on the database, the last if statement is meant to stop when it discovers that it has reached the root user.

How can I show dynamic error message using PHP?

I have a html form and this form is validating by PHP with jQuery/Ajax request.
Currently it's working perfectly. Now I want to show a dynamic error message.
For e. g:
I am validating integer number using following function :
function only_number ($string) {
if( preg_match('/^[0-9]+$/', $string ) ) {
return true;
} else {
return false;
}
}
This function is implementing by following way :
$msg = array();
$msg['error'] = false;
if(empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} elseif( only_number($emp_id) === false ) {
$msg[] = 'Assign to must be numeric value';
$msg['error'] = true;
}
echo json_encode($msg);
You see that I am showing error message
Assign to must be numeric value
in the function implemented page e.g. update.php
It's very time consuming that I need to type several type of error message every time.
NOW, I want to write this error message in the function and it will show/implemented on validating page like : update.php page.
How can I do this ?
You can return array from your function. E.g:
function only_number ($string) {
$result = array(
'success' => false,
'error' => '',
);
if( preg_match('/^[0-9]+$/', $string ) ) {
$result['success'] = true;
} else {
$result['error'] = 'Assign to must be numeric value';
}
return $result;
}
And check:
if (empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} else {
$check = only_number($emp_id);
if ($check['success'] == false) {
$msg[] = $check['error'];
$msg['error'] = true;
}
}
In stead of returning true/false you can also return a string with the error message
function only_number ($string) {
if (empty ($string) return 'Select assign to';
if(!preg_match('/^[0-9]+$/', $string ) ) return 'Assign to must be numeric value';
else return 'no error';
}
next in your code
if (only_number($emp_id) <> 'no error') echo (json_encode(only_number($emp_id)));

I'm having issues with returning false values to functions in PHP

This is a sample of individual functions that validate form data from a request submission. A variable of true has been set and each function checks for validation requirements then either continues without returning anything or returns false and changes the $check value. The function down the bottom then checks if the $check value has changed to false and if it has the SQL statement will not be run.
$check = true;
function productNameValidation(){
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$check = false;
}
}
function checkProduct()
{
productNameValidation();
productGenreValidation();
productPriceValidation();
productEsrbValidation();
productThumbnailValidation();
releaseDateValidation();
return $check;
}
if($check == true)
{
//Insert into database
}
What you need to do is add different variables on different functions. If you are working this code to the method that it begins as true and is required to be checked and if the check fails then becomes false, try this method:
// $check = true;
function productNameValidation(){
$nameValidation = TRUE;
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$nameValidation = false;
}
return $nameValidation;
}
function checkProduct()
{
$checkProduct = true; ///true until proven false.
$checkProduct = productNameValidation();
//This code gives $checkProduct the boolean value returned
//from the function
$checkProduct = productGenreValidation();
$checkProduct = productPriceValidation();
$checkProduct = productEsrbValidation();
$checkProduct = productThumbnailValidation();
$checkProduct = releaseDateValidation();
return $checkProduct;
}
if($checkProduct == true)
{
//Insert into database
}
What I have done here is each function returns a TRue/False flag boolean variables which can be checked with an if(){ statement, you can run through numerous functions in this way checking each aspect you need. The important point is that you need to return a value from each function and you can set the booleans manually with initial settings which is then updated upon conditionals - such as setting $checkProduct = TRUE until it is FALSE from any sub function.
Global variables are really not a good idea in this case.
Edit: Thanks to #Edward for some clarification of boolean return code.
You can do something like that:
function productNameValidation(){
$check = true;
if(isset($_REQUEST['product_name']) && !empty($_REQUEST['product_name']) && preg_match("/^[A-Za-z0-9 :]*[A-Za-z0-9][A-Za-z0-9 :]{0,50}$/",($_REQUEST['product_name']))){
//then $valid['ID'] = "string: " . $_REQUEST['ID']
$valid['product_name'] = $_REQUEST['product_name'];
$err['product_name'] = "No errors";
//if not
} else {
if(empty($_REQUEST['product_name'])){
$valid['product_name'] = "No data entered!";
} else {
$valid['product_name'] = $_REQUEST['product_name'];
} //$err['ID'] = "error message"
$err['product_name'] = "Product Name must only contain letters, numbers and ':'!";
$check = false;
}
return $check;
}
if(productNameValidation()) {
....
}
You can return $check in your validation functions which will allow you to use the value of $check outside the function scope like this: $check = productNameValidation(). Another important note which I saw mentioned above: You should try to avoid the global scope as much as possible.
You can use check like a local variable not global, so in function.
Instead if you want it as a global, at the beginning of the function, you have to specify that you referring to
global $check;

PHP Authentication using text file

So i have fixed the problem with the loop by placing the ifelse statement outside the for loop. So when it is true it is working fine. However when FALSE i get the following error!
Notice: Undefined offset: 2 in webaddhidden.php on line 25 Invalid Login
I am new to PHP and am trying to make a simple login with a text file.
Error Message: if an incorrect username/password is entered :
Invalid LoginInvalid LoginInvalid LoginInvalid Login Notice: Undefined offset: 2 in webaddhidden.php on line 25 Invalid Login
and if the correct username/password the error is:
Invalid LoginMatch Found!
So it prints both the if and the ifelse statements.
Your help would be much appreciated.
Thanks!!!!
The code I am using is:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$matchFound = false;
$fileArray = array();
$myFile = fopen("customers.txt", 'r');
while(!feof($myFile) ) //reads all lines of text file
{
$fileArray[] = fgets($myFile);
}
fclose($myFile);
for($lineCounter = 0; $lineCounter < count($fileArray); $lineCounter++)
{
$exploadedLine = explode("\t",$fileArray[$lineCounter]);
if(trim($exploadedLine[2] == $username && trim($exploadedLine[3])
== $password))
{
echo 'Match Found!';
$matchFound = true;
break;
}
elseif($matchFound == false)
{
echo 'Invalid Login';
}
}
?>
This block of code is actioned as the file is searched - inside the loop.
elseif($matchFound == false)
{
echo 'Invalid Login';
}
It needs to be placed outside the loop.
Few things you can do to fix/improve your code:
You can use file() to directly read lines of text files into an array. http://www.php.net/function.file-get-contents
Make sure indexes of are set in exploded array using isset() function to avoid notices in case the text file is not formatted as expected. http://www.php.net/manual/en/function.isset.php
Move the logic block checking invalid login out of the loop so that it doesn't print invalid error message each time the loop finds a mismatch.
Try using the code below:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$matchFound = false;
$fileArray = file("customers.txt"); //reads all lines of text file
for ($lineCounter = 0; $lineCounter < count($fileArray); $lineCounter++) {
$exploadedLine = explode("\t", $fileArray[$lineCounter]);
if ((isset($exploadedLine[2]) && trim($exploadedLine[2]) == $username) &&
(isset($exploadedLine[3]) && trim($exploadedLine[3]) == $password)) {
echo 'Match Found!';
$matchFound = true;
break;
}
}
if ($matchFound === false) {
echo 'Invalid Login';
}
?>

php - return variable from function

I am trying to return a variable from a function. I have the function below, which inserts a postid to the database. I need the postid's value returned to another page.
forum.php - Where the function is.
function newTopic(){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
return $postid;
}
newtopic.php - Where I need the $postid variable.
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
As you can see, I am trying to use $postid variable from the function newTopic(). Although, the $postid variable is empty.
How can I get the value from the function newTopic.php located in forum.php, to newtopic.php?
When you have used
return 100;
your code will never see
return $postid;
You can use this code to return
return array("code"=>"100","postid"=>$postid);
Now in new_topic.php use the code as shown
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic['code'])
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$newTopic['postid']");
}
Your code looks that is returning value 100 before returning $postid variable.
That's wrong.Your code will exit the function at first return.
comment the line "//return 100;"
OR return an array. You cannot return two values like u do.
Instead of doing
return 100;
return $postid;
Do
//return 100;
return array("successs"=>100,"id"=>$postid);
Then use your $newTopic variable as folows:
In switch:
switch($newTopic['success'])
Use the postId anywhere else
$newTopic['id']
try with reference like in the below code
function newTopic(&$postid){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
}
....... //some codes
$postid = null;
newTopic($postid);
$my_postId = $postid; //Now you have your post ID
OR in you exists code like
if($_POST)
{
$last_postid = null;
$newTopic = $forum->newTopic($last_postid );
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
$postid = $last_postid;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
EDIT: Call-time pass-by-reference fixed.
If you want to return two values you can not just write two returns.
There are several options to return more values. One is using an array:
return array(100, $postId);
and
list($status, $postId) = $forum->newTopic();
You can also use an associatve array as s.d suggested.
However, as your one variable only contains the status you can also use exceptions in the case the operation fails.

Categories