Check if session data isset and apply error to each item - php

I have to do the following for a large amount of session variables, is there a way I can shorten this code to apply to all the variables rather than repeatedly writing out if(!isset($_SESSION['whatever'])) and adding the apropriate error to the errors array.
if(!isset($_SESSION['fiat'])) {
$errors[fiat] = 'Please enter valid amount';
}
if(!isset($_SESSION['contact'])) {
$errors[contact] = 'Please enter valid contact';
}
if(!isset($_SESSION['name'])) {
$errors[name] = 'Please enter valid name';
}
I have tried some things with for loops and arrays but am really struggling even after some serious googling, so any help much appreciated.
Thanks!
I have now made the following array but am unsure how to use it:
$errors = array(
$_SESSION['fiat'] => 'Please enter valid amount',
$_SESSION['contact'] => 'Please enter valid contact',
$_SESSION['name'] => 'Please enter valid name',
);
Do i do something like the following? Not sure what goes inbetween.
for(!isset($errors)){
}

What you can do is the following:
$errors = array();
// List all session parameters and error messages you want to check here
$valuesToCheck = array(
'fiat' => 'Please enter valid amount',
'contact' => 'Please enter valid contact'
// and so on...
);
// Loop through all values you want to check and validate it. if validation doesn't pass add error message to $errors array.
foreach ($valuesToCheck as $k => $v) {
if(!isset($_SESSION[$k])) {
$errors[$k] = $v;
}
}
// Check if after the validation array with errors is not empty then deal with it.
if (!empty($errors)) {
// Do something with errors here
}
PS: I think you should learn more about software development basics before start writing a code. This will be useful in your further career.

Related

Form Post Data As Array Value

I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.
I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.
Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}

Multiple IF statements in simple form validation

I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs

Concatenate two variables

Here's what I'm trying to do:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo $errmsg_.$error; //'Please make changes to your post';
Nothing will work, and there are many error messages like these ones that I have to echo.
Can anyone help?
What you're asking for is known as a variable variable -- see http://uk.php.net/manual/en/language.variables.variable.php for more info.
But please don't do that; it's considered very poor coding practice.
What you actually need is an array:
$errmsg = array(
'Please make changes to your post', //this will be $errmsg[0]
'Please make changes to your post image' //this will be $errmsg[1]
);
$error = 0; //nb: arrays start at item number 0, not 1.
echo $errmsg[$error];
That's much better coding practice than messing around with variable variables.
Store error messages in array:
$errmsg[1] = 'Please make changes to your post';
$errmsg[2] = 'Please make changes to your post image';
// and so on
$error = 1;
echo $errmsg[$error];
Try
echo {'$errmsg_' . $error};
Although you're doing this really rather incorrectly. You should be using an array instead; concatenating variable names is bad practice and leads to messy/unreadable/broken code. Using an array would work like this:
$errors = array(
'Please make changes to your post',
'Please make changes to your post image'
);
echo $errors[$error];
Although bear in mind that $error starts from 0 as arrays are 0-index based.
Off the top of my head I think you want $errmsg_{$error}, but I'm not in a position to test/double check that right now.
This should work:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo ${'errmsg_ ' . $error};
No offence meant but what you're doing is bad design.
A small but no means perfect solution would be store your errors as an Array.
$errors = array('Please make changes to your post', 'Please make changes to your post image');
$error = 0;
echo $errors[$error];
Try using this ${$errmsg_.$error}
This is a variable variable: http://php.net/manual/en/language.variables.variable.php
You're trying to do this:
function errorMsg($code)
{
$msg;
switch($code)
{
case 1:
$msg = 'Please make changes to your post';
break;
case 2:
$msg = 'Please make changes to your post image';
break;
}
return $msg;
}
echo errorMsg(1);
$error_msg = 'Please make changes to your ';
$error[1] = 'post';
$error[2] = 'post image';
for($i=1; $i<=count($error); $i++)
echo $error_msg . $error[$i];
Use arrays. keep the indexes for easy future reference, as well as easy error message changing and organized API.
$errmsg = array(
1 => 'Please make changes to your post',
2 => 'Please make changes to your post image'
);
$error = 1;
echo $errmsg[$error]; //'Please make changes to your post';

PHP Server Side Validation

