passing html variable to multiple php files - php

I am building a family tree for a class assignment and I have to pass variables from an HTML form to a PHP file for that family member depending on whose information is being updated. I need the form variables to be able to pass to the php file for father, mother, wife, ect.
HTML File
<form action="handle_family.php" method="post">
<p>Family Member: <select name="name">
<option value="david">David</option>
<option value="linda">Linda</option>
<option value="cayla">Cayla</option>
<option value="sophie">Sophie</option>
<option value="sawyer">Sawyer</option>
</select></p>
<p>Relationship: <select name="relationship">
<option value="father">Father</option>
<option value="mother">Mother</option>
<option value="wife">Wife</option>
<option value="son">Son</option>
<option value="daughter">Daughter</option>
</select></p>
<p>Interests: <input type="text" name="interests" size="60" /></p>
<p>History: <input type="text" name="history" size="60" /></p>
<p>Occupation: <input type="text" name="occupation" size="60" /></p>
<input type="submit" name="submit" value="Update Page" />
</form>
</div>
handle_family.php
<?php // Script 6.2 - handle_reg.php
ini_set ('display_errors', 1);
error_reporting (E_ALL | E_STRICT);
$okay= TRUE;
$relationship= $_POST['relationship'];
$interests= $_POST['interests'];
$history= $_POST['history'];
$occupation= $_POST['occupation'];
$name= $_POST['name'];
if($name == 'david')
{
session_start();
$_SESSION[$father_relationship] = $relationship;
$_SESSION[$father_interests] = $interests;
$_SESSION[$father_occupation] = $occupation;
$_SESSION[$father_name] = $name;
$_SESSION[$father_history] = $history;
include 'david.php';
exit();
}
david.php
<?php // david.php
// Define Variables
$father_name = $_SESSION[$father_name];
$father_relationship = $_SESSION[$father_relationship];
$father_interests = $_SESSION[$father_interests];
$father_history = $_SESSION[$father_history];
$father_occupation = $_SESSION[$father_occupation];
//print father's information
print"<h3>Relationship to Chris</h3>
<p>$father_relationship</p>
<h3>History</h3>
<p>$father_history</p>
<h3>Occupation</h3>
<p>$father_occupation</p>
<h3>Interests</h3>
<p>$father_interests</p>";
?>

It is necessary that the Session be Set/Active in all the Files that need access to the Data that were set using $_Session and setting the session should be the very first thing on any script that needs to access data stored in the Session Global Variable....
HTML FILE:
<div>
<form action="handle_family.php" method="post">
<p>Family Member: <select name="name">
<option value="david">David</option>
<option value="linda">Linda</option>
<option value="cayla">Cayla</option>
<option value="sophie">Sophie</option>
<option value="sawyer">Sawyer</option>
</select></p>
<p>Relationship: <select name="relationship">
<option value="father">Father</option>
<option value="mother">Mother</option>
<option value="wife">Wife</option>
<option value="son">Son</option>
<option value="daughter">Daughter</option>
</select></p>
<p>Interests: <input type="text" name="interests" size="60" /></p>
<p>History: <input type="text" name="history" size="60" /></p>
<p>Occupation: <input type="text" name="occupation" size="60" /></p>
<input type="submit" name="submit" value="Update Page" />
</form>
</div>
handle_family.php FILE:
<?php // NOTICE THAT THERE IS NOT WHITE-SPACE BEFORE <?php
// Script 6.2 - handle_reg.php
// FILE-NAME: handle_reg.php WHERE YOU HAVE TO SET THE SESSION VARIABLE
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
if(!isset($_SESSION['familyTree'])){
$_SESSION['familyTree'] = array();
}
if(isset($_POST['submit'])) {
ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);
$okay = TRUE;
$relationship = htmlspecialchars(trim($_POST['relationship']));
$interests = htmlspecialchars(trim($_POST['interests']));
$history = htmlspecialchars(trim($_POST['history']));
$occupation = htmlspecialchars(trim($_POST['occupation']));
$name = htmlspecialchars(trim($_POST['name']));
// STORE EACH NAME IN THE SESSION USING THE LOWER-CASED FATHERS-NAME AS A UNIQUE KEY
$lcName = strtolower($name);
$_SESSION['familyTree'][$lcName]['father_name'] = $name;
$_SESSION['familyTree'][$lcName]['father_history'] = $history;
$_SESSION['familyTree'][$lcName]['father_interests'] = $interests;
$_SESSION['familyTree'][$lcName]['father_occupation'] = $occupation;
$_SESSION['familyTree'][$lcName]['father_relationship'] = $relationship;
if ($lcName == 'david') {
include 'david.php';
exit();
}
}
david.php FILE:
<?php // NOTICE THAT THERE IS NOT WHITE-SPACE BEFORE <?php
// FILE-NAME: david.php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
$name = "david"; // MAKE SURE THIS IS LOWER-CASE...
$fatherInfo = "";
if(!isset($_SESSION['familyTree'][$name])) {
// Define Variables
$father_name = $_SESSION['familyTree'][$name]['father_name'];
$father_history = $_SESSION['familyTree'][$name]['father_history'];
$father_interests = $_SESSION['familyTree'][$name]['father_interests'];
$father_occupation = $_SESSION['familyTree'][$name]['father_occupation'];
$father_relationship = $_SESSION['familyTree'][$name]['father_relationship'];
//print father's information
$fatherInfo = "<h3>Relationship to Chris</h3>" . PHP_EOL;
$fatherInfo.= "<p>$father_relationship</p>" . PHP_EOL;
$fatherInfo.= " <h3>History</h3>" . PHP_EOL;
$fatherInfo.= "<p>$father_history</p>" . PHP_EOL;
$fatherInfo.= " <h3>Occupation</h3>" . PHP_EOL;
$fatherInfo.= "<p>$father_occupation</p>" . PHP_EOL;
$fatherInfo.= " <h3>Interests</h3>" . PHP_EOL;
$fatherInfo.= "<p>$father_interests</p>" . PHP_EOL;
}
echo $fatherInfo;

Related

PHP Validating Form

