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

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.

Related

Contact form white page of death

When I try to get my contact form working, my browser crashes and sends me a white page. I have found the reason, but I cannot understand what is wrong.
//getting fields
$naam = $_POST['naam'];
$email = $_POST['email'];
$adres = $_POST['adres'];
$postcode = $_POST['postcode'];
$telefoon = $_POST['telefoon'];
$iban = $_POST['iban'];
$15 = $_POST['15'];
$20 = $_POST['20'];
$25 = $_POST['25'];
$30 = $_POST['30'];
$anderbedrag = $_POST['anderbedrag'];
//message to webmaster
$message = $naam;
$message .= "jaarlijks bijdrage: ";
if ($15 != null){
$message .= '15,-';
}
if ($15 != null){
$message .= '20,-';
}
if ($15 != null){
$message .= '25,-';
}
if ($15 != null){
$message .= '30,-';
}
if ($anderbedrag != null){
$message .= $anderbedrag;
}
From the docs:
A valid variable name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores.
So your variable names aren't valid ($15 etc).
Besides that; always enable error reporting when developing. Php would have told you this.
ini_set('display_errors', 1);
error_reporting(E_ALL);

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.

My php mail function is sending blank messages

So as the title states I receive blank emails from my contact form. The php code is below. I've checked the value of $msg and it appears correctly, I've also googled a ton and I can't find anything standard cause that apply to me.
<?php
main();
function main() {
$posted = setVariables();
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
}
function setVariables() {
$name;
if (isset($_POST['name'])){
$name=$_POST['name'];
if ($name == null) {
$name = "ERROR - name is null";
}
}
$email;
if (isset($_POST['email'])){
$email=$_POST['email'];
if ($email == null) {
$email = "ERROR - email is null";
}
}
$enquiry;
if (isset($_POST['enquiry'])){
$enquiry=$_POST['enquiry'];
if ($enquiry == null) {
$enquiry = "ERROR - enquiry is null";
}
}
$message;
if (isset($_POST['message'])){
$message=$_POST['message'];
if ($message == null) {
$message = "ERROR - message is null";
}
}
$posted = array($name,$email,$enquiry,$message);
return $posted;
}
function setMessage($posted) {
$msg = "Name: " . $posted[0] . "\r\nEmail: " . $posted[1] . "\r\nEnquiry: " . $posted[2] . "\r\nMessage: " . $posted[3];
$msg = wordwrap($msg,70);
$msg = Trim(stripslashes($_POST['Message']));
return $msg;
}
function sendMail($msg) {
$result = mail("social#georgeappleton.co.uk","Contact From Portfolio",$msg, "From: <info#yourdomain.co.uk>");
return $result;
}
function userFeedback($result) {
if ($result == false) {
echo "Message failed to send, please inform me through my email address. social#georgeappleton.co.uk";
} else {
echo "Message Sent!<br/><br/>Returning you to <a href='http://www.georgeappleton.co.uk'>georgeappleton.co.uk</a> in 5 seconds";
}
echo "<script>setTimeout(function() {window.location = 'http://www.georgeappleton.co.uk';},5000);</script>";
}
?>
Thanks guys, appreciate it a lot
-Shardj
Get rid of this line:
$msg = Trim(stripslashes($_POST['Message']));
It's overwriting $msg with the contents of a nonexistent parameter. It already contains the message text, which was in $posted[3].
It's your variable scope. $name withing setVariables()
$name=$_POST['name'];
if (strlen($name) < 1) {$name = "ERROR - name is null";}
$email=$_POST['email'];
if (strlen($email) < 1) {$email = "ERROR - email is null";}
$enquiry=$_POST['enquiry'];
if (strlen($enquiry) < 1) {$enquiry = "ERROR - enquiry is null";}
$posted = array($name,$email,$enquiry,$message);
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);

Can't figure out how to format this logic statement in PHP