Using various tutorials namely here and here I've managed to put together the following PHP script which performs server side validation on the form being submitted. (I already have script which is dealing with the 'client side' validation.
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address) VALUES ('$email')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
What I'm now trying to do is to add another field, in this case 'name' which I'd like to also validate.
The problem I'm having is that I'm not sure how to add another field into the above code. Again, I've been trying to find an example which I could use to study from, but I haven't found any that I can use.
I just wondered whether someone could possibly look at this please, and perhaps point me in the right direction.
Many thanks and kind regards
PHP has a Filter extension to validate and sanitize input.
The function you are looking for is
filter_var_array — Gets multiple variables and optionally filters them
There is also filter_input_array but since there is no easy way to unit-test that properly, it is easier to use the above one instead and pass it the superglobals as needed.
Example:
$userInput = array(
'signup-email' => 'foo at example.com',
'name' => 'ArthurDent42'
);
$validatedInput = filter_var_array(
$userInput,
array(
'signup-email' => FILTER_VALIDATE_EMAIL,
'name' => array(
'filter' => FILTER_VALIDATE_REGEXP,
'options' => array(
'regexp' => "/^[a-z ]{5,10}$/i"
)
)
)
);
var_dump($validatedInput);
Output (demo):
array(2) {
["signup-email"]=> bool(false)
["name"]=> bool(false)
}
Once you have the input validated and sanitized put some guard clauses for each of the values in the array and return early when they are false:
if (!$validatedInput['signup-email']) {
return json_encode(array(
'status' => 'error',
'message' => 'The eMail was invalid'
));
}
if (!$validatedInput['name']) {
return json_encode(array(
'status' => 'error',
'message' => 'Name must be 5 to 10 letters from A to Z only'
));
}
// everything's validated at this point. Insert stuff to database now.
Note that you want to use either PDO or mysqli instead of ext/mysql.
In your HTML add a field:
<input type="text" name="name" value="" />
In your PHP:
$name = trim($_POST['name']);
To validate:
if ($name === '') {
$status = 'error';
$message = 'need a name!';
}
Now add name to your insert statement (it would be better to use PDO prepared statements):
$nameSql = mysql_real_escape_string($name);
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, name) VALUES ('$email', '$nameSql')");
$rule['email']= '/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$`/'
$rule['name']= 'bla bla';
$rule['address']= 'bla bla';
$data = sanitize($_POST,$rule);
function sanitize($input_array,$rule){
$message = array();
foreach($input_array as $key=> $value){
$input_array[$key]= mysql_real_escape_string($value);
if(isset($rule[$key])){
if(!preg_match($rule[$key],$input_array[$key]){
$message[$key] = 'error';
unset($input_array[$key]);//optional
}
}
}
return array('data'=>$input_array,'message'=>$message);
}

Codeigniter form validation

Can I display a single message for the multiple form fields in CodeIgniter?
For example, I have set following rules for the email and password fields. I want to display only one message if any of these two fields is invalid. (eg. invalid email or password ")
$this->form_validation->set_rules('email_address', 'Email Address', 'valid_email|required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
How i can do that? Thanks for any help.
Edit: Sorry if my question is not clear. Currently I'm using validation_errors(), and i get errors of each field. However, I want to show a same error message if any of the two fields (email or password) is invalid. No matter if email is invalid, or if password is invalid, or both are invalid, it should print a single message, such as: invalid email or password.
I'm not sure if this is what you need, but you can try:
if($this->form_validation->run() == FALSE){
$message = 'Your error message here'; //validation_errors() works too.
}else{
$message = 'Your success message here';
}
$this->load->view('yourview',array('feedback_message'=>$message));
If you don't care which field isn't valid, then this snippet is ok. "Something is wrong, i don't care what's wrong, tell the user".
Iterate over each field and check using form_error(), add any invalid field names to a single error string:
if($this->form_validation->run() == FALSE){
$fields = array('email_address', 'password');
$invalid_fields = array(); //where we'll store invalid field names
foreach($fields as $field){
if(form_error($field)){
$invalid_fields[] = $field;
}
}
$data['error_message'] = 'The following fields are invalid: ' . implode(",", $invalid_fields);
}
$this->load->view('yourview', $data); //if !empty($error_message) in view echo it out
In your view you can just do this:
<?php if(!empty($this->form_validation->_error_array)): ?>
<p>There were some errors.</p>
<?php endif; ?>
$this->form_validation->set_message('rule', 'Error Message');
I think ,setting the same error message for both the rules will do the job ;)

Categories