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
}
Related
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.
}
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)
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 is suppose to be pretty straight forward and is driving me mad!
I'm trying to upload a file in PHP and writing the file to MySQL as a blob.
Problem is that the site throws a "Undefined index" all the time when I'm trying to use the
$_FILES['file']['tmp_name'] property.
Here is my code :
<head>
<title>Upload Worksheet</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000" />
File :
<input type="file" name"file" id="file"><input type="submit" value="Upload">
</form>
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
?>
</body>
This is what the error message looks like :
I haven't even gotten to the database side, as I can't get past this stage.
I'm a PHP noob, so any help would be greatly appreciated!
You recieve that error message because the form is not sent, yet. When you hit the upload button, the form is sent to your server and PHP populates the $_POST and $_FILES array with data. However, the arrays are empty until that point. It is therefore good practice to check whether or not your data is set, like so:
if (isset ($_POST['upload']))
{
// upload logic here
if(!isset($_FILES['file']) || ($_FILES['file']['tmp_name'] == ''))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
This assumes you have a submit button named "upload".
The Above answer is perfect because you should check the for post values in order to run any code on those values but you can also try the following
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
if(isset($_POST))
{
if(array_key_exists('file',$_FILES))
{
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
?>