How to access variable value from another php script - php

I have read so many pages and am stuck on this for the past three hours now because it just won't work.
I keep getting Notice: Undefined index: firstname
here is the bulk of the segment that isn't working:
$errMsg = "";
function sanitise($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["firstname"]))
{
$firstname = $_POST["firstname"];
$firstname = sanitise($firstname);
if (!preg_match("/^[A-Za-z \-]+$/",$firstname))
{
$errMsg .= "First name must contain only letters or hyphens.<br/>";
}
if (strlen($firstname) > 40)
{
$errMsg .= "First name cannot be over 40 characters long.<br/>";
}
} else {
$errMsg .= "First name cannot be empty.<br/>";
$firstname = "";
}
if ($errMsg != "")
{
header("Location: fix_order.php?firstname=$firstname");
}
this is the code on fix_order.php where I want to access the variables.
$firstname = $_GET["firstname"];
echo "<p>firstname is $firstname .</p>";
I have tested the $firstname on the first page and it echo's the values just fine.

change your code to
$firstname = $_GET["errMsg"];
echo "<p>firstname is $firstname .</p>";
You can't access $firstname as this is the value not the key. errMsg is the key you should use.

Looks fine to me, it should work.
To get rid of the notice, you need to define variable by using isset()
$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
OR
if(isset($_GET['firstname'])) {
$firstname = $_GET['firstname'];
} else {
$firstname = '';
}

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
}

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.

trying to compare two email fields - page blanks out

Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}

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.

compare string got with $_POST with a string got from file.txt in php

I want to compare a string got with POST method with a string in a .txt file...if there is a match do action...I got this but it seems it can't pass the loop...it searches a match for the email and every third string in the .txt is an email string, this is why iterate by three...
<?php
$email = $_POST['user'];
$password = $_POST['pass'];
$filename = 'C:\xampp\htdocs\www\zavrsni\emailList.txt';
if (($row = file_get_contents($filename)) != '') {
$wordsArray = explode(' ', $row);
for ($i=0; $i<sizeof($wordsArray); $i+3) {
if (strcmp($wordsArray[$i], $email) == 0){
//some action
exit();
}
}
}
?>
<?php
/* content of emailList.txt
user_1 password_1 test1#default.com
user_2 password_2 test2#default.com
user_3 password_3 test3#default.com
user_4 password_4 test4#default.com
user_999 password_999 test999#default.com
user_5 password_5 test5#default.com
*/
// set POST for testing only!!
$_POST['user'] = 'test999#default.com';
$_POST['pass'] = 'test';
//
$email = $_POST['user'];
$email = strtolower($email);
$password = $_POST['pass'];
$filename = './emailList.txt';
// read entire file into an array, skipping empty lines and not adding return characters
$trimmed_file_array = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($trimmed_file_array AS $row) {
//print $row.'<br>';
list($f_user, $f_password, $f_email) = explode(' ', $row);
$f_email = strtolower($f_email);
if ($email === $f_email) {
print 'found user: '.$f_user.' - password: '.$f_password.' - email: '.$f_email.'<br>';
break;
}
}
?>

Categories