I have some PHP I'm using to validate a form, and once the validation is complete the data from the form is sent into a database. My problem isn't actually a code problem, it's just I can't figure out how to write the if-else statement blocks.
Basically I have all these if statements that check if one of the form fields is empty or doesn't meed the criteria, and then a corresponding else statement which simply holds the data they've entered, so when the form reloads they don't have to enter it in again. At the moment I have an else statement at the end which posts all the data into my database when all the fields are validated - the problem is that I have one too many else statements and it gives me errors for this.
So I figure I have to wrap the whole block of code in one if-else statement, that would basically say if there are no errrors, do the else which sends the data to the database.
Basically I have the else done, I just need help to think of what condition to put for the if
Here's my code
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
## Initialise varialbes to null ##
$nameError ="";
$emailError ="";
$categoryError ="";
$messageError ="";
$validName ="";
$validEmail ="";
$validMessage ="";
## On submitting form below function will execute ##
if(isset($_POST['submit']))
{
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$category = $_POST['category'];
//if name is less than 10 characters
if (empty($_POST["name"]) || strlen($name)<10)
{
$nameError ="* Name is too short";
}
else
{
$validName = $_POST["name"];
}
//if email is too short or is not the right format
if (empty($_POST["email"]) || !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email) || strlen($email)<10 )
{
$emailError = "* You did not enter a valid email";
$validEmail = $_POST["email"];
}
else
{
$validEmail = $_POST["email"];
}
//if a category is not chosen
if (empty($_POST["category"])) {
$categoryError = "* Please select a category";
}
//if the message is left blank
if (empty($_POST["message"]) || strlen($message)<25 ) {
$messageError = "* Your message is too short";
}
else {
$validMessage = $_POST["message"];
}
//If there are no errors, email details to admin
else {
// variables to send email
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $_POST[category] \r\n
Message: $_POST[message] \r\n
Name: $_POST[name] \r\n
Email: $_POST[email]";
// Email Function
mail($to,$subject,$body);
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
}
?> <!-- End of PHP -->
Essentially I need to figure out another if statement to put just after the first one, but for the life of me I can't think of a condition to have. I thought what if I made a boolean that was false, and once all the data is correct it is put to true, but I can't figure out how to implement it. Just looking for any ideas on how to go about it
When I do validation, I personally try to come up with a function that will validate each value similarly. There are a few checks you should be doing as you go. Here is a restructure of what you have with some notations:
<?php
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
// I usually build a simple validate function
// This is just an example, you can edit based on your needs
function validate_var($value = false,$type = 'str')
{
// Validate the different options
if(!empty($value) && $value != false) {
switch ($type) {
case ('str'):
return (is_string($value))? true:false;
case ('num') :
return (is_numeric($value))? true:false;
case ('email'):
return (filter_var($value,FILTER_VALIDATE_EMAIL))? true:false;
}
// This will just check not empty and string length if numeric
if((is_numeric($type) && !empty($value)) && (strlen($value) >= $type))
return true;
}
// Return false if all else fails
return false;
}
// On post, proceed
if(isset($_POST['submit'])) {
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
// Strip the message of html as a precaution
// Since you are not binding in your sql lower down, you should probably use
// htmlspecialchars($_POST['message'],ENT_QUOTES))
// or use the binding from the mysqli_ library to escape the input
$message = htmlspecialchars(strip_tags($_POST['message']),ENT_QUOTES));
// Do a "just-incase" filter (based on what this is supposed to be)
$category = preg_replace('/[^a-zA-Z0-9]/',"",$_POST['category']);
// Validate string length of 10
if(!validate_var($name,10))
$error['name'] = true;
// Validate email
if(!validate_var($email,'email'))
$error['email'] = true;
// Validate message length
if(!validate_var($message,25))
$error['message'] = true;
// Validate your category
if(!validate_var($category))
$error['category'] = true;
// Check if there are errors set
if(!isset($error)) {
// Use the filtered variables,
// not the raw $_POST variables
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $category \r\n
Message: $message \r\n
Name: $name \r\n
Email: $email";
// Don't just send and insert, make sure you insert into your databases
// on successful send
if(mail($to,$subject,$body)) {
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
else
echo 'An error occurred.';
}
else {
// Loop through errors cast
foreach($error as $kind => $true) {
switch ($kind) {
case ('name') :
echo "* Name is too short";
break;
case ('email') :
echo "* You did not enter a valid email";
break;
case ('category') :
echo "* Please select a category";
break;
case ('message') :
echo "* Your message is too short";
break;
}
}
}
}
?>

