Waring: illegal string offset in 'name' in contactform since PHP7.1 - php

Since the update to php7.1 I get an error on a contactform. Downgrading is not an option. Any solution? I tried some thing I found, but doesn't seem to work what I change.
The message I get is "Warning: illegal string offset in 'name'" and it does this for all the values in the form (name, email, message,...).
<?php
require_once("classes/phpmailer/class.phpmailer.php");
$smarty_mail = new Smarty;
$smarty_mail->template_dir = 'templates/mail';
$smarty_mail->compile_dir = 'pages/templates_c';
if ( isset($_POST['submit']) )
{
$error = '';
print_r($error);
if (!trim($_POST['name'])) $error['name']=true;
if (!check_email($_POST['email'])) $error['email']=true;
if (!trim($_POST['message'])) $error['message']=true;
if (!isset($_POST['privacypolicy'])) $error['privacypolicy']=true;
$_POST['name'] = stripslashes($_POST['name']);
$_POST['message'] = stripslashes($_POST['message']);
if (!$error)
{
$contact = $_POST;
$contact['ip'] = $_SERVER['REMOTE_ADDR'];
$contact['host'] = gethostbyaddr( $contact['ip']);
$smarty_mail->assign("contact", $contact);
$message = $smarty_mail->fetch("mail_contact.tpl.html");
$subject = "contactformulier";
if( sendemail(MAIL_FROM_NAME, MAIL_FROM, $_POST['name'], $_POST['email'], $subject, $message, "HTML", "", ""))
{
$smarty->assign("send", true);
}
}
$smarty->assign("error",$error);
$smarty->assign("set", $_POST);
}
$main_content_template = "contact.tpl.html";
?>

$error = '';
makes no sense. You're initializing $error as a string, but then you're accessing it as if it were an array:
$error['name']=true;
It should probably be
$error = array();
instead.

Related

PHP validating multiple required input fields

