error! got undefined variable if sent empty post - php

i got error message if sent empty post in my registration form
Notice: Undefined index: terms in /opt/lampp/htdocs/user/register.php on line 34
in the line 34 i have this
$terms = trim($_POST["terms"]);
and in the form i have this
<p>
<input type="checkbox" name="terms" id="terms"> I have read and accept the conditions of use
</p>
and this is all the validation form
if(!empty($_POST))
{
$errors = array();
$terms = trim($_POST["terms"]);
$captcha = md5($_POST["captcha"]);
$name = trim($_POST["name"]);
if($terms == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_NAME");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email,$name,$lastname);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
if($user->email_blocked) $errors[] = lang("ACCOUNT_EMAIL_BLOCKED");
}
else
{
//Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if(!$user->userCakeAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
}
?>
why i got this alert message?
thanks

Try to replace this:
if(!empty($_POST))
with this:
if(!empty($_POST["terms"]))
You need to make sure that array $_POST has a value with key terms
EDIT:
Try this:
$terms = empty($_POST["terms"]) ? null : trim($_POST["terms"]);
$captcha = empty($_POST["captcha"]) ? null : md5($_POST["captcha"]);
$name = empty($_POST["name"]) ? null : trim($_POST["name"]);
instead of this:
$terms = trim($_POST["terms"]);
$captcha = md5($_POST["captcha"]);
$name = trim($_POST["name"]);

It's not an error but a Notice and a notice can be ignored if it’s not critical..
if(isset($_POST['terms']))$terms = trim($_POST["terms"]);
isset() function in PHP determines whether a variable is set and is not NULL. It returns a Boolean value, that is, if the variable is set it will return true and if the variable value is null it will return false.
You can also turn off notices by using
error_reporting(E_ALL ^ E_NOTICE);
in the start of your script..

Related

Issue pushing an element in an array.(array_push)

I did this php code
<?php
if (!isset($_GET['id']) or !is_numeric($_GET['id'])) {
header('Location: index.php');
} else {
extract($_GET);
$id = strip_tags($id);
require_once 'config/functions.php';
$errors = array();
if (!empty($_POST)) {
extract($_POST);
$author = strip_tags($author);
$comment = strip_tags($comment);
if (empty($author)) {
$errors = array_push($errors, 'Entre a nickname');
}
if (empty($comment)) {
$errors = array_push($errors, 'Entre a comment');
}
var_dump($comment);
var_dump($author);
var_dump($errors);
if (count($errors) == 0) {
$comment = addComment($id, $author, $comment);
$sucess = 'Your comment has been sent';
unset($author);
unset($comment);
}
}
$article = getArticle($id);
$comments = getComments($id);
}
However, when I submitted the form I saw that every time the submission was successful so I decided to dump the variables $errors , $comment and $author to try to solve the issue. Here, the array $errors no matter what was empty. I tried not to put the comment or the author or even both but it still isn't working.
Could you help me out with this problem guys because I really don't know from where it comes from?
In PHP array_push() is a function which allows you to push multiple elements into the array, and the result of that function is the number of elements added. The array itself is passed as reference in the first argument.
However, you do not need to call this function.
Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.
You can just use the array append operator
if(!$comment) {
$errors[] = 'Entre a comment';
}
On unrelated note, you should never trust user input. Do not extract() your $_GET or $_POST super-globals!

php is not detecting all empty fields

I've got the following line of code in PHP at the top of the page making sure all form fields have content in them and not submitted empty...
if(!isset($_POST['name'])) { $err_name = 1; }
if (!isset($_POST['phone'])) { $err_phone = 1; }
if (!isset($_POST['email'])) { $err_email = 1; }
if ((!isset($_POST['serve'])) && ($_POST['other'] == "")) { $err_serve = 1; }
name is a text input
email is a text input
phone is a text input
serve is a checkbox array
other is a text input
Then below that I've got the following lines which allow the php code to continue if there are no errors (above)
if (($err_name != 1) && ($err_phone != 1) && ($err_email != 1) && ($err_serve != 1)) {
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$serve = $_POST['serve'];
$other = $_POST['other'];
Then I've got this next to each form field...
<?php if ($err_name == 1) { echo '<font color="red">Name cannot be empty</font>'; } ?>
<?php if ($err_phone == 1) { echo '<br /><font color="red">Phone cannot be empty</font>'; } ?>
<?php if ($err_email == 1) { echo '<font color="red">Email cannot be empty</font>'; } ?>
<?php if($err_serve == 1) { echo '<br /><font color="red">You must choose at least 1 area to serve</font>'; } ?>
Can someone please help me figure out WHY its doing the following...
if I take && ($err_serve != 1) out of the 2nd code, everything
except phone shows error messages
if I leave it in, ONLY err_serve throws error. The others are
ignored and no error is displayed.
Phone refuses to throw error messages. This is everything where $_POST
handling is in the php.
Note that all tests are done by submitting a completely empty form
The values will be set whether or not they are filled with a value. If it's an empty value, it's still a value.
Instead of using isset(), use empty(). It checks both if:
The value exists at all
The value is something other than 0, an empty string, false, etc.
The reason it works for the checkbox, is because when a checkbox is not checked, the browser does not send the value at all. This is contrary to text fields. A browser will send the value of a text field whether or not it's empty.
http://ca2.php.net/manual/en/function.empty.php

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';
}
?>

Troubleshooting "Undefined offset" error

It's show following error:
Notice: Undefined offset: 1 in C:\xampp\htdocs\evantechbd\secure\content\feature_link_process.php on line 28.
Why it's show the error...? Can anyone tell me... Here is the code:
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if(isset($coun)){
$errors = array();
if(empty($coun))
$errors[] = 'Country Name require<br>';
}
$row = explode("|", $_POST['coun_name']);
$coun_id = $row[1]; // cat_id
$coun_name = $row[0];
if $_POST['coun_name] has no | than $row[1] is not defined.
You will probably want to do something like this, instead:
$errors = array();
if( empty($_POST['coun_name']) )
{
$errors[] = 'Country Name required.';
}
elseif( strpos($_POST['coun_name'], '|') === false )
{
$errors[] = 'Country Name invalid.';
}
else
{
list($coun_name, $coun_id) = explode("|", $_POST['coun_name'], 2);
}
The first condition checks to make sure the user submitted a value for $_POST['coun_name']. The second condition checks to make sure that the value contains a '|' character.
If both conditions are met, $coun_name and $coun_id are populated by explode()'ing $_POST['coun_name'] as normal (I dropped in a call to list() for brevity).

Multiple conditions in PHP

I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>

Categories