Unique file name when uploading using uniqid() - php

I am trying to upload images from a cell phone and display them on a gallery page. I need each file name to be unique or images will overwrite themselves. I have the following code where $new_image_name is suggested from this topic but I can't seem to get it to work:
if ($_FILES["image"]["error"] > 0) {
//Bad Output for form results red text
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
} else {
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
$file="images/".$new_image_name);
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>
</form>';
}
mysql_close();
This was my code prior to adding uniqid() which worked fine except the images overwrote each other
} else {
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
$file="images/".$_FILES["image"]["name"];
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>
</form>';
}
mysql_close();

You should really get into the habit of using error checking. As your code sits right now I can upload ANYTHING and your code will save it as a jpg image.
Start by checking to see if the user even selected a file for upload.
Then compare the file type to a predetermined list of allowed file types.
Then save it as the file type that was uploaded. Which may not always be a jpg. As your code sits right now, if I upload a gif or png file... it will save it as a jpg. Thereby rendering the image useless because it is not a jpg.
Your upload process with error checking...
<?php
$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if(isset($_POST["upload"]) && $_POST["upload"] == 'changer') {
// set some basic variables
$fileName = $_FILES["image"]["name"]; // The file name
$fileTempLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$type = strtolower(substr(strrchr($fileName,"."),1));
if($type == 'jpeg' || $type == 'jpe') { $type = 'jprg'; } // make a jpeg or jpe file a jpg file
if (!$fileTempLoc) { // if no file selected
die ('<div align="center" style="color:#ff0000;"><br /><h3>ERROR: Please select an image before clicking the upload button.<br /><br />Try again</h3></div>');
} else {
// This is the allowed list (images only)
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/jpe',
'image/gif',
'image/png'
);
// check to see if the file being uploaded is in our allowed list
if(!in_array($_FILES['image']['type'], $acceptable) && !empty($_FILES["image"]["type"])) { // Is file type in the allowed list
die ('<div align="center" style="color:#ff0000;"><br /><h3>Invalid file type. Only JPEG, JPG, JPE, GIF and PNG types are allowed.<br /><br />Try again</h3></div>');
} else {
if ($_FILES["image"]["error"] > 0) {
//Bad Output for form results red text
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
} else {
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.'.$type;
move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
$file="images/".$new_image_name;
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>';
mysql_close();
} // end if no errors
} // end if in allowed list
} // end if no file selected
} // end if form submitted
?>
The form...
<form enctype="multipart/form-data" action="<?php echo $FormAction ?>" method="post" name="changer">
<input type="file" name="image" id="image" />
<input name="submit" type="submit" value="Upload">
<input type="hidden" name="upload" id="upload" value="changer" />
</form>
One final note... Do yourself a favor and stop using mysql. Start using pdo_mysql instead. mysql was deprecated in PHP version 5.5 and totally removed in PHP version 7. If you're using mysql code, your code will soon stop functioning completely.

I am assuming your posted working code, then maybe because of bellow line,
$file="images/".$new_image_name);
You added extra ')' remove that line, it may work fine.
$file="images/".$new_image_name;
Let me know issue is resolved.

Related

Why won't my image files upload in PHP?