I am having trouble showing the output that i called in printf in php tutorial. I just followed the tutorial but still can't figure out what is wrong in displaying the variables inside the printf in localhost. Is anyone can help me. Thank you.
<?php
$name = '';
$password = '';
$gender = '';
$color = '';
$languages = [];
$comments = '';
$tc = '';
if (isset($_POST['submit'])) {
if (isset($_POST['name'])) {
$name = $_POST['name'];
};
if (isset($_POST['password'])) {
$password = $_POST['password'];
};
if (isset($_POST['gender'])) {
$gender = $_POST['gender'];
};
if (isset($_POST['color'])) {
$color = $_POST['color'];
};
if (isset($_POST['languages'])) {
$languages = $_POST['languages'];
};
if (isset($_POST['comments'])) {
$comments = $_POST['comments'];
};
if (isset($_POST['tc'])) {
$tc = $_POST['tc'];
};
//here's the problem i cant resolve printing out the output//
printf('User name: %s
<br>Password: %s
<br>Gender: %s
<br>Color: %s
<br>Language(s): %s
<br>Comments: %s
<br>T&C: %s',
htmlspecialchars($name, ENT_QUOTES),
htmlspecialchars($password, ENT_QUOTES),
htmlspecialchars($gender, ENT_QUOTES),
htmlspecialchars($color, ENT_QUOTES),
htmlspecialchars(implode('', $languages), ENT_QUOTES),
htmlspecialchars($comments, ENT_QUOTES),
htmlspecialchars($tc, ENT_QUOTES));
}
?>
<form action=""
method="post">
User name: <input type="text" name="name"><br>
Password: <input type="password" value="password"><br>
Gender:
<input type="radio" name="gender" value="f"> female
<input type="radio" name="gender" value="m"> male
<input type="radio" name="gender" value="o"> other<br/>
Favorite color:
<select name="color">
<option value="">Please select</option>
<option value="#f00">red</option>
<option value="#0f0">green</option>
<option value="#00f">blue</option>
</select><br>
Languages spoken:
<select name="languages[]"multiple size="3">
<option value="en">English</option>
<option value="fr">French</option>
<option value="it">Italian</option>
</select><br>
Comments: <textarea name="comments"></textarea><br>
<input type="checkbox" name="tc" value="ok"> I accept the T&C<br>
<input type="submit" value="Register">
</form>`
The problem here is if (isset($_POST['submit'])) there is no any form field with the name submit and it will never become true to execute. Remove the if Condition with submit or Else give the sumbit button name as Submit
<input type="submit" value="Register" name="submit">
Errors in your previous code are:
No semicolons ; are needed after ending if statements.
No name attribute is specified for password input in the form.
Posting form data as if (isset($_POST['submit'])) {...} without specifying the name="submit" attribute in the form.
Invalid use of implode function which will generate output be like enfrit or vice versa.
Additional Tips
Add the required attribute to each input to prevent from sending empty form data.
You have already specified method="post" in the form tag so, no need for validating each input field as if (isset($_POST['fieldname'])) {...} . if (isset($_POST['submit'])) {...} will send all the form data as POST method.
And lastly, here is your updated code.
<?php
if (isset($_POST['submit'])) {
$name = '';
$password = '';
$gender = '';
$color = '';
$languages = [];
$comments = '';
$tc = '';
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
if (isset($_POST['gender'])) {
$gender = $_POST['gender'];
}
if (isset($_POST['color'])) {
$color = $_POST['color'];
}
if (isset($_POST['languages'])) {
$languages = $_POST['languages'];
}
if (isset($_POST['comments'])) {
$comments = $_POST['comments'];
}
if (isset($_POST['tc'])) {
$tc = $_POST['tc'];
}
//print output
printf('User name: %s
<br>Password: %s
<br>Gender: %s
<br>Color: %s
<br>Language(s): %s
<br>Comments: %s
<br>T & C: %s
<br><br>',
htmlspecialchars($name, ENT_QUOTES),
htmlspecialchars($password, ENT_QUOTES),
htmlspecialchars($gender, ENT_QUOTES),
htmlspecialchars($color, ENT_QUOTES),
htmlspecialchars(implode(', ', $languages), ENT_QUOTES),
htmlspecialchars($comments, ENT_QUOTES),
htmlspecialchars($tc, ENT_QUOTES));
}
?>
<form action="" method="post">
User name: <input type="text" name="name">
<br>
Password: <input type="password" name="password">
<br>
Gender:
<input type="radio" name="gender" value="f"> female
<input type="radio" name="gender" value="m"> male
<input type="radio" name="gender" value="o"> other
<br>
Favorite color:
<select name="color">
<option value="">Please select</option>
<option value="#f00">red</option>
<option value="#0f0">green</option>
<option value="#00f">blue</option>
</select>
<br>
Languages spoken:
<select name="languages[]" multiple size="3">
<option value="en">English</option>
<option value="fr">French</option>
<option value="it">Italian</option>
</select>
<br>
Comments: <textarea name="comments"></textarea>
<br>
<input type="checkbox" name="tc" value="ok"> I accept the T & C
<br>
<input type="submit" name="submit" value="Register">
</form>

PHP: How to carry over session variables between 3 pages?

So as of now, i can successfully get the results to move from page one to page two using post and get, but no matter what im doing it will not move the info to the 3rd page. Im trying to switch it over to sessions after reading its made exactly for this but for some reason im doing something wrong and after hours of searching i cant for the life of me figure out what it is. I've followed guides, followed videos, and other post related to the topic on this website. I have now come to the conclusion that it is just me and i need some assistance. Any help would be greatly appreciated.
Page 1 (Index Page | Input Your Variables):
<?php session_start();
$_GET['q'] = $q;
$_GET['s'] = $s;
?>
<form action="search.php" method="get">
<input name="q" maxlength="8" type="text" placeholder="License Plate" id="textbox" required />
<select name="s" id="s" required aria-required="true">
<option value="" disabled selected>CHOOSE STATE</option>
<option value="AL">ALABAMA</option>
<option value="AK">ALASKA</option>
<option value="AZ">ARIZONA</option>
<option value="AR">ARKANSAS</option>
<option value="CA">CALIFORNIA</option>
<option value="CO">COLORADO</option>
<option value="CT">CONNECTICUT</option>
etc...
</select>
<input type="submit" value="SEARCH" id="submitbtn"></form>
Page 2 (Search.php that will take you directly to page specified if its already been created):
<?php session_start();
$q = $_POST['q'];
$s = $_POST['s'];
?>
<?php
$dir = 'states';
$s = (isset($_GET['s']))? strtolower($_POST['s']) : '';
$q = (isset($_GET['q']))? strtoupper($_POST['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtoupper($file),$q)!== false &&!in_array($file)) {
echo "<a href='$dir/$s/$q.htm'>$file</a>";
}
}
closedir($res);
?>
<?php
echo $htmlHeader;
while($stuff){
echo $stuff;
}
echo "<script>window.location =
'http://www.somesite.com/$dir/$s/$q.htm'</script>";
?>
Page 3 (404 page for catch all that are not in the system):
<?php session_start();
?>
<form action="" method="" name="FormChoice">
<input name="q" maxlength="8" type="text" value="<?php echo $_POST['q']; ?>" id="q" required>
<select name="s" id="s" required aria-required="true">
<option value="" disabled>CHOOSE STATE</option>
<option value="AL" <?php if($_POST['s'] == al) {echo ' selected="selected"';} ?>>ALABAMA</option>
<option value="AK" <?php if($_POST['s'] == ak) {echo ' selected="selected"';} ?>>ALASKA</option>
<option value="AZ" <?php if($_POST['s'] == az) {echo ' selected="selected"';} ?>>ARIZONA</option>
<option value="AR" <?php if($_POST['s'] == ar) {echo ' selected="selected"';} ?>>ARKANSAS</option>
<option value="CA" <?php if($_POST['s'] == ca) {echo ' selected="selected"';} ?>>CALIFORNIA</option>
<option value="CO" <?php if($_POST['s'] == co) {echo ' selected="selected"';} ?>>COLORADO</option>
<option value="CT" <?php if($_POST['s'] == ct) {echo ' selected="selected"';} ?>>CONNECTICUT</option>
</select>
<input type="submit" id="submitbtn2" value="SEARCH" name="submit" OnClick="search()" />
<span id="or">OR</span>
<input type="submit" id="addbtn" value="ADD" name="submit" OnClick="add()" />
</form>
page1
<?php
session_start();
// next 2 lines do NOTHING remove them
// as you have not yet loaded any values into $q and $s
//$_GET['q'] = $q;
//$_GET['s'] = $s;
?>
<form action="search.php" method="get">
<input name="q" maxlength="8" type="text" placeholder="License Plate" id="textbox" required />
<select name="s" id="s" required aria-required="true">
<option value="" disabled selected>CHOOSE STATE</option>
<option value="AL">ALABAMA</option>
<option value="AK">ALASKA</option>
<option value="AZ">ARIZONA</option>
<option value="AR">ARKANSAS</option>
<option value="CA">CALIFORNIA</option>
<option value="CO">COLORADO</option>
<option value="CT">CONNECTICUT</option>
etc...
</select>
<input type="submit" value="SEARCH" id="submitbtn"></form>
Page 2 - Search - receives data from previous form
- Contains lots of unecessary <?php...?>
- Previous form uses method="get" so data will arrive in the $_GET array not the $_POST array
<?php
session_start();
//$q = $_POST['q'];
//$s = $_POST['s'];
// But this is silly as you have not yet tested these values exist
// but you do that in the next lines
//$q = $_GET['q'];
//$s = $_GET['s'];
$dir = 'states';
$s = (isset($_GET['s']))? strtolower($_POST['s']) : '';
$q = (isset($_GET['q']))? strtoupper($_POST['q']) : '';
$res = opendir($dir);
// Now if you want to pass the values of `q` and `s` on to the next form
// they now need to be added to the session
$_SESSION['q'] = $q;
$_SESSION['s'] = $s;
while(false!== ($file = readdir($res))) {
if(strpos(strtoupper($file),$q)!== false &&!in_array($file)) {
echo "<a href='$dir/$s/$q.htm'>$file</a>";
}
}
closedir($res);
echo $htmlHeader;
while($stuff){
echo $stuff;
}
echo "<script>
window.location = 'http://www.somesite.com/$dir/$s/$q.htm';
</script>";
// added missing semi colon ^
?>
Page 3 (404 page for catch all that are not in the system):
Now the data will be available in the SESSION, when you get to this page.

Getting empty $_FILES array

I want to upload a file to server.I have added all the code to upload file to server but the $_FILES array is empty. File Value is not getting set in an array.
I have done same code for another web page and it works fine, but not getting whats the issue in this.
I have set the enctype as multipart/form-data but still its giving empty array.
html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<script>
</script>
<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<select id="types" name="types" onchange="myFunction(this)">
<option value="">Select type</option>
<option value="2">Add Link</option>
<option value="0">Upload Image</option>
<option value="1">Upload Video</option>
</select><br><br>
<div id="link" style="display: none">
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="urlType">Select Url Type :(required)</label>
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<!-- <option value="0">Server Image</option>
<option value="1">Server Video</option>-->
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
</div>
<div id="filediv" style="display: none">
Select file to upload:
<br><br>
<input name = "file" type="file" id="fileToUpload"><br><br>
</div>
<p>
<label for="postType"> Select Post Type :(required)</label>
<select name="postType" id="postType">
<option value="">Select Post Type...</option>
<option value="0">Normal</option>
<option value="1">Featured</option>
<option value="2">Sponsored</option>
</select>
</p>
<p>
<label for="category"> Select Category :(required)</label>
<select name="category" id="category">
<option value="">Select Category...</option>
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<!-- Cancel
Add User-->
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</fieldset>
<div class="result" id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
function myFunction(obj) {
var type = obj.value;
var x = document.getElementById('link');
var y = document.getElementById('filediv');
if(type == "2")
{
x.style.display = 'block';
y.style.display = 'none';
}
else {
x.style.display = 'none';
y.style.display = 'block';
}
}
</script>
</form>
</body>
</html>
addPost.php
<?php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
$file_result = "";
if(strcmp($_POST['types'],"2") == 0)
{
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "Post submitted.";
} else {
echo "Could not submit post.";
}
}
else {
if(isset($_POST['submit'])){
print_r($_FILES);
if (isset($_FILES["file"]["name"])) {
$file_result = "";
if ($_FILES["file"]["error"] > 0) {
$file_result .= "No file uploaded or invalid file.";
$file_result .= "Error code : " . $_FILES["file"]["error"] . "<br>";
} else {
if (strcmp($_POST['types'], "0") == 0) {
$target_dir = "AgTv/images/";
} else {
$target_dir = "AgTv/videos/";
}
$newfilename = preg_replace('/\s+/', '',
$_FILES["file"]["name"]);
$target_file = $target_dir . basename($newfilename);
/*$target_file = $target_dir . basename($_FILES["file"]["name"]);*/
$file_result .=
"Upload " . $_FILES["file"]["name"] . "<br>" .
"type " . $_FILES["file"]["type"] . "<br>" .
"temp file " . $_FILES["file"]["tmp_name"] . "<br>";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "The file " . basename($_FILES['file']['name']) . " has been uploaded, and your information has been added to the directory";
} else {
echo "Could not submit post.";
}
}
}
}
else{
echo 'empty file';
}
}
}
}
}
?>
Can anyone help please? Thank you.
UPDATED WITH SOLUTION:
just add
<script>
$("#postForm").validate();
</script>
below the inclusion of jquery.validate.min.js. You $_FILES array is working fine, you are just not sending the post at all!

Passing function to another page in PHP

So this has been bugging me for sometime, I want to pass a calculation which I have stored in a function onto another page, I can pass field entries no problem (sorry im newish at PHP) but how do i pass my calculation from:
// calculation section (calculator.php) - this is a include on every page
The calculation is made by a users entries which is in a include on every page
// The thank-you.php page outputs a thank you comment and sends the email
I receive all the other info fine but the function won't come through in my email.
The output from the calculation is also stored in calculator.php which is the include but it outputs to the screen fine just not to my email :(.
Am I missing something?
Sorry (edit) here is my code:
<?php
error_reporting(E_ALL);
if(isset($_POST['name']) && isset($_POST['to'])){
ini_set('date.timezone', 'Europe/Madrid');
$now = date("H:i");
$cutoff = "06:00";
$higherthan = "22:00";
$name = $_REQUEST['name'];
$telephone = $_REQUEST['telephone'];
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$date = $_REQUEST['date'];
$returndate = $_REQUEST['returndate'];
$people = $_REQUEST['people'];
$return = $_REQUEST['return'];
$myemail = $_REQUEST['myemail'];
include_once('includes/config.php');
$settingsSql = mysql_query("SELECT * FROM transfers_in WHERE location='$to' AND no_passengers='$people'");
$settings = mysql_fetch_assoc($settingsSql);
echo "From: ".$from." To: ".$settings['location']."<br />";
echo "Number of passengers: ".$settings['no_passengers']."<br />";
ini_set('date.timezone', 'Europe/Madrid');
$now = date("H:i");
$cutoff = "06:00";
$higherthan = "22:00";
echo "Time cost: ".$settings['price']." euros<br /><hr />Total: ";
function timeCost() {
$to = $_REQUEST['to'];
$people = $_REQUEST['people'];
$return = $_REQUEST['return'];
include_once('includes/config.php');
$settingsSql = mysql_query("SELECT * FROM transfers_in WHERE location='$to' AND no_passengers='$people'");
$settings = mysql_fetch_assoc($settingsSql);
//echo $return;
if ($return == "No"){
if ((strtotime($now) < strtotime($cutoff)) || (strtotime($now) > strtotime($higherthan))){
echo number_format($settings['price']) + 1.40;
} else {
echo number_format($settings['price']) + 0.00;
}
} elseif ($return == "Yes") {
if ((strtotime($now) < strtotime($cutoff)) || (strtotime($now) > strtotime($higherthan))){
echo number_format($settings['price']) * 2 + 1.40;
} else {
echo number_format($settings['price']) * 2 + 0.00;
}
}
echo " in euros<br /><br />";
}
echo timeCost();
} else { ?>
<form method="POST" action="thank-you.php" name="chooseDateForm" id="chooseDateForm">
<label>Name:</label>
<input type="text" value="" name="name" />
<label>Telephone:</label>
<input type="text" value="" name="telephone" />
<label>Email:</label>
<input type="text" value="" name="myemail" />
<label>From:</label>
<select name="from">
<option selected="selected">Malaga</option>
</select>
<div class="clr"></div>
<label>To:</label>
<select name="to">
<?php foreach ($data as $place => $price){
echo "<option>{$place}</option>\n";
}
echo '</select>
<div class="clr"></div>
<label>Date:</label>
<input type="text" value="dd/mm/yyyy" id="date" name="date" class="date-pick" />
<span id="calendar"></span>
<div id="return-journey">
<label>Return Date:</label>
<input type="text" value="dd/mm/yyyy" id="returndate" name="returndate" class="date-pick" />
<span id="calendar"></span>
</div>
<label>Number of people:</label>
<select id="people" name="people">
<option value="4">4</option>
<option value="6">6</option>
<option value="8">8</option>
</select>
<div class="clr"></div>
<div id="return">
<label>Is this a return<br />journey?</label>
<div class="clr"></div>
<div id="radio-buttons">
<input type="radio" name="return" value="Yes" class="radio returning" />Yes<br />
<input type="radio" name="return" value="No" class="radio" checked />No
</div>
</div>
<div class="clr"></div>
<input type="submit" name="submit" class="fauxButton" />
</form>';
}
?>
If you are using sessions, you can store the variable, results, array -- whatever into a session variable and then retrieve it on a new page.
session_start();
$_SESSION['test_var'] = 'Jake';
Then when I navigate to a new page and retrieve the var:
session_start();
echo $_SESSION['test_var']
// outputs 'Jake'

Unnecessary Error Message Being Displayed

I've set up a form to update my blog and it was working fine up until about this morning. It keeps on turning up with an Invalid Entry ID error on the edit post page when I click the update button despite the fact that it updates the homepage.
All help is seriously appreciated.
<html>
<head>
<title>Ultan's Blog | New Post</title>
<link rel="stylesheet" href="css/editpost.css" type="text/css" />
</head>
<body>
<div class="new-form">
<div class="header">
</div>
<div class="form-bg">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
if (isset($_POST['update'])) {
$id = htmlspecialchars(strip_tags($_POST['id']));
$month = htmlspecialchars(strip_tags($_POST['month']));
$date = htmlspecialchars(strip_tags($_POST['date']));
$year = htmlspecialchars(strip_tags($_POST['year']));
$time = htmlspecialchars(strip_tags($_POST['time']));
$entry = $_POST['entry'];
$title = htmlspecialchars(strip_tags($_POST['title']));
if (isset($_POST['password'])) $password = htmlspecialchars(strip_tags($_POST['password']));
else $password = "";
$entry = nl2br($entry);
if (!get_magic_quotes_gpc()) {
$title = addslashes($title);
$entry = addslashes($entry);
}
$timestamp = strtotime ($month . " " . $date . " " . $year . " " . $time);
$result = mysql_query("UPDATE php_blog SET timestamp='$timestamp', title='$title', entry='$entry', password='$password' WHERE id='$id' LIMIT 1") or print ("Can't update entry.<br />" . mysql_error());
header("Location: post.php?id=" . $id);
}
if (isset($_POST['delete'])) {
$id = (int)$_POST['id'];
$result = mysql_query("DELETE FROM php_blog WHERE id='$id'") or print ("Can't delete entry.<br />" . mysql_error());
if ($result != false) {
print "The entry has been successfully deleted from the database.";
exit;
}
}
if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_GET['id'];
}
$result = mysql_query ("SELECT * FROM php_blog WHERE id='$id'") or print ("Can't select entry.<br />" . $sql . "<br />" . mysql_error());
while ($row = mysql_fetch_array($result)) {
$old_timestamp = $row['timestamp'];
$old_title = stripslashes($row['title']);
$old_entry = stripslashes($row['entry']);
$old_password = $row['password'];
$old_title = str_replace('"','\'',$old_title);
$old_entry = str_replace('<br />', '', $old_entry);
$old_month = date("F",$old_timestamp);
$old_date = date("d",$old_timestamp);
$old_year = date("Y",$old_timestamp);
$old_time = date("H:i",$old_timestamp);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><input type="hidden" name="id" value="<?php echo $id; ?>" />
<strong><label for="month">Date (month, day, year):</label></strong>
<select name="month" id="month">
<option value="<?php echo $old_month; ?>"><?php echo $old_month; ?></option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<input type="text" name="date" id="date" size="2" value="<?php echo $old_date; ?>" />
<select name="year" id="year">
<option value="<?php echo $old_year; ?>"><?php echo $old_year; ?></option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
</select>
<strong><label for="time">Time:</label></strong> <input type="text" name="time" id="time" size="5" value="<?php echo $old_time; ?>" /></p>
<p><strong><label for="title">Title:</label></strong> <input type="text" name="title" id="title" value="<?php echo $old_title; ?>" size="40" /> </p>
<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1"<?php if($old_password == 1) echo " checked=\"checked\""; ?> /></p>
<p><textarea cols="80" rows="20" name="entry" id="entry"><?php echo $old_entry; ?></textarea></p>
<p><input type="submit" name="update" id="update" value="Update"></p>
</form>
<p><strong>Be absolutely sure that this is the post that you wish to remove from the blog!</strong><br />
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />
<input type="submit" name="delete" id="delete" value="Delete" />
</form>
</div>
</div>
</div>
<div class="bottom"></div>
</body>
</html>
As far as I can see, you use either $_GET['id'] or $_POST['id'] to identify the entry ID. So you must check on the two when you set the $id variable:
if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']))
die("Invalid entry ID.");
Or, more selectively:
if (isset($_GET['id']) && is_numeric($_GET['id']))
$id = intval($_GET['id']);
else if (isset($_POST['id']) && is_numeric($_POST['id']))
$id = intval($_POST['id']);
else
die('Invalid entry ID.');
The empty check is redundant to is_numeric: an empty string is not numeric. Also, empty returns true with 0, which, I believe, should not halt your system since 0 could be a valid ID.
I believe the issue here is the mixing of POST and GET
Your form uses the POST method:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
So you need to change:
if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_GET['id'];
}
to:
if (!isset($_POST['id']) || empty($_POST['id']) || !is_numeric($_POST['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_POST['id'];
}

Categories