how to rename uploaded files if there's duplicated names - php

i'm having a small issue in the duplicated names.
I want to auto rename any duplicated upload files, like numbering them.
or if i could make the name same with numbers, such as file1.jpg / file2.jpg
for all uploaded files
here's my code
<?php
include('connect-db.php');
if (isset($_POST['submit'])) {
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"photos/$filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo= mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename== '' ) {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
Even the echo of if(file_exists($_FILES["imgfile"]["name"])) it's not working, i don't know why
Thank you very much before replying

try this code
this code will never get same name this code will rename file like 2jh5425h44u5h45h454k5image.jpg this is how it will save file so no need to worry about duplicate file
i have added random name generator $newname = md5(rand() * time()); this will generate random name for your file
<?php
include('connect-db.php');
$newname = md5(rand() * time());
if (isset($_POST['submit'])) {
$filename = $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif") || ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)) {
if (file_exists($_FILES["imgfile"]["name"])) {
echo "File name exists.";
} else {
move_uploaded_file($_FILES["imgfile"]["tmp_name"], "photos/$newname . $filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo = mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
if you need to rename only if file is duplicate here is answer Renaming duplicate files in a folder with php

Related

I cant seem to upload my picture in my function

I still have the error 2 days after. Help...
I have an error with picture upload in my code. The file upload works perfectly when i remove anything image related but fails once i add anything image related.
I get 2 errors
"Sorry, there was a problem uploading your file." and
"Problem uploading item". I have no idea why...
I'll post the section i have the problem with.
if((($_FILES["pic"]["type"] != "image/jpg")
|| ($_FILES["pic"]["type"] != "image/jpeg")
|| ($_FILES["pic"]["type"] != "image/png")
|| ($_FILES["pic"]["type"] != "image/pjpeg"))
&& ($_FILES["pic"]["size"] > 1000000))
{
$_SESSION['itemerror'][] = "Pic must be jpg, jpeg, png or pjpeg and must be less than 1mb";
}
//final disposition
if (count($_SESSION['itemerror']) > 0) {
die(header("Location: postitem.php"));
} else {
if(registerItem($_POST)) {
unset($_SESSION['formAttempt']);
$_SESSION['itemsuccess'][] = "Successfully Uploaded";
die(header("Location: postitem.php"));
} else {
error_log("Problem uploading item: {$_POST['name']}");
$_SESSION['itemerror'][] = "Problem uploading item";
die(header("Location: upload.php"));
}
}
function registerItem($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$target = "img/";
$target = $target . basename( $_FILES['pic']['name']);
$pic=($_FILES['pic']['name']);
$poster = htmlspecialchars($mysqli->real_escape_string($_POST['user']));
$itemcategory = htmlspecialchars($mysqli->real_escape_string($_POST['category']));
$itemname = htmlspecialchars($mysqli->real_escape_string($_POST['name']));
$itemdescription = htmlspecialchars($mysqli->real_escape_string($_POST['description']));
$itemprice = htmlspecialchars($mysqli->real_escape_string($_POST['price']));
$itemlocation = htmlspecialchars($mysqli->real_escape_string($_POST['addr']));
$itemcity = htmlspecialchars($mysqli->real_escape_string($_POST['city']));
$itemstate = htmlspecialchars($mysqli->real_escape_string($_POST['state']));
$itemphone = htmlspecialchars($mysqli->real_escape_string($_POST['phone']));
$itemnegotiate = htmlspecialchars($mysqli->real_escape_string($_POST['negotiate']));
if(move_uploaded_file($_FILES['pic']['tmp_name'],$target)){
$query = "INSERT INTO Product
(category,name,upload_date,user,
description,price,location,city,
state,phone,negotiatable,pic_link)" .
" VALUES ('{$itemcategory}','{$itemname}',NOW(),'{$poster}',
'{$itemdescription}','{$itemprice}','{$itemlocation}'" .
",'{$itemcity}','{$itemstate}','{$itemphone}','{$itemnegotiate}', '{$pic}')";
if ($mysqli->query($query)) {
$itemname = $mysqli->insert_itemname;
error_log("Inserted {$itemname} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
} else {
$_SESSION['itemerror'][] = "Sorry, there was a problem uploading your file.";
}
}
The form contains this:
<form id="userForm" method="POST" action="upload.php">
And this for the picture input:
<label for="pic">Pictures: </label>
<input class="input100" type="file" id="pic" name="pic">
Add the attribute enctype="multipart/form-data" to your <form>
Like this
<form id="userForm" method="POST" action="upload.php" enctype="multipart/form-data">
I do not know if that will solve your problem, but it will probably help you.
It seems to me that it's mandatory for an upload form.

SQLi injection prevention and error reporting issues

I know separately these questions are quite common although I have searched around for usable answers and am not having much luck finding a lot of information for MySQLi or the new PHP version. Hopefully one of you experts might be able to help me out.
I have a 'simple' html form running a PHP script to the database, which seems to work perfectly, also includes a file upload, which also works. I have some knowledge over security and protection and I am pretty sure my script isn't at all secure. I am also have problems displaying anything if the script doesn't run properly.
I attempted to add a code such as:
} else {
header('Location: addpcn.php?pcnerror=4');
}
Although there are so many '}' at the end of my code, I am not sure where to add it. Also, there are a lot of issues I may be forgetting to alert the user if the code is unsuccessful and the error would never be displayed?
Here is my code so far:
if(isset($_POST['pcn'])){
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
if(empty($pcn_number) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_reg) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($street_name) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($offence) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_make) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_colour) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($date_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($time_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_from) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_to) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($issued_by) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
mysqli_query($conn, "INSERT INTO parkingtickets (id, pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, special_fine_discount, special_fine, paid, paid_date, evidence) VALUES ('','$pcn_number', '$date_issued', '$vehicle_reg', '$vehicle_make', '$vehicle_model', '$vehicle_colour', '$street_name', '$witnessed_from', '$witnessed_to', '$time_issued', '$offence', '$issued_by', '', '', '0', '', '$name')");
header('Location: addpcn.php?pcnerror=3');
}
}
}
}
}
}
}
}
}
}
}
}
I know that you guys will see it as the wrong way to go about it, but I'm still a novice, and hopefully you'll be able to point me in the right direction with a few better examples as error reporting for this code as well as MySQLi injection prevention could be improved drastically.
Thanks!
I made some changes at your code. For consistency i used underscore for all variables and not the camelCase convention. Same for table name in database (parking_tickets).
It is a good practice to validate your inputs so if one of them isn't of correct type you will be able to show info messages for it.
Also, i used associative arrays instead of multiple if statements.
Thanks to # Scott Arciszewski i added the prepared statements with the difference i omit the paid column so make sure it has 0 as default value in your database.
if (isset($_POST['pcn'])) {
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
//User input validation chekcs
$is_valid = true;
//e.g
if (!(is_numeric((int)$pcn_number) && ctype_digit((string)$pcn_number))) {
$is_valid = false;
echo 'The pcn_number is not valid. It must be an integer.';
}
if (!(is_numeric((int)$vehicle_reg) && ctype_digit((string)$vehicle_reg))) {
$is_valid = false;
echo 'The vehicle_reg is not valid. It must be an integer.';
}
if (!$is_valid) {
//Do something here and dont continue if one of the inputs is not valid
}
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$upload_ok = true;
$image_file_type = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if ($check !== false) {
$upload_ok = true;
} else {
$upload_ok = false;
}
// Check if file already exists
if (file_exists($target_file)) {
$upload_ok = false;
}
// Allow certain file formats
$valid_formats = array('jpg', 'png', 'jpeg', 'gif');
if (!in_array($image_file_type, $valid_formats)) {
$upload_ok = false;
}
// Check if $uploadOk is set to false by an error
if ($upload_ok === false) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
$checks = array(
array (
'var'=>$pcn_number,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
array (
'var'=>$vehicle_reg,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
/*
* More elements here
*/
);
foreach($checks as $key => $value) {
if (empty($value['var']) === $value['condition'] ) {
header('Location: '.$value['location']);
exit;
}
}
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$stmt = mysqli_prepare($connection, "INSERT INTO parking_tickets (pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?");
if (mysqli_stmt_bind_param($stmt, 'sssssssssssss', $pcn_number, $date_issued, $vehicle_reg, $vehicle_make, $vehicle_model, $vehicle_colour, $street_name, $witnessed_from, $witnessed_to, $time_issued, $offence, $issued_by, $name)) {
mysqli_stmt_execute($stmt);
header('Location: addpcn.php?pcnerror=3');
exit;
}
}

User Credentials Validation Error and Update With Media Error using CodeBird PHP

i want to check user credentials after user login in a form, then if username and password correct, user will redirected to upload.php page, and after upload an image and a status, image and status will post on user twit
here's my code for verifikasi.php
<h2>Verifikasi ID Twitter...</h2>
/*verification of user credentials
after validation of username and password success, redirect to upload image and status page
but if validation of username and password fail, back to login page
*/
<?php
require_once('codebird.php');
$cb = new \Codebird\Codebird;
$id = $_POST['id'];
$pass = $_POST['pass'];
//if($_POST['loginTwitter'] == "Submit"){
//if(isset($_POST['loginTwitter'])){
if(isset($id) && isset($pass)){
//cek bener apa engga nya
//if($_POST['id'] == '' || $_POST['pass'] == ''){ header('login.php'); }
$cb::setConsumerKey('somekey', 'somekeysecret');
$cb::getInstance();
$cb->setToken('tokenaccess', 'tokenaccesssecret');
$code = $cb->account_verifyCredentials();
if($code == 200){
//$reply = $cb->oauth2_token();
//$bearer_token = $reply->access_token;
header('upload.php');
}
else{ header('login.php'); }
//echo "Redirect to Upload Image...."; for($i = 0; $i <= 20000000; $i++); header('upload.php');
}
else{
echo "<br />";
echo "<h3>Something went wrong... Please Check Again Your Credentials</h3>";
}
?>
and here's the post.php page (for posting image and status to user twit using update_with_media API
<div id="photo_tweet">
<h2>Photo Tweet</h2>
<br />
<?php require_once('codebird.php'); ?>
<?php
function redirectToUpload(){
echo "Redirect...";
for($i = 0; $i <= 20000000; $i++);
header('upload.php');
}
?>
<?php
$imgExt = array("jpeg", "jpg", "png");
$currImgExt = end( explode(".", $_FILES["file"]["name"]) );
if($_POST['uploadTwit'] == "Submit"){
if ((($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png") || $_POST['status'] == '')
&& ($_FILES["file"]["size"] < 20000)
&& in_array($currImgExt, $imgExt))
{
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
redirectToUpload();
}
else{
$params = array(
'status' => $_POST['status'],
'media[]' => $_FILES["file"]["name"]
);
/*
$data_user = array(
'user_id' => ,
'screen_name' =>
);
*/
$reply = $cb->statuses_updateWithMedia($params);
}
}
}
else { echo "Invalid Image File or Invalid File Size or Twit cannot empty! Please check agian your image file before proceed!"; redirectToUpload(); }
?>
<p>You Just Succeed Post image and status!</p>
</div>
The problem for verifikasi.php is
Notice: Object of class stdClass could not be converted to int in C:\wamp\www\twcodebird\verifikasi.php on line 36
i want to return status code in verifikasi.php, if code = 200 then user redirected to upload.php page,
but looking from error return, it seems my code wrong return... what should i do?
for post.php i'm not run it yet, because i want to make sure verification of user credentials work first

fail upload to database

I am trying to save a image file name at database, but i cannot make it, please help me
my database have no wrong, duno why it cannot update to databse, but i can get the $newname correctly
?php session_start();
include_once("connectDB.php");
$ID = $_SESSION['ID'];
if(isset($_POST['upload'])){
$ID = $_SESSION['ID'];
$loc = "profilepicture/";
if($_FILES["Adminpic"]["type"] == "image/png" || $_FILES["Adminpic"]["type"] ==
"image/jpeg" || $_FILES["Adminpic"]["type"] == "image/jpg" || $_FILES["Adminpic"]
["type"] == "image/gif")
{
$ID = $_SESSION['ID'];
$file = explode(".", $_FILES["Adminpic"]["name"]);
$newname = "$ID.$file[0].$file[1]";
mysql_query("UPDATE admin SET Adminpic == '$newname' WHERE ID='$ID'");
$path = "$loc$newname";
move_uploaded_file($_FILES["Adminpic"]["tmp_name"], $path) ;
echo "Your image has been uploaded success, $newname";
}
else{
echo"invalid file.";
}
}
Because your query is incorrect
mysql_query("UPDATE admin SET Adminpic ='$newname' WHERE ID=$ID");
try with this because you use double equal after Adminpic .

Multiple Submit Buttons On Form Difficulties

I wonder whether someone may be able to help me please.
I've put together this form which, if you scroll to the bottom of the page, has multiple submission buttons. i.e 'Submit', 'Deleted selected image' and 'View Selected Image'.
I posted a query on this site yesterday here, about about how to go about dealing with multiple 'submission' buttons and received some great advice.
I've tried to implement the advice I was given, but I just can't seem to get this to work. As the guidance suggested, I've added a name to each button and tried to call that through the PHP script, but all that happens is the page refreshes as if submitting the whole page, rather, than for example, being able to view the selected file.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Please find my PHP code & Form script below
<?php
$db_host = 'host';
$db_user = 'username';
$db_pwd = 'password';
$database = 'databasename';
$table = 'images';
// use the same name as SQL table
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//print_r($_FILES);exit;
if($_FILES["photo"]["error"] >= 4) {
$msg = '<b>Error!</b> - You <b> must </b> select a file before clicking the <b> "Upload This Image" </b> button. Please try again.';
}
else
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "gif", "jpeg" </b> or <b> "png" </b>. Please try again.';
if($_FILES["photo"]["size"]/1150000 >= 1) {
$msg = '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = '<b> Success! </b> - Your image has been uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['deleteimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
if (isset($_POST['viewimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
}
}
?>
<form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
<div align="left">
<!-- This form is used for image deletion -->
<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
echo '<ul><li>You have no images loaded</li></ul>';
else
{
echo '<ul>';
while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
{
// outputing list
echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
echo " <small>{$title}</small> &nbsp";
echo "<small>{$imagetime}</small></li>";
}
echo '</ul>';
echo '<input type="submit" value="Delete Selected Image" onclick="document.getElementById(\'action\').value=\'delete\'" />';
echo '<input type="submit" value="View Selected Image" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
<input type="hidden" name="action" id="action" />
</div>
</form>
Many thanks and kind regards
Where you're checking the $_POST action, you need to do this:
if ($_POST["viewimage"] == "View Selected Image") { // Do stuff }
if ($_POST["deleteimage"] == "Delete Selected Image") { // Do stuff }
Basically, you need to check $_POST['name'] == 'value'

Categories