I want my users to be able to upload images to their account (my MySQL database). However, when I try to encode it and upload it, it appears that the file was never uploaded and is empty. I have checked the maximum upload size etc. in my PHP settings. Thanks in advance!!
$data = "";
if(isset($_FILES["up"])) {
$data = file_get_contents($_FILES['up']['tmp_name']);
$data = base64_encode($data);
$data = $connection->real_escape_string($data);
} else {
echo '<div style="position:absolute;height:100px;top:0px;left:0px;
border-top-right-radius:20px;border-top-left-radius:20px;
width:100%;background:white;z-index:100;"
>
<font style="color:#BB0000;font-size:2.2vw;">'.$_FILES['up']['error'].'</font>
</div>';
die('');
}
My HTML is: (And the form submits correctly)
<input type="file" accept=".jpg,.png,.jpeg" name="up" id="up"/>
Suggestion: store the images in a directory.
why not DB you ask?
read/write to a DB is always slower than a filesystem
your DB backups will become more time consuming
so, here is my solution.
STEP 1: create a directory userPhotos
STEP 2: create a form
<form action="upload.php" method="post" enctype="multipart/form-data">
Select your profile picture:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="Upload" value="Upload Image" name="submit">
</form>
STEP 3: create a file called upload.php which handles file uploads.
<?php
$target_dir = "userPhotos/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$newfilename = ;//assign unique user ID
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
if (move_uploaded_file($_FILES["fileToUpload"][$newfilename.$imageFileType], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";$uploadOk = 1;
}
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if($uploadOK==1){
store the path of image in DB as "/userPhotos/".$newfilename
echo "uploaded photo : <img src='userphotos/".$newfilename."'">
}
//to display the image fetch the path using user ID as put it in src of img tag.
?>
Let me know if anyone has a better solution. thanks and Good luck.
PHP Code
$data = "";
if(isset($_FILES["up"])) {
$data = file_get_contents($_FILES['up']['tmp_name']);
$data = base64_encode($data);
$data = $connection->real_escape_string($data);
} else {
echo '<div style="position:absolute;height:100px;top:0px;left:0px;
border-top-right-radius:20px;border-top-left-radius:20px;
width:100%;background:white;z-index:100;"
>
<font style="color:#BB0000;font-size:2.2vw;">'.$_FILES['up']['error'].'</font>
</div>';
die('');
}
HTML Code
<form method="POST" enctype="multipart/form-data">
<input type="file" accept=".jpg,.png,.jpeg" name="up" id="up"/>
</form>

Problems when uploading two times using same function php

I'm having problems with a file upload script for my site. I've copied a simple upload script, and I'm setting it up so that I can upload multiple files. I have to do this by first making one form for one file, then a copy of the form for the next one and so one. (I first set the page up with the "multiple" tag in the form, but then i discovered that the IE at work is version 8, and no flash. So I have to do it this way)
The scripts uploads ok. The problem is that the second file is called file1.jpgfile2.jpg, the third one file1.jpgfile2.jpgfile3.jpg and so on.
this is my form, followed by the code with form #2 File #2 and on goes through the same form:
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=addpicturetoproc">
<input type="hidden" name="uploadpath" value="<? echo "Prosedyrer/$hovedkategori/$underkategori/$navn/$mappe_navn/" ?>">
Bildefil: <input type="file" name="fileup" value=""><br>
<input type="submit" name="submit" value="Upload">
</form>
<br>
<?
}
elseif ($choice=="addpicturetoproc")
{
$max_size = 2000; // maximum file size, in KiloBytes
$alwidth = 1900; // maximum allowed width, in pixels
$alheight = 1800; // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png'); // allowed extensions
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
echo '<h1>Filen: <b>'. basename( $_FILES['fileup']['name']). '</b> ble lastet opp!</h1>';
}
else echo '<b>Feil ved opplastning.</b>';
}
else echo $err;
}
?><p>Do you need another upload?</p>
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=addpicturetoproc">
<input type="hidden" name="uploadpath" value="<? echo $uploadpath; ?>">
Bildefil: <input type="file" name="fileup" value="Sett inn bildefilen her"><br>
<input type="submit" name="submit" value="Last opp bildefil">
</form>
<br>
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=menu">
<input type="submit" name="submit" value="Nei, jeg er ferdig">
</form>
I have tried using unset($fileup); before the second run, but still filename1.jpgfilename2.jpg.
Any obvious solutions?
I believe this is because you're appending to the $uploadpath
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
So the first file will be file1.jpg then the second file will be file1.jpgfile2.jpg and so on.
I would suggest setting the base upload path to a different variable and trying something like
$uploadpath = $baseuploadpath . basename( $_FILES['fileup']['name']);

How to store image link in database php/mysql

I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".

How to save uploaded image in database

I need help in writing this code to upload and save uploaded image in data base.
File 1:
<?php
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
<iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
File 2:
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path="my/";
$result = 0;
$name=$_FILES['myfile']['name'];
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
$result = 1;
}
// sleep(1);
$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');
if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {
// define the posted file into variables
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$type = $_FILES['myfile']['type'];
$size = $_FILES['myfile']['size'];
// if your server has magic quotes turned off, add slashes manually
//if(!get_magic_quotes_gpc()){
//$name = addslashes($name);
//}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, filesize($tmp_name));
$content = addslashes($content);
fclose($extract);
// connect to the database
// the query that will add this to the database
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}
?>
Technically, if it is a small project.
You should not store images files in "Database" ; rather only their link (you may not even need that). Image or any media files are stored on server along with your other files (html,css,php). Of course, you need to put them on a dedicated folder for it.
The reason for not storing on database : because they are meant for data retrieval only and more importantly they are of smaller size (bigger sizes do exist, i am speaking in case of a small project which requires least possible resources. Storing media files on database is just not efficient.
Looking at your code, i can tell you are trying to store the files on your server.
They have used a very simple script for uploading here . Try it on your localhost before trying on a server.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) is incorrect.
It should be if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))
Remove the #.
I have created three page for it
index.php (Form for uplad image)
upload.php (Save the image in upload folder and its path in database)
3.showimage.php (Show the images from database)
Database Structure
id int(4) auto increment - image varchar(100) - image_name varchar(50)
here is the code:
index.php
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" />
</form>
uplad.php
<?php
$target_Folder = "upload/";
$uid = $_POST['id'];
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('upload/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO image (id,image, image_name)
VALUES ('','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
showimage.php
<?php
$con=mysqli_connect("localhost","user_name","password","test"); //Change it if required
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM image " );
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';
}
mysqli_close($con);
?>

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories