Getting empty $_FILES array - php

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!

Related

Combobox in html and php

If the combobox select the Archers the browser will echo Correct but if the combobox will not select the Archers the browser will echo, i want to know if my syntax is wrong.
Wrong. Error: Undefined index text_hname.
Here's the structure:
<form action="server.php" method="POST">
<img src="images/logo.png" class="logo">
<div class="container">
<h1>Account Details</h1>
<br>
<label class="username">Username</label>
<input type="text" name="text_username" class="text_user" placeholder="Enter username">
<label class="password">Password</label>
<input type="text" name="text_password" class="text_pass" placeholder="Enter password">
<label class="email">Email</label>
<input type="text" name="text_email" class="text_email" placeholder="Enter email">
<label class="cname">Character Name</label>
<input type="text" name="text_cname" class="text_cname" placeholder="Enter Character Name">
<label class="character">Select Character</label>
<select class="names" name="text_hname">
<option>Archer</option>
<option>Barbarian</option>
<option>Balloon</option>
<option>Witch</option>
<option>Spirit</option>
<option>Hog Rider</option>
<option>Minion</option>
</select>
<img src="images/">
<br>
<input type="submit" class="submit" name="submit">
</div>
</form>
//option
$hero = $_POST['text_hname'];
if (isset($_POST['text_hname'])) {
if ($hero == 'Archers') {
echo "Correct";
} else {
echo "wrong";
}
}
The problem is that if you're trying to assign $hero before you've checked if text_hname is set, it might not be defined.
Suggested refactor:
if (isset($_POST['text_hname'])) {
$hero = $_POST['text_hname'];
if ($hero == 'Archers') {
echo "Correct";
}
else
{
echo "wrong";
}
}
//Your select in form needs values. Same values that you are going to compare.
<select class="names" name="text_hname">
<option value="Archer">Archer</option>
<option value="Barbarian">Barbarian</option>
<option value="Balloon">Balloon</option>
<option value="Witch">Witch</option>
<option value="Spirit">Spirit</option>
<option value="HogRider">Hog Rider</option>
<option value="Minion">Minion</option>
</select>
//Php code
if (isset($_POST['text_hname'])) {
$hero = $_POST['text_hname'];
if ($hero == 'Archer') { //Its Archer, not Archers
echo "Correct";
}
else
{
echo "wrong";
}
}
$_POST['text_hname'] will return the selected option value , not option name .
Modify your select like this:
<select class="names" name="text_hname">
<option value="Archer">Archer</option>
<option value="Barbarian">Barbarian</option>
<option value="Balloon">Balloon</option>
<option value="Witch">Witch</option>
<option value="Spirit">Spirit</option>
<option value="Hog_Rider">Hog Rider</option>
<option value="Minion">Minion</option>
</select>
and server.php page
if (isset($_POST['text_hname'])) {
$hero = trim($_POST['text_hname']); //** to remove any whitespace
if ($hero == 'Archer') {
echo "Correct";
} else {
echo "wrong";
}
}
EDIT : it might be because your $_POST['text_hname'] has whitespace. Try trim() on $_POST['text_hname']
Hope it's helpful.

How to display selected value in combo box in php?

I've written this code... but this fails to display text... not sure what's wrong with the code. I'm new to PHP and trying to create a page that gets customer details and puts it in SQL.
<!DOCTYPE html>
<html>
<body>
<?php
$initial="";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
echo "Customer Intial: $initial <br>";
?>
</body>
</html>
Try this:
$initial="";
if(isset($_POST['initial'])){
$initial=htmlentities($_POST['initial']);
}
You correctly sent the POST however you didn't put the value given with the POST into the $initial variable.
<!DOCTYPE html>
<html>
<body>
<?php
$initial = "";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
$initial = filter_input(INPUT_POST, "initial");//GET the input in post method
if ($initial == 1) {
$initial_value = "Mr.";
} elseif ($initial == 2) {
$initial_value = "Mrs.";
} elseif ($initial == 3) {
$initial_value = "Ms.";
} elseif ($initial == 4) {
$initial_value = "M/s";
} else {
$initial_value = "Select initial";
}
echo "Customer Intial: $initial_value <br>";
?>
</body>
</html>
Try,
<form method="post" action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>>
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<br>
<br>
<?php
if(isset($_POST['initial'])){
$initial=$_POST['initial'];
} else {
$initial = "empty";
}
echo "Customer Intial : ".$initial;
?>
</body>
</html>

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

PHP sticky forms dropdown and checkboxes

