Basically I have created a set of php files that have a simple job:
Allows a user to log in.
Allows that user to upload a file.
Then Allows the user to see all files they have uploaded.
Strangely though, when I upload a file through 1 user name, the file list result shows the same result 4 times then I uploaded a second file, it appeared 5 times. With another user it displays it 5 times.
I checked the place the files get stored after upload, and there is only 1 copy of each file there. Below is my code, any help?
index.php - This has login form, file upload form and finally the download list
<?
break;
}
?>
<?php if ($_SESSION['username']): ?>
<h1>Welcome, <?php echo $_SESSION["username"] ?></h1></br>
<?php
//include ("config.php");
//Connect to mysql server
$link = mysql_connect($host, $dbuser, $dbpwd);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db($dbname);
if(!$db) {
die("Unable to select database");
}
?>
Select File To Upload
<div style="width:100%; margin:5px;">
<form action="uploadclientfile.php" method="post" enctype="multipart/form-data" name="upload" style="margin:5px;">
<label> File</label>
<input name="uploaded_file" type="file" class="input-xlarge" required/>
<input type="hidden" name="" value="<?php $_SESSION['username'] ?>" />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /><br /><br />
<input name="Upload" type="submit" value="Upload" class="btn" />
</form>
</div></br></br>
File list:</br>
<?php
$userfiles = mysql_query("SELECT filename, filelocation FROM cfiles WHERE userid='{$_SESSION['username']}'" );
while ($row = mysql_fetch_assoc($userfiles)) {
$filename = $row['filename'];
$filelocation = $row['filelocation'];
echo "" .$filename . "<br />";
} ?>
<?php endif; ?>
Log-in | Log-out<br />
</body>
</html>
and also upload.php
<?php
session_start();
echo( "<pre>" );
print_r( $_POST );
print_r( $_FILES );
echo( "</pre>" );
$target = "userfiles/";
$target = $target . basename( $_FILES['uploaded_file']['name']);
$new_file_name = str_replace(' ', '_', $target);
//This gets all the other information from the form
$userid = $_SESSION['username'];
$file = basename( $_FILES['uploaded_file']['name'] );
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
//Writes the file to the server
if( #move_uploaded_file( $_FILES['uploaded_file']['tmp_name'], $new_file_name ) )
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploaded_file']['name'] ). " has been uploaded, and your information has been added to the directory.";
}
else
{
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
So there are the 2 main files used in this process. Any help as to why my file is appearing in the download list and mysql database multiple times? It is only appearing once in the folder it is stored.
This part of your code:
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
Loops through how ever many users you have and adds a new file entry for each. So if you have 5 users you add 5 entries into cfiles for the $userid of the person that's logged in. This will increase with more users.
Is this what you meant to do? You probably just want to add one entry for that user, and not other users, correct?
If you remove the loop and replace that code with this:
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
You'll only get one entry
This code confuses me:
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
//Writes the information to the database
mysql_query("INSERT INTO `cfiles` VALUES ('{$userid}', '{$file}', '{$new_file_name}')") or die( mysql_error() ) ;
}
What are you trying to do here? It appears that you're inserting the uploaded file into the database multiple times, one time for each user who exists. Why are you doing that? Is that why the file is appearing multiple times? (Seems likely to me)
Related
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 am trying to make a PHP form that will only allow the user to update the MySQL Table column photo, if the photo column is blank. Currently, the form will still update the photo column even if there is data other than "blank" data. For example, the photo column contains the data "columbia.jpg" and the user submits the form with the image "Jefferson.jpg" in the first input. The image column's data gets replaced from columbia.jpg to jefferson.jpg when it is not supposed to replace it at all. Instead it should return an error message stating that the user must first delete the old image before adding a new one. The column data should only get replaced when the column data is equal to "blank". (Not the word "blank" but "".)
Here is my full PHP page code:
<?php
if (isset($_GET["id"])) {
$sn = (int)($_GET["id"]);
?>
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
Photo 1: <input type="file" name="photo"><br>
<input name="add_image" id="add_image" type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
<?php
if(isset($_POST['add_image']))
{
$dbLink = new mysqli('daom', 'sm', 'aer', 'kabm');
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array=mysqli_fetch_assoc($result);
if($query = " "){
//Writes the information to the database
$query1 =
"UPDATE used_trailers ".
"SET photo = '$pic' ".
"WHERE id = $sn" ;
// Execute the query
$results = $dbLink->query($query1);
// Check if it was successfull
if($results) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to Photo 1, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your image.";
}
} else {
echo '<p>You must first delete the "Photo 1" image, $array, in order to add a new photo. This is to prevent the server from overloading with too many images.</p>';
}
}
}
echo "$query1";
?>
Thank you for any help. All help is appreciated.
There are some errors in your script. First of all if ($query = " ") will always return true, because you are assigning the variable $query the string " ". To correctly check this, you'd need to use if ($query == " ").
However, this won't solve your problem as $query is the query - not the result. This should work
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array = mysqli_fetch_assoc($result);
if (empty($array['photo'])){
//etc.
}
Back again with another newbie question. I've been working on a document that will allow users to upload their own avatars to a blog that I'm creating to learn some PHP. I've been working on this document for two days now and I've spent over six hours of searching and trying different things to fix it but I just can't get it to get past this:
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
It does send the "bad message" finally after about an hour of trying different solutions but I'm not quite sure why it is giving me the "bad message", to me everything looks okay.
FULL CODE:
<?php
session_start();
if (isset($_SESSION['username'])){
if (isset($_POST['submit']) && isset($_FILES['avatar'])) {
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('webserver', $con);
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$id = $row['id'];
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
}else{
echo "38";
}
}
?>
<form enctype="multipart/form-data" action='uploadavatar.php' method='POST'>
<table>
<tr>
<td>
Upload an avatar:
</td>
</tr>
<td>
<input type='file' name='avatar'>
</td>
</tr>
</table>
<p>
<input enctype='multipart/form-data' type='submit' name='submit' value='Submit'>
</p>
</form>
By the way I'm sorry there is probably a bunch of useless code in there, I have spent a bunch of time just getting it far enough to give me an error.
The location where the uploaded file is stored on disk is $_FILES['avatar']['tmp_name']. You want to move that, not $_FILES['avatar']['name'].
The problem here is that, you're using move_uploaded_file() in wrong way.
The first parameter requires a filename with its extension, without base path, like
mypic.jpg. The second requires a destination where that file should be uploaded.
As for your code,
Replace this,
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['temp'], $target)){
with
// I'd assume that dirname(__FILE__) refers to your root
//Directory to save stuff
$destination = sprintf('%s/images/useravatars/%s', dirname(__FILE__), $_FILES['avatar']['name']);
//Save the avatar
if (move_uploaded_file($_FILES['avatar']['tmp_name'], $destination)) {
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.
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