PHP Undefined variable with POST [duplicate] - php

This question already has answers here:
Undefined index error PHP
(9 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
I am getting this...
Notice: Undefined index: cost, sku, costMethod
I think it is the validation part that is breaking this. I have tested sending these variables without the validation and they are received fine. I believe it is when everything is valid and the header gives it the destination is where it is losing the variables.
Here is my Form code:
<!DOCTYPE HTML>
<html>
<head>
<title>Shipping Overrides Client</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#additive").click(function(){
$("#cost").attr("value","0.00");
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$message = "SKU is required!";
$skuErr = "";
$sku = "";
$costErr ="";
$cost = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$valid = true;
if (empty($_POST["sku"]))
{$skuErr = "SKU is required";
$valid = false;}
else
{$sku = $_POST["sku"];}
if (empty($_POST["cost"]))
{$costErr = "Cost is required";
$valid = false;
}
else
{$cost = $_POST["cost"];}
if(isset($_POST['costMethod'])){
$costMethod = $_POST["costMethod"];
}
if($valid){
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
exit();
}
}
?>
<h1>Shipping Override Client</h1>
<form method="post" action="index.php" >
SKU: <input type="text" name="sku" value="<?php echo $sku ?>">* <?php echo $skuErr;?><br>
STD Shipping Cost: $ <input type="text" name="cost" id="cost" value="<?php echo $cost ?>">* <?php echo $costErr;?><br>
<input type="radio" name="costMethod" id="exclusive" value="Exclusive" checked>Override
<input type="radio" name="costMethod" id="additive" value="Additive" >Delete Existing Override <br>
<input type="submit" name= "submit" value="Submit">
</form>
</body>
</html>
Here is SubmitFeedSample.php:
<?php
$shippingCost = $_POST["cost"];
$sku = $_POST["sku"];
$costMeth = $_POST["costMethod"];
echo $shippingCost . "<br>";
echo $sku . "<br>";
echo $costMeth . "<br>";
var_dump($_POST);
?>
How can I get the variables to send when valid?

You are making a GET request here -
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
Try changing this -
<?php
$shippingCost = $_GET["cost"];
$sku = $_GET["sku"];
$costMeth = $_GET["costMethod"];
echo $shippingCost . "<br>";
echo $sku . "<br>";
echo $costMeth . "<br>";
var_dump($_POST);
?>

You cannot redirect with header once headers have already been sent:
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
That's why you are probably not getting the result there. Also that's not a proper way to fetch the post data. If you are passing arguments in URL like that you are using GET not POST.

Related