I'm writing a php form and I can't get the drop down boxes and check boxes to stick as in when I fill in my details but don't click something it will keep everything else filled but that one part that wasn't filled out. I can do it for the input text and radio buttons but I can't get it done for drop downs and checkboxes
<!DOCTYPE html>
<style>
#import url(stickyTextInput.css);
</style>
<?php
if(isset($_REQUEST["left"]))
{
process_form();
}
else
{
display_form_page('');
}
?>
<?php
function display_form_page($error)
{
$self =$_SERVER['PHP_SELF'];
$first_name = isset($_REQUEST['name']) ? $_REQUEST['name']:'';
$last_name = isset($_REQUEST['lastname']) ? $_REQUEST['lastname']:'';
$age = isset($_REQUEST['age']) ? $_REQUEST['age']:'';
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']: '';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head>
<title>
Forms Sticky input
</title>
<style>
#import url(stickyTextInput.css);
</style>
<style type="text/css">
.error
{
color:#ff0000
}
</style>
</head>
<body>
<?php
if($error)
{
echo "<p>$error</p>\n";
}
?>
<form action= "<?php echo $self?>" method = "post">
<h1>Forms-Sticky Input</h1>
<label>First Name:</label>
<input type="text" size="10" maxlength="40" name="name" value = "<?php echo $first_name?>">
<br>
<label>Last Name:</label>
<input type="text" size="10" maxlength="40" name="lastname" value = "<?php echo $last_name?>">
<br>
<label>Age:</label>
<input type="text" name="age" size="10" value="<?php echo $age?>">
<br>
<label>Gender</label>
<input type="radio" name="gender" value="male" <?php check($gender, "male")?>>Male
<input type="radio" name="gender" value="female" <?php check ($gender, "female")?>>Female
<br>
<label>Select favourite Colour</label>
<select name= "color">
<option <?php checkradio($color, "Red")?>>Red
<option <?php checkradio($color, "Blue")?>>Blue
<option <?php checkradio($color, "Green")?>>Green
<option <?php checkradio($color, "Pink")?>>Pink
<option selected="selected" disabled="disabled">
</select>
<br>
<label>Food</label>
<input type="checkbox" name="food[]" value="beans" <?php checkbox ($food, "beans")?>>Beans
<input type="checkbox" name="food[]" value="crisps" <?php checkbox ($food, "crisps")?>>Crisps
<input type="checkbox" name="food[]" value="lemons" <?php checkbox ($food, "lemons")?>>Lemons
<br>
<div id="buttons">
<input type="submit" name="left" id="left" value="Submit" >
<input type="reset" name="right" id="right" value="Reset" >
</div>
</form>
</body>
</html>
<?php
}
?>
<?php
// If $group has the value $val then select this list item
function check($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function checkradio($group, $val)
{
if ($group === $val)
{
echo 'selected = "selected"';
}
}
?>
<?php
// If $group has the value $val then select this list item
function checkbox($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function process_form()
{
$error = validate_form();
if($error)
{
display_form_page($error);
}
else
{
display_output_page();
}
}
?>
<?php
function validate_form()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
$error = '';
$reg_exp = '/^[a-zA-Z\-\']+$/';
$reg_exp1 = '[0-9]{3}';
if(!preg_match($reg_exp, $first_name))
{
$error .= "<span class=\"error\">First Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!preg_match($reg_exp, $last_name))
{
$error .= "<span class=\"error\">Last Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!is_numeric($age))
{
$error .= "<span class=\"error\">Age is invalid (numbers only)</span><br>";
}
if (strlen($gender) == 0)
{
$error .= "<span class=\"error\">Select Male/Female</span><br>";
}
if (strlen($color) == 0)
{
$error .= "<span class=\"error\">Select one color</span><br>";
}
if (! is_array($food))
{
$error .= "<span class=\"error\">You must select one food</span><br>";
}
return $error;
}
?>
<?php
function display_output_page()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head><title>Form Results</title></head>
<body>
<h1>Form Results</h1>
<?php
echo " First Name: $first_name<br/>\n";
echo " Last Name: $last_name<br/>\n";
echo " Age: $age<br/>\n";
echo " Gender: $gender<br/>\n";
echo " Favourite Color: $color<br/>\n";
echo "<ul>";
if (is_array($food))
{
echo "Favourite Food is:";
foreach($food as $selection)
{
echo "<li>$selection</li>";
}
}
echo "</ul>";
?>
</body>
</html>
<?php
}
?>
Possibly a browser issue, however most browsers only require 'checked' at the end of the html input element for checkboxes. However you appear to be outputting checked = "checked" This is possibly the problem. Have a look at the sample below:
<?php
$name = isset($_GET['name']) ? $_GET['name'] : '';
$agree = isset($_GET['agree']) ? 'checked' : '';
$title = isset($_GET['title']) ? $_GET['title'] : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="name" id="name" value="<?=$name;?>">
<input type="checkbox" name="agree" id="agree" <?=$agree;?>>
<select name="title" id="title">
<option value="Mr" <?=$title == 'Mr' ? 'selected' : ''?>>Mr</option>
<option value="Mrs" <?=$title == 'Mrs' ? 'selected' : ''?>>Mrs</option>
<option value="Miss" <?=$title == 'Miss' ? 'selected' : ''?>>Miss</option>
</select>
<button type="submit">submit</button>
</form>
</body>
</html>
After processing the values the output html should be as follows:
<form action="">
<input type="text" name="name" id="name" value="test">
<input type="checkbox" name="agree" id="agree" checked>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss" selected>Miss</option>
</select>
<button type="submit">submit</button>
</form>

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