This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
files get uploaded just before they get cancelled
I have a situation when it comes to cancelling a file upload. What is suppose to happen is that if the user clicks on the "Cancel" button, then it will go to script below and remove the file from the server and delete the file's records from the database:
cancelaudio.php
<?php
session_start();
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
unlink("AudioFiles/" . $_SESSION['AudioFile']); //undefined notice
$delete = $mysqli->prepare('DELETE FROM Audio WHERE AudioId = ?');
$delete->bind_param("i",$_SESSION['lastAudioID']);
$delete->execute();
$deleteaud = $mysqli->prepare('DELETE FROM Audio_Question WHERE AudioId = ?');
$deleteaud->bind_param("i",$_SESSION['lastAudioID']);
$deleteaud->execute();
?>
Now this is the situation I am having:
If I clean my cookies, it means obviously I have no files stored my $_SESSION variable. Now if I try to upload a file (first file) but then cancel it, then I get an undefined index notice for "AudioFile". This is fair as obviously I have no file stored in that $_SESSION variable. But the problem is that it does not perfrom the unlink() and DELETE statement in the code above so it will display the record of the file and still uploads it.
So what is happening is that until I have one file in the server and a file stored in the $_SESSION['AudioFile'], it would not remove the file from the server and and it would delete the record from the database.
So what my question is that what do I need to do so that if there is no file in the $_SESSION['AudioFile'] and the user uploads and then cancels a file, how can I stop it from inserting the file into the server and inserting the database record?
Below is the code where it uploads the files and inserts the data into the database:
audioupload.php
<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if( file_exists("AudioFiles/".$_FILES['fileAudio']['name'])) {
$parts = explode(".",$_FILES['fileAudio']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("AudioFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileAudio']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
$audiosql = "INSERT INTO Audio (AudioFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($audiosql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$aud);
//Assign the variable
$aud = 'AudioFiles/'.$_FILES['fileAudio']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastAudioID = $mysqli->insert_id;
$_SESSION['lastAudioID'] = $lastAudioID;
$_SESSION['AudioFile'] = $_FILES["fileAudio"]["name"];
$audioquestionsql = "INSERT INTO Audio_Question (AudioId, QuestionId)
VALUES (?, ?)";
if (!$insertaudioquestion = $mysqli->prepare($audioquestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err audioquestion";
}
$qnum = (int)$_POST['numaudio'];
$insertaudioquestion->bind_param("iii",$lastAudioID, $qnum);
$insertaudioquestion->execute();
if ($insertaudioquestion->errno) {
// Handle query error here
}
$insertaudioquestion->close();
?>
Below is the HTML form for the file input:
<form action='audioupload.php' method='post' enctype='multipart/form-data' target='upload_target_audio' onsubmit='return audioClickHandler(this);' class='audiouploadform' >
Audio File: <input name='fileAudio' type='file' class='fileAudio' /></label><br/><br/><label class='audiolbl'>
<input type='submit' name='submitAudioBtn' class='sbtnaudio' value='Upload' /></label>
<input type='hidden' class='numaudio' name='numaudio' value='" + GetFormAudioCount() + "' />
<label><input type='reset' name='audioCancel' class='audioCancel' value='Cancel' /></label>
<iframe class='upload_target_audio' name='upload_target_audio' src='#' style='width:300px;height:300px;border:0px;solid;#fff;'></iframe></form>
Finally below is the jquery function where if the user clicks on the "Cancel" button while the file is uploading, it will simply change the iframe source to "cancelaudio.php":
function startAudioUpload(audiouploadform){
$(audiouploadform).find('.audiof1_upload_process').css('visibility','visible');
$(audiouploadform).find('.audiof1_upload_form').css('visibility','hidden');
sourceAudioForm = audiouploadform;
$(audiouploadform).find(".audioCancel").on("click", function(event) {
$('.upload_target_audio').get(0).contentwindow
$("iframe[name='upload_target_audio']").attr("src", "cancelaudio.php");
return stopAudioUpload();
});
return true;
}
To get rid of your undefined index stuff, plus make your script a lot more robust, you SHOULD add error checking. Even a simple
if ($_FILES['fileAudio']['error'] === UPLOAD_ERR_OK) {
... successful upload ...
}
would reduce a lot of your problems. Right now your code simply assumes a successful upload, without even bothering to check if an upload was event attempted.
The various error codes for failure are defined here: http://php.net/manual/en/features.file-upload.errors.php
Related
I have a PDO prepared statement that I use on a single-image page where a user is going to be able to download that specific image. I currently have a counter that increments each time the download button is clicked which updates a counter value in a MySQL database. I'd like to transfer and use the download counter from the single-image page onto an index page that shows multiple images.
Because the form element is inside a while loop when you click the download button, the current functionality updates the counter for all of the images on this page (i.e. everything inside the loop).
Obviously I don't think I can move it outside of the loop because it then won't update anything at all?
How do I get it so the when the download button is clicked for a particular instance of the form, it only updates that specific form elements details?
PHP
<?php
// get username from URL parameter
isset($_GET['username']) ? $username = $_GET['username'] : header("Location: index.php");
// fetch filename details from database
$stmt = $connection->prepare("SELECT * FROM imageposts WHERE username = :username");
$stmt->execute([':username' => $username]);
while ($row = $stmt->fetch()) {
$db_image_filename = htmlspecialchars($row['filename']);
// -- HTML that shows the image file goes here --
// update counter for number of downloads of an image
if (isset($_POST['download'])) {
try {
$sql = "UPDATE imageposts SET downloads = downloads +1 WHERE filename = :filename";
$stmt = $connection->prepare($sql);
$stmt->execute([
':filename' => $db_image_filename
]);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
// download button that updates the counter
<form method="post">
<button type="submit" name="download">Download</button>
</form>
<?php } ?>
One way to approach this is to add some PHP outside of your loop, that references a value from a hidden <form> element inside the loop - in this case you have a $db_image_filename value you could use.
<form method="post">
<button type="submit" name="download">Download</button>
<input type="hidden" name="hidden-filename" value="<?php echo $db_image_filename; ?>">
</form>
Then reference this value in PHP:
<?php
if (isset($_POST['download'])) {
// value from hidden form element
$hidden_filename = $_POST['hidden-filename'];
try {
$sql = "UPDATE imageposts SET downloads = downloads +1 WHERE filename = :filename";
$stmt = $connection->prepare($sql);
$stmt->execute([
':filename' => $hidden_filename
]);
header("location: " . $_SERVER['PHP_SELF']);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
I have a code in php with validation ok all working properly but my problem is that when I try to save in database I obtain something like this:
img_id img_small img_big
5 /tmp/phpdlYkiG /tmp/phph3dhka
I don't know why php save that name because the images have a diffent names like koala.jpg and horse.jpg
Here is my code in order to see if somebody have any suggestion...
<form enctype="multipart/form-data" action="upload_type_1.php" method="POST" >
<input type="file" name="img_small_1" id="img_small_1">
<input type="file" name="img_big_1" id="img_big_1">
<input type="submit" value="Upload" name="submit">
</form>
and this is my php code:
if ( (move_uploaded_file($_FILES["img_small_1"]["tmp_name"], $target)) && (move_uploaded_file($_FILES["img_big_1"]["tmp_name"], $target2)) ){
$img_title_1 = $_POST['img_title_1'];
$sql = "INSERT INTO press (img_title, img_small, img_big) VALUES ('$img_title_1', '$img_small_1', '$img_big_1')";
$retval = mysql_query( $sql, $conn );
if(!$retval) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo "Your files has been uploaded";
} else {
echo "Sorry, there was an error uploading your files.";
exit;
}
This code work properly the only problem is that save into database that strange names and I need to use that names...
Thanks! - Waiting for help!
Your issue is probably not in the code that you are showing but in the code you are not showing, which is your variable declarations for $img_small_1 && $img_big_1. Taking a guess you have
$img_small_1 = $_FILES["img_small_1"]["tmp_name"];
$img_big_1 = $_FILES["img_big_1"]["tmp_name"];
but you want/need
$img_small_1 = $_FILES["img_small_1"]["name"];
$img_big_1 = $_FILES["img_big_1"]["name"];
$img_title_1 = $_POST['img_title_1'];
Should be:
$img_title_1 = $_FILES["img_small_1"]["name"]
A Simple Example of File Uploading
$uploadDir = "Your_upload_dir";
$img_small = $_FILES['img_small_1'];
$img_small_name = $img_small['name']; // get image name
$img_small_tmpName = $img_small['tmp_name'];
$img_small_fileSize = $img_small['size'];
$img_small_fileType = $img_small['type'];
if ($img_small['error'] == 0)
{
$img_small_filePath = $uploadDir . $img_small_name;
$result = move_uploaded_file($img_small_tmpName, img_small_filePath); //return true or false
}
I'm having trouble with a PHP script which apparently is getting errors from one single line. The top line in this bit of code is apparently causing quite a bit of trouble:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
header("Location: index.php");
}
The errors I'm getting for the top line of code:
Warning: Unexpected character in input: ' in cms/new.php on line 131
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at cms/new.php:131) in cms/new.php on line 85
First I thought CHmodding the upload folder to 777 would solve this error, but apparently it doesn't. I really don't know what to do anymore. Is there anyone who can help?
The complete block of code that includes the little snippet above:
<?php
}
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
include("config.php");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
//set root
$root = getcwd ();
// get form data, making sure it is valid
$inmenu = mysql_real_escape_string(htmlspecialchars($_POST['inmenu']));
$pagid = strtolower(str_replace(" ", "-", mysql_real_escape_string(htmlspecialchars($_POST['pagid']))));
$titlename = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$contentname = mysql_real_escape_string(htmlspecialchars($_POST['contentedit']));
$youtube = mysql_real_escape_string(htmlspecialchars($_POST['youtube']));
// check to make sure both fields are entered
if ($titlename == '' || $pagid == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($pagid, $titlename, $contentname, $error);
}
else
{
if(file_exists($root."/upload/".$_FILES["image"]["name"]))
{
$filename = explode(".",$_FILES['image']['name']);
$randomnumber = rand(0, 10000);
$imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
$imageName = $_FILES['image']['name'];
}
$image = mysql_real_escape_string(htmlspecialchars("/upload/".$imageName));
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
else {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
When using double quotes you can just insert PHP variables so
Try this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
$query = "INSERT " . $pages . SET inmenu=$inmenu, pagid=$pagid, title=$titlename, contenct=$contentname, image=$image, youtube=$youtube";
mysql_query($query) or die(mysql_error());
header("Location: index.php");
}
Another way (if you'd like) would be this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='".$inmenu."', pagid='".$pagid."', title='".$titlename."', content='".$contentname."', image='".$image."', youtube='".$youtube."'")
or die(mysql_error());
header("Location: index.php");
}
I've a form with upload field, it works fine. it uploads and everything is good, except that when the upload field is empty. the field in the database table goes blank as well, nothing in it, not even the old image entry!
My Form:
<form enctype="multipart/form-data" action="add.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="site_logo"><br>
<input type="submit" value="Add">
</form>
The PHP code:
<?php
$target = "../upload/";
$target = $target . basename($_FILES['site_logo']['name']);?>
<?php
move_uploaded_file($_FILES['site_logo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
the query:
$site_logo=($_FILES['site_logo']['name']);
$query = "UPDATE ss_settings SET
site_logo = '{$site_logo}'
WHERE id = 1 ";
$result = mysql_query($query, $connection);
I've set the database connection and the update query and everything. just posted the process code so it be clear to you guys. I just want it to do nothing when the field is empty.
Check out the error messages explained http://www.php.net/manual/en/features.file-upload.errors.php
To check if a file wasn't uploaded:
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_NO_FILE)
A better way, is to check if there were no errors.
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
If your query is an UPDATE statement you should not change it, also you can try with
<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
// do stuff when no file field is set
}else{
// do stuff when file is set
}
// ...
?>
Personally I would not use an un-sanitized name for a file, but all you need to do in your case, is check for a valid file-upload before you do your query.
So something like (in PDO as the mysql_* functions are deprecated):
// first line borrowed from #DaveChen, +1 for that
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
{
$stmt = $db->prepare("UPDATE `ss_settings` SET
`site_logo` = :site_logo
WHERE `id` = :id ";
// bind variables
$stmt->bindValue(':site_logo', $_FILES['site_logo']['name'], PDO::PARAM_STR);
$stmt->bindValue(':id', $the_ID, PDO::PARAM_INT);
// execute query
$stmt->execute();
}
Perhaps try something like this to prevent processing of blank uploads:
if($_FILES['site_logo']['error']==0) {
// process
} else {
// handle the error
}
http://php.net/manual/en/features.file-upload.errors.php
Your problem is that you're simply assuming that a successful upload has taken place. NEVER assume success. ALways check for failure. PHP provides the ['error'] parameter in $_FILES for a reason. use it:
if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
... upload was successful
} else {
die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
You'll wan to check for code 4 (UPLOAD_ERR_NO_FILE), which means the user didn't upload anything at all.
look at this code
<?
require_once("conn.php");
require_once("includes.php");
require_once("access.php");
if(isset($_POST[s1]))
{
//manage files
if(!empty($_FILES[images]))
{
while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value))
{
$NewImageName = $t."_".$value;
copy($_FILES[images][tmp_name][$key], "images/".$NewImageName);
$MyImages[] = $NewImageName;
}
}
if(!empty($MyImages))
{
$ImageStr = implode("|", $MyImages);
}
}
$q1 = "insert into class_catalog set
MemberID = '$_SESSION[MemberID]',
CategoryID = '$_POST[CategoryID]',
Description = '$_POST[Description]',
images = '$ImageStr',
DatePosted = '$t',
DateExp = '$_SESSION[AccountExpDate]',
FeaturedStatus = '$_POST[sp]' ";
//echo $q1;
mysql_query($q1) or die(mysql_error());
}
//get the posted offers
$q1 = "select count(*) from class_catalog where MemberID = '$_SESSION[MemberID]' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);
header("location:AddAsset.php");
exit();
?>
The mySql insert function isn't adding anything also it return success to me , I've tried using INSERT ... Values but what it done was overwtiting existing value ( i.e make 1 entry and overwties it everytime).
I am using PHP 4.4.9 and MySql 4
I tried to add from Phpmyadmin and it is working also it was working after installation but after i quit the browser and made a new account to test it it is not working but the old ones is working ! you can see it here http://bemidjiclassifieds.com/
try to login with usr:openbook pass:mohamed24 and you can see it will be working but any new account won't work!
Maybe $_POST[s1] is not set or you are inserting into a different database than you are watching.
if(isset($_POST[s1]))
should probably be
if(isset($_POST['s1']))
(note the quotes). Also, it's best to NOT depend on a field being present in the submitted data to check if you're doing a POSt. the 100% reliable method is
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
As well, you're not checking if the file uploads succeeded. Each file should be checked like this:
foreach($_FILES['images']['name'] as $key => $name) {
if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
echo "File #$key failed to upload, error code {$_FILES['images']['error'][$key]}";
}
...
}
Don't use copy() to move uploaded files. There's a move_uploaded_files() function for that, which does some extra sanity checking to make sure nothing's tampered with the file between the time the upload finished and your script tries to move it.