I am validating some input fields before sending the email. I am using for each to loop through the array faster and check that every single input is not empty and return it as a response in jquery to show the errors. The problem is that email and message inputs are not being validated. Emails are being sent even if the inputs are empty.
the array elements come from the input name attributes from the html.
function e_($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
#required fields
$required = array('name', 'email','lname','message','country' , 'city' ,'adcategory','plan' ,'company');
$success = false;
#non required fields
$website = e_($_POST['website']);
$addr = e_($_POST['address']);
foreach($required as $field) {
if (empty($_POST[$field]))
{
$success = false;
}
else if(!empty($_POST[$field])){
$success = true;
$name = e_($_POST['fname']);
$email = e_($_POST['email']); #this has issue
$lname = e_($_POST['lname']);
$msg = e_($_POST['message']); #this has issue
$country = e_($_POST['country']);
$city = e_($_POST['city']);
$adCategory = e_($_POST['adcategory']);
$plan = e_($_POST['plan']);
$companyName = e_($_POST['company']);
}
}
if($success)
echo "success";
else if (!$success)
echo json_encode(['errors'=>true]); #this will be manipulated in jquery
The problem is that you set $success = true; whenever you find a required field, and this undoes the $success = false; for a previous field. You also process all the fields in the else if, even though that just means that one of the required fields was found.
$success = true;
foreach ($required as $field) {
if (empty($_POST[$field])) {
$success = false;
$missing_field = $field;
break;
}
}
if (!$success) {
echo json_encode(['errors'=>true, 'missing' => $missing_field]);
exit();
}
$name = e_($_POST['fname']);
$email = e_($_POST['email']); #this has issue
$lname = e_($_POST['lname']);
$msg = e_($_POST['message']); #this has issue
$country = e_($_POST['country']);
$city = e_($_POST['city']);
$adCategory = e_($_POST['adcategory']);
$plan = e_($_POST['plan']);
$companyName = e_($_POST['company']);
echo "Success";
Your foreach loop is wrong. You have your if statement that checks if it's not empty inside your for loop that checks if it's empty. You need to check to see if all the values are empty first then run that if statement.
$success = true;
foreach($required as $field) {
if (empty($_POST[$field]))
{
$success = false;
break;
}
}
if($success)
{
// set your variables
} else {
// don't set your variables
}

Fatal error: Cannot redeclare function for all functions

I think I have had a bug with a contact form which has been working for the last 2 months and now all of a sudden is says:
Fatal error: Cannot redeclare function (previously declared in...)
I have tried turning off the functions one by one but it just gives same error for next function down. My code is pretty standard. but, here it is (this is the beginning of the function. The code is long)
//Functions
function e($value)
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
//---------die dump function----------
function dd($data)
{
die(var_dump($data));
}
//Booking Page code (beginning)
<?php
require 'includes/config.php';
$name = $email = $date = $phone = $age = $tour = $message = '';
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = e($_POST['name']);
$email = e($_POST['email']);
$tour = !empty($_POST['tour']) ? $_POST['tour'] : '';
$phone = e($_POST['phone']);
$date = e($_POST['date']);
$age = e($_POST['age']);
$message = e($_POST['message']);
$errors['name'] = checkNameBooking($name);
$errors['email'] = checkEmailBooking($email);
$errors['tour'] = checkTourBooking($tour);
$errors['date'] = checktimeBooking($date);
$errors['age'] = checkAgeBooking($age);

How to fix variable declaration in PHP from a form submit

I am creating a registration page. Here is my PHP code:
<?php
$id = $name = $pwd = $confirm_pwd = $eamil = $phone = $dob = $region = $city = "";
$idErr = $nameErr = $passErr = $phoneErr = $emailErr = $message = $dobErr = $regionErr = $cityErr = "";
if(isset($_POST['submit'])) {
if (empty($_POST["national_id"])) {
$nameErr = "national id is required";
} else {
$id = test_input($_POST["national_id"]);
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["pwd"])) {
$passErr = "password is required";
} else {
$pwd = test_input($_POST["pass"]);
}
/* Password Matching Validation */
if($_POST['pwd'] != $_POST['confirm_pwd']){
$message = 'Passwords should be same<br>';
}
else {
$pwd = test_input($_POST["pwd"]);
}
if (empty($_POST["email"])) {
$emailErr = "email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["date_of_birth"])) {
$dobErr = "date of birth is required";
} else {
$dob = test_input($_POST["date_of_birth"]);
}
if (empty($_POST["region"])) {
$regionErr = "region is required";
} else {
$region = test_input($_POST["region"]);
}
if (empty($_POST["city"])) {
$cityErr = "city is required";
} else {
$phone = test_input($_POST["city"]);
}
}
else{
$con = new mysqli("localhost","root","","seis") or die(mysql_error());
$id = $_POST["national_id"];
$name = $_POST["name" ];
$pwd = md5($_POST["pwd" ]);
$email = $_POST["email" ];
$phone = $_POST["phone" ];
$dob = $_POST["date_of_birth" ];
$region = $_POST["region" ];
$city = $_POST["city" ];
$national_id = trim($id);
$cust_name = trim($name);
$cust_pwd = trim($pwd);
$cust_email = trim($email);
$cust_phone = trim($phone);
$cust_dob = trim($dob);
$cust_region = trim($region);
$cust_city = trim($city);
$processvalue = "Insert INTO Registration
VALUES ('$national_id' ,'$cust_name', '$cust_dob' ,'$cust_email' , '$cust_pwd' , '$phone' , (select region_serial,city_serial from cities where region = '$cust_region' AND city = '$cust_city') )";
if (mysqli_query($con, $processvalue)) {
echo 'You are registered ';
} else {
echo "error:" .mysqli_error($con);
}
}
mysqli_close($con)
?>
I am trying to insert each variable to an SQL statement, but it seems like I have a problem with variable initialization.
This is the error I get:
Notice: Undefined index: national_id in
C:\xampp\htdocs\seis-new\signup.php on line 68
Notice: Undefined index: name in C:\xampp\htdocs\seis-new\signup.php
on line 69
Notice: Undefined index: pwd in C:\xampp\htdocs\seis-new\signup.php on
line 70
Notice: Undefined index: email in C:\xampp\htdocs\seis-new\signup.php
on line 71
Notice: Undefined index: phone in C:\xampp\htdocs\seis-new\signup.php
on line 72
Notice: Undefined index: date_of_birth in
C:\xampp\htdocs\seis-new\signup.php on line 73
Notice: Undefined index: region in C:\xampp\htdocs\seis-new\signup.php
on line 74
Notice: Undefined index: city in C:\xampp\htdocs\seis-new\signup.php
on line 75 error:Table 'seis.registration' doesn't exist
you have to use isset() function to check variable index is set or not
function empty() check value. If you will give assoc array, then you need to have given key.
Check first, if value exist in given key by isset().
Simply check, if this request is not good practice.
Your IF statement should look like:
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST["national_id"]) || empty($_POST["national_id"])) {
// didn't provide field national_id or is empty
$errors[] = "national id is required";
} else {
$id = test_input($_POST["national_id"]);
}
}
if (count($errors)) {
// You have errors
}
First of all what have you done on 2nd and 3rd line too many variables equal? Can you please tell whats you intention doing so...
The reason you are getting undefined indexes because you have problem in your form. Check all the name attributes in your form and use that names as indexes in your $_POST['index'] method....
On your first line, you mispelled the variable you wrote $eamil and every other line is written $email fix this and check if it works, it probably will.
I recommend you to write your IF statements to check for empty fields like this:
if (!empty($_POST["national_id"])) {
$id = test_input($_POST["national_id"]);
} else {
$nameErr = "national id is required";
}
Also, your $convariable is connecting to the database using mysqli but then you wrote mysql_error. You must use mysqliall the time, otherwise it don't detect the table you wish. And I would take the comments advices to improve the entire code, it's a bit messy and there's a lot of stuff than can retrieve errors.
Obs: Reputation lower than 50, cannot comment yet.

array is showing empty not giving any value

I'm running function to check input empty but problem is that variable in array not working.
Here is my code:
$name = $email = $message = $result = "";
function has_presense($input){
if(empty($input)){
return $result = ucwords($input) ." is missing!";
}
}
if(isset($_POST['send'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$input = array($name,$email,$message);
foreach($input as $key => $value){
if(has_presense($key)){
$result = $value . "is missing";
}
}
}
Result:
Array ( [0] => [1] => [2] => )
it's showing empty array what is problem in it.
Description Make use of var_dump($_POST) or print_r($_POST) which will tell you what is in it if the form submission is successfully done.
The problem is that name, email, and message are empty.
Try:
var_dump($_POST);
to check if your the PHP is recieving everything.

Call to a member function verifyInput() on a non-object

It seems like a pretty common problem but I can't see to find the answer to my problem. I have been getting the dreaded "Call to a member function verifyInput() on a non-object" fatal error.
<?php
// empty values
$name = $email = $topic = $message = "";
$nameErr = $emailErr = $topicErr = $messageErr = "";
// link the name tags in HTML
$name = $_POST['name'];
$email = $_POST['email'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/* name if */
if (empty($_POST['name'])) {
$nameErr = " * Name is required";
} else {
$name = test_input($_POST["name"]);
}
/* email if */
if ( ! empty($_POST['email'])) {
if ($email->verifyInput($_POST['email'], 6)){
$fill['email'] = $_POST['email']; //$fill is the array of values passed
} else {
$emailErr = " * Email is incorrect - Try Again";
}
} else {
$emailErr = " * Email is required";
}
// Form content
$recipient = "generic#gmail.com";
$subject = "Contact Form";
$formcontent = "4 Days of Fun.ca -
\n\n\nFrom: $name \n\nEmail: $email \n\nSubject: $topic
\n\n\nMessage: $message";
$mailheader = "From: $email - Subject: $topic \r\n";
//function to send mail
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank you for contacting us, $name! \nWe will respond to you soon!";
}
//function for test_input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Validation of Inputs
function verifyInput($input, $type){
if ($type == 0) $pattern = '/^1$/';//just the number 1
elseif ($type == 1) $pattern = '/^[0-9]+$/';//just integers
elseif ($type == 2) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü]+$/';//just letters
elseif ($type == 3) $pattern = '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
elseif ($type == 4) $pattern = '/^[A-Za-zÁ-Úá-ú0-9àÀÜü\s()\/\'":\*,.;\-!?&#$#]{1,1500}$/';//text
elseif ($type == 5) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü0-9\']+[A-Za-zÁ-Úá-úàÀÜü0-9 \'\-\.]+$/';//name
elseif ($type == 6) $pattern = '/^.+#[^\.].*\.[a-z]{2,}$/';//e-mail
elseif ($type == 7) $pattern = '/^((\(0?[1-9][0-9]\))|(0?[1-9][0-9]))?[ -.]?([1-9][0-9]{3})[ -.]?([0-9]{4})$/';//brazilian phone
if (preg_match($pattern, $input) == 1) return true;
else return false;
}
?>
This is where the error is in question:if ($email->verifyInput($_POST['email'], 6)){ however I'm confused... I looked it up and everywhere states that the variable passed in ie $email may not be an object. But the variable is declared as an object here: $email = $_POST['email']; is it not? Or am I missing something big and obvious?
I just started learning PHP but I've got a lot of foundational knowledge with C++, so there are a lot of similarities I already get... This is not one of them.
Maybe I'm just not understanding the -> operator, or maybe it's a non-object because of something else?
Thanks in advance.
$email->verifyInput() would call the method (function) verifyInput() that is included in the class email, but here i can see that your function is not a member of any class, so if you need to call this fuction you just have to change:
if ($email->verifyInput($_POST['email'], 6)){...
to:
if (verifyInput($_POST['email'], 6)){...
And regarding your question about ->:
As i mentioned above -> is used after the instantiated class followed by the member or the method name. probably you need to read more about PHP, i would suggest this course, or you can jump directly to get a course about PHP OOP right here.

Categories