PHP Feedback form Checkbox error

Ok here is a shortened version of the php for my contact form, (the checkboxes are not being sent through correctly)
<?php
//please fill this in at least!
$myemail = "";
$title = "Feedback Form";
if(isset($_POST['submit'])) { //form has been submitted
//set variables with filters
$cont_name = filter_var($_POST['cont_name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['cont_email'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['cont_phone'], FILTER_SANITIZE_STRING);
$first_time = filter_var($_POST['first_time'], FILTER_SANITIZE_STRING);
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
function valid_email($str){
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;}
$errors = 0; //by default there are no errors
$trimcont_name = trim($cont_name);
if(empty($trimcont_name)){
//the name field is empty
$errors = 1; //tips off the error messages below
$errorcont_name = "The name field is empty"; //this error is displayed next to the label
}
if(!valid_email($email)) {
//email is invalid or empty
$errors = 1;
$erroremail = "The email address was not valid";
}
$trimphone = trim($phone);
if(empty($trimphone)){
//the phone field is empty
$errors = 1;
$errorphone = "The phone field is empty";
}
$trimfirst_time = trim($first_time);
if(empty($trimfirst_time)){
//the first_time field is empty
$errors = 1;
$errorfirst_time = "This field is empty";
}
$trimhear_about = trim($hear_about);
if(empty($trimhear_about)){
//the hear_about field is empty
$errors = 1;
$errorhear_about = "This field is empty";
}
if($spam != "") {
//spam was filled in
$errors = 1;
$errorspam = "The Spam box was filled in";
}
if($errors == 0) {
$sendto = $myemail;
$message = <<<DATA
DETAILS
Name: $cont_name
Email: $email
Phone: $phone
Was this the first time you have been to us?
$first_time
How did you hear about us?
$hear_about
DATA;
$headers = 'From: ' . $name . '<' . $email . '>';
if(mail($sendto, $title, $message, $headers)) {
//this is where it sends, using the php mail function
$success = true;
//set all the variables to blank to prevent re-submitting.
$cont_name = "";
$email = "";
$phone = "";
$hear_about = "";
$first_time = "";
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
And the area not functioning correctly is
<fieldset>
<legend>How did you hear about us? <span class="phpformerror"><?php echo $errorhear_about; ?></span></legend>
<div><input type="checkbox" name="hear_about[]" value="Web" /> Web</div>
<div><input type="checkbox" name="hear_about[]" value="Newspaper" /> Newspaper</div>
<div><input type="checkbox" name="hear_about[]" value="Radio" /> Radio</div>
<div><input type="checkbox" name="hear_about[]" value="Driving" /> Driving Past</div>
<div><input type="checkbox" name="hear_about[]" value="Referal" /> Referal</div>
<div><input type="checkbox" name="hear_about[]" value="Other" /> Other</div>
</fieldset>
At the moment it will only come through displaying one of the variables if multiple variables are selected.
hear_about is an array and filter_var() does not handle arrays correctly. Instead use filter_var_array():
$hear_about = filter_var_array($_POST['hear_about'], FILTER_SANITIZE_STRING);
Remember that $hear_about is an array, and must be treated like one throughout your code (e.g. just using $hear_about won't work, it needs to be $hear_about[0], $hear_about[1], etc).
So for example in your trim line you would need something like:
foreach($hear_about as $key => $value) {
$trimhear_about[$key] = trim($value);
if(empty($trimhear_about[$key])){
//the hear_about field is empty
$errors = 1;
$errorhear_about[$key] = "This field is empty";
}
}
This will preserve the benefits of dealing with an array.
$_POST['hear_about'] is an array of values. You are handling it as a simple string!
I think you can solve simply replacing the line:
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
With:
$hear_about = filter_var(implode(', ', $_POST['hear_about']), FILTER_SANITIZE_STRING);
The implode function (doc) "transform" an array to a string by concatenating the array values with the given glue. So you can just concatenate selected "How did you hear about us?" options with a comma and then use the resulting string as the other data.

Categories