php function not being applied [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I have been following the w3schools php tutorial to produce a form. The form collects and displays data but none of the error checking is working. I have run the php and html through lint with no errors and double checked my use of quotes.
Specifically the script is not applying htmlspecialchars, trim or split. None of the regex checking is being applied and the error messages are not appearing. I tried replacing an error message with a simple if / not echo message and that worked, although the message was placed at the head of the web page, not next to the field.
I am also getting the following on execution.
Notice: Undefined index: numChild in /volume1/homes/richard/www/action.php on line 22
Line 22 is:
$totalGuests = $_POST['numAdults'] =+ $_POST['numChild'];
The difference between this and other undefined index questions is that the function 'test_input' is not being applied. I have included #Poiz suggestion below and this resolves the undefined index problem but the function is still now working.
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// define variables and set to empty values
$guestName = $guestEmail = $guestPhone = $startDate = $endDate = $numAdults = $numChild = "";
$guestNameErr = $guestEmailErr = $guestPhoneErr = $startDateErr = $endDateErr = $numAdultsErr = $numChildErr = "";
$maxAllowed = 4;
$totalGuests = $_POST['numAdults'] =+ $_POST['numChild'];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['guestName'])) {
$guestNameErr = "guestName is required";
} else {
$guestName = test_input($_POST['guestName']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$guestName)) {
$guestNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['guestEmail'])) {
$guestEmailErr = "Email is required";
} else {
$guestEmail = test_input($_POST['guestEmail']);
// check if e-mail address is well-formed
if (!filter_var($guestEmail, FILTER_VALIDATE_EMAIL)) {
$guestEmailErr = "Invalid guest email format";
}
}
if (empty($_POST['guestPhone'])) {
$guestPhoneErr = "Phone number is required";
} else {
$guestPhone = test_input($_POST['guestPhone']);
// check if phone number is UK format and valid
if (!preg_match("/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/",$guestPhone)) {
$guestPhoneErr = "Please enter a valid phone number";
}
}
if (empty($_POST['startDate'])) {
$startDateErr = "Start date is required";
} else {
$startDate = $_POST['startDate'];
}
if (empty($_POST['endDate'])) {
$endDateErr = "Start date is required";
} else {
$endDate = $_POST['endDate'];
if ($_POST['endDate'] < $_POST['startDate']) {
$sendDateErr = "End date must be before start date";
}
}
if ($totalGuests > $maxAllowed) {
$bookingErr = "A maximum of 4 guests can be accommodated at Mariner's Loft";
} else {
$numAdults = ($_POST['numAdults']);
$numChild = ($_POST['numChild']);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<br><input type="text" class="form-control" id="guestName" name="guestName" value="<?php echo $guestName;?>" placeholder="Full name" autofocus required>
<br>
<br><input type="email" class="form-control" id="guestEmail" name="guestEmail" value="<?php echo $guestEmail;?>" placeholder="email">
<br>
<br><input type="phone" class="form-control" id="guestPhone" name="guestPhone" value="<?php echo $guestPhone;?>" placeholder="Phone number">
<p><strong>How many guests?</strong></p>
<p>How many adults?</p>
<br><input type="text" class="form-control" id="numAdults" name="numAdults" value="<?php echo $numAdults;?>" placeholder="number of adults">
<p>How many children?</p>
<br><input type="text" class="form-control" id="numChild" name="numChild" value="<?php echo $numChild;?>" placeholder="number of children">
<br>
<br><input type="date" class="form-control" id="startDate" name="startDate" value="<?php echo $startDate;?>" placeholder="Arrival date">
<br>
<br><input type="date" class="form-control" id="endDate" name="endDate" value="<?php echo $endDate;?>" placeholder="Leaving date">
<br><br>
<input type="submit" name="submit" value= "Submit"/>
<br><br>
<input type="reset" name="submit" value="Cancel"/>
</form>
<?php
echo "<h2>Guest info:</h2>";
echo $guestName;
echo "<br>";
echo $guestEmail;
echo "<br>";
echo $guestPhone;
echo "<br>";
echo $totalGuests;
echo "<br>";
echo $startDate;
echo "<br>";
echo $endDate;
?>
</body>
</html>
Any help gratefully received.
The Code $totalGuests = $_POST['numAdults'] =+ $_POST['numChild']; should be moved into the Conditional Block or redeclared to have a Default: (1, for example)...
$maxAllowed = 4;
$totalGuests = ( isset($_POST['numAdults'] ) &&
isset($_POST['numChild']) ) ?
( $_POST['numAdults'] + $_POST['numChild'] )
:1;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// REST OF THE CODES
}

PHP form not recognizing code on localhost but works on online hosting [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I have this php form processing code downloaded from php form guide site
The code works perfectly without any errors on my hosting space.
But if i try to run on xampp localhost, its not recognizing the fields. and giving this error:
Notice: Undefined variable: varMovie in C:\wamp64\www\form\myform2.php on line 88 Call Stack #TimeMemoryFunctionLocation 10.0007248808{main}( )...\myform2.php:0
Can anyone help me in this? I'm pasting the php code:
<?php
if (isset($_POST['formSubmit']) && $_POST['formSubmit'] == 'Submit')
{
$errorMessage = "";
if(empty($_POST['formMovie']))
{
$errorMessage .= "<li>You forgot to enter a movie!</li>";
}
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter a name!</li>";
}
if(empty($_POST['formGender']))
{
$errorMessage .= "<li>You forgot to select your Gender!</li>";
}
$varMovie = $_POST['formMovie'];
$varName = $_POST['formName'];
$varGender = $_POST['formGender'];
if(empty($errorMessage))
{
$db = mysql_connect("loclhost","root","admin");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("my_db" ,$db);
$sql = "INSERT INTO movieformdata (moviename, yourname, Gender) VALUES (".
PrepSQL($varMovie) . ", " .
PrepSQL($varName) . ", " .
PrepSQL($varGender) . ")";
mysql_query($sql);
header("Location: thankyou.html");
exit();
}
}
// function: PrepSQL()
// use stripslashes and mysql_real_escape_string PHP functions
// to sanitize a string for use in an SQL query
//
// also puts single quotes around the string
//
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>PHP Form processing example</title>
<!-- define some style elements-->
<style>
label, a {
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
</head>
<body>
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formMovie'>Which is your favorite movie?</label>
<br/>
<input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>" />
</p>
<p>
<label for='formName'>What is your name?</label>
<br/>
<input type="text" name="formName" maxlength="50" value="<?=$varName;?>" />
</p>
<p>
<label for='formGender'>What is your Gender?</label>
<br/>
<select name="formGender">
<option value="">Select...</option>
<option value="M"<? if($varGender=="M") echo(" selected=\"selected\"");?>>Male</option>
<option value="F"<? if($varGender=="F") echo(" selected=\"selected\"");?>>Female</option>
</select>
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
<p> <a href='http://www.html-form-guide.com/php-form/php-form-processing.html'
>'PHP form processing' article page</a> </p>
</body>
</html>
You are connecting to localhost as the database server. When you move the code to a different server, you'd be connecting to a different database. Maybe the other server doesn't have a database.
Also, please use mysqli and bind_param instead of mysql_real_escape_string. The hacker group Anonymous found a way around mysql_real_escape_string by sending in single quotes in a foreign language.

Undefined index: firstname in C:\xampp\htdocs\form_require1.php on line 53/55 [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
Hello everyone!
can someone guide me for the following problem? I was trying to make a php form, but it shows the error ( Undefined index: firstname in C:\xampp\htdocs\form_require1.php on line 53/55) when I run it. please help me
enter code here <?php // define valiables and set to empty values $firstnameErr = $lastnameErr = ""; $firstname = $lastname = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "Name is required";
} else {
$firstname = test_input($_POST["firstname"]); }
if (empty($_POST["lastname"])){
$lastnameErr = "Name is require"; } else { $lastname = test_input($_POST["lastname"]); } } function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
return $data; } ?> `enter code here` <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]) ?>" method="post"> Your firstname <input type="text" name="firstname" /> <span class="error">* <?php echo $firstnameErr;?></span> <br><br> Your Lastname <input type="text" name="lastname" /> <span class="error">* <?php echo $lastnameErr;?></span> <br><br> <input type="submit" value="Submit" /> </form> <?php // } else {
echo 'Your Details';
echo "<br>";
echo 'Fistname: ' . $_POST["firstname"];
echo "<br>";
echo 'Lastname: ' . $_POST["lastname"];
Basically the $_POST variables you want to use are not set. To be sure the form passes the right variables use var_dump($_POST); to see what variables it passes on.
For more information about your error see: php notice undefined variable and notice undefined index

Can't login using a PHP code and SQL [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
So here is my form I use to get the email and password, don't mind all the tabs xD.
<form method="post" action="">
<ul>
<label for='usermail'>email </label>
<input type='text' name='email' placeholder="jouwnaam#mail.nl" required>
</ul>
<ul>
<label for="password">Wachtwoord</label>
<input type="password" name="wachtwoord" placeholder="wachtwoord" required>
</ul>
<ul>
<div class='login-btn btn btn-default btn-lg'><input name="submit" type="submit" value="Inloggen"></div>
</ul>
</form>
And this is my PHP code:
<?php
if (isset($_POST['inloggen']))
{
mysql_connect("localhost","root","usbw") or die('error');
mysql_select_db("sportschool") or die('error');
$k_email = $_POST['email'];
$wachtwoord = $_POST['wachtwoord'];
echo $k_email;
if (mysql_query("SELECT * FROM klant;") == false)
{
echo mysql_error();
}
else
{
$resultaat = mysql_query("SELECT wachtwoord FROM klanten WHERE email='".$k_code."';");
$data = mysql_fetch_assoc($resultaat);
echo "<br />";
echo "<br />";
$k_wachtwoord = $data["wachtwoord"];
echo $k_wachtwoord;
if ($wachtwoord==$k_wachtwoord)
{
echo "U are logged in";
session_start();
$_SESSION['ingelogd'] = true;
$_SESSION['klantemail'] = $k_email;
}
else
{
echo "Username or Password is not right try again.";
}
echo "<br />";
mysql_close();
}
}
?>
Every time I login with the correct email and password the page is refreshed but I don't get the echo for logged in or the error for not logging in.
I have this PHP code which checks if the user is logged in, and that one stays on not logged in:
<?php
if ((isset($_SESSION['ingelogd'])) && ($_SESSION['ingelogd'] == true))
{
echo $_SESSION['klantemail']." is ingelogd";
}
else
{
echo "Nog niet ingelogd.";
}
?>
I don't use PHP a lot, so there may be a lot of mistakes.
Replace this code
if (isset($_POST['inloggen']))
with
if (isset($_POST['submit']))
Your are not checking the correct value.
Try:
if (isset($_POST['submit']) && $_POST['submit'] == "Inloggen")
The key to the post variable is the name attribute of the submit button while its value would be inloggen.
So it should be:
if (isset($_POST['submit']))

line 75 : if (is_array($errors)) [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 9 years ago.
Error!
The following error(s) occurred:
Notice: Undefined variable: errors in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\scripts\ladies_paradise\checkout.php on line 75
Please try again.
`
Untitled Document
<body>
<?php
$page_title='ORDER FORM';
if(isset($_POST['submitted'])){
$errors= array();
$price=($_POST['price']);;
$quantity=($_POST['quantity']);
$total = $quantity * $price;
$total = number_format ($total, 2);
// Validate the name and combat Magic Quotes, if necessary.
if (empty ($_POST['product'])) {
$errors[]='You forgot to enter product.';
}else{
$pr=trim($_POST['product']);
}
// Validate the price.
if (empty ($_POST['price'])) {
$errors[] ='You forgot to enter price.';
} else {
$p=trim($_POST['price']);
}
// Validate the quantity.
if (empty ($_POST['quantity'])) {
$errors[] ='You forgot to enter quantity.';
} else {
$q=trim($_POST['quantity']);
}
if(empty($errors)){
require_once('checkout_connect.php');
$query="INSERT INTO customers(product,price,quantity)VALUES('$pr','$p','$q')";
$result=#mysql_query($query);//Run the query.
if($result){
echo 'You are purchasing <b>', $c. '</b>.
Total price is <b>$', $total, '</b>.';
} else { // One from element was not filled out properly.
echo '<p><font color="orange">Please go back and fill out the form again.</font></p>';
}
exit();
}else{ //If it did not run OK.
echo '<h1 id="mainhead">System Error</h1>
<p class="error">You could not registered due to system error.We apologize for any inconvenience.</p>';//Public message.
echo '<p>'.mysql_error().'<br/><br/>'.$query.'</p>'; //Debugging message.
exit();
}
mysql_close(); //Close the database connection.
}else{ //Report the errors.
echo '<h1 id="mainhead">Error!</h1>
<p class="error">The following error(s) occurred:<br />';
if (is_array($errors)) {
foreach ($errors as $msg){ //Print each error.
echo " - $msg<br />\n";
}
}
echo '</p><p>Please try again.</p><p><br /></p>';
}//End of if (empty($errors)) IF.
?>
<h2>ORDER FORM:</h2>
<form action="checkout.php" method="post">
<p>Product: <input type="number" name="code_item" size="15" maxlength="15" value"<?php if (isset($_POST['product'])) echo $_POST['product']; ?>" /></p>
<p>Price: <input type="number" name="price" size="15" maxlength="30" value"<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p>
<p>Quantity: <input type="number" name="quantity" size="30" maxlength="50" value"<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted" value="TRUE" />
</form>
</body>
</html>``
Define it at the top of the document.
<?php
$errors = false;
Alternatively, check if it is set using a ternary where assignment is necessary.
echo isset($errors) ? $errors: '';
Where '' can be replaced with whatever assignment correlates to the requirements.

Categories