Giving uploaded images a unique name for mysqli - php

I want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..
Here is my code:
if(isset($_POST['submitimage'])){
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Any help would be amazing. Thank you!

My solution is to generate a random string for each uploaded file, i.e.:
<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}
function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}
?>

PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
?>
Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension
$uploadfile = tempnam_sfx($uploaddir, $ext);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
?>

One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.
if(isset($_POST['submitimage'])){
//generate 3 sequences of random numbers,you could do more or less if you wish
$randomNumber=rand().rand().rand();
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Note : you could also look into generating random strings if numbers are not your thing.

Related

What's wrong?, I want to copy the image file to my other directory after upload, and input it to the mysql database too

this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission

Using move_uploaded_file To Rename File BEFORE Being Placed In uploads/ Folder

I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

PHP image upload and assignment of unique file name

Thank you in advance. I've checked similar questions and they are not helping because the work flow is set up differently.
Trying to get working:
1.user uploads image via form field
2.(SCRIPT 1) on other page script assigns unique name (SCRIPT 2), saves image file to server and image URL is uploaded to SQL. Goes to new page at end of script.
Problem is I'm not getting errors, the script runs and the new page opens but there is no file saved on the server and no data inserted into the SQL table (the entry date adds but not the image URL). My PHP.ini instructions far exceeds the size of the images I've been testing with. The folder location is chamode 0777. I'm posting the whole script because with getting errors it's hard to see where problem lies.
Image processing
<?php
require_once 'unique_gen.php';
$page_path = $_POST['page_path'];
$imgloc = "/avatars/";
//up one directory level
$store_loc = "..".$imgloc;
$link_loc = "http://www.webapge.com".$imgloc;
//Upload and characterize image file
if(isset($_FILES['image'])){
//File
$upload['image'] = $_FILES['image'];
//Verify
if ($upload['image']["error"] > 0){
die ("File Upload Error: " . $upload['image']["error"]);
}else{
//Upload
$img_ext = end(explode('.', $upload['image']['name']));
//Unique code generator
$image_name = implode('.', array(unique_generator(),$img_ext));
while(file_exists($store_loc.$image_name)){
$image_name = implode('.', array(unique_generator(),$img_ext));
}
$image_name = $upload['image']['name'];
//Move file to another location
move_uploaded_file($upload['image']["tmp_name"],$store_loc.$image_name) or exit("<br>Error, IMAGE file not moved!");
//Save location as link
$link_to_img = $link_loc.$image_name;
}
}else{
$image_name = "";
}
//connect to db
$con=mysqli_connect("localhost","usernm","pssword","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert to SQL
$sql="INSERT INTO comments (avatar, entry_date)
VALUES
('$_POST[link_to_image]', now())";
//verify insert
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//direct to new page using variable
header('Location: http://www.weBsite.com/' . $page_path);
//close session
mysqli_close($con);
?>
Unique generator
<?php
function unique_generator($lot_size = 15){
$alpha_s = range('a', 'z');
$alpha_l = range('A', 'Z');
$numbers = range(0, 9);
$char = array_merge($alpha_l,$alpha_s,$numbers);
$code = "";
for($i = 0; $i < $lot_size; $i++){
$key = rand(0,count($char)-1);
$code .= $char[$key];
}
return $code;
}
?>
Try putting this at the top of your script:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
This at the bottom:
<?php
print_r(array_keys(get_defined_vars()));
print_r(array_values(get_defined_vars()));
?>

Does tmp_name disappear after move_uploaded_file is used?

I have this page where you can send message to multiple people and attach files into it...
Here is my code
<?php
session_start();
$inboxfrom = $_SESSION['loginusername'];
$inboxto = $_POST['inboxto'];
$inboxsubject = $_POST['inboxsubject'];
$inboxcontent = $_POST['inboxcontent'];
$inboxtime = date('g:i A', time()+(6*60*60));
$inboxdate = date('Y-m-d', time()+(6*60*60));
mysql_connect("127.0.0.1", "root", "")or die("Cannot Connect toDb");
mysql_select_db("Abbot_db");
$count = 0;
function generateRandomString($length = 8){
$string = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //character that can be used
for($i=0;$i < $length;$i++){
$char = substr($possible, rand(0, strlen($possible)-1), 1);
if (!strstr($string, $char)){
$string .= $char;
}
}
return $string;
}
if (count($inboxto) != 0){
$count = 0;
while ($count < count($inboxto)){
$recepient = $_POST['inboxto'][$count];
mysql_query("INSERT INTO Inbox_tbl(InboxTo, InboxFrom, InboxSubject, InboxContent, InboxTime, InboxDate,InboxStatus,ToDelete,FromDelete)VALUES ('$recepient','$inboxfrom','$inboxsubject','$inboxcontent','$inboxtime','$inboxdate','Unread','No','No')");
$recepient_result = mysql_query("SELECT * FROM Accounts_tbl WHERE UserID='$recepient'");
if (mysql_result($recepient_result, 0, "UserTypeID") == 1){
$notiurl = "LMSadmin_inbox.php";
} else if (mysql_result($recepient_result, 0, "UserTypeID") == 2) {
$notiurl = "LMSteacher_inbox.php";
} else {
$notiurl = "LMSstud_inbox.php";
}
mysql_query("INSERT INTO Noti_tbl(NotiTo,NotiFrom,NotiContent,NotiDate,NotiTime,NotiType,NotiUrl)
VALUES('$recepient','$inboxfrom','has sent you a message','$inboxdate','$inboxtime','Message','$notiurl')");
//---------------------------------------------------------
$countto = 0;
$cont = generateRandomString(128);
$folder = "./Attachments/".$cont;
$name = $_FILES['file']['name'];
if (!empty($name)){
while (is_dir($folder)){
$cont = generateRandomString(128);
$folder = "./Attachments/".$cont;
}
mkdir($folder, 0700, true);
}
while ($countto < count($_FILES['file']['name'])){
$name = $_FILES['file']['name'][$countto];
$type = $_FILES['file']['type'][$countto];
$tmp_name = $_FILES['file']['tmp_name'][$countto];
$folder = "Attachments/".$cont."/";
move_uploaded_file($tmp_name, $folder.$name);
$fileurl = $cont."/".$name;
$dummypost = mysql_query("SELECT * FROM Inbox_tbl ORDER BY InboxID DESC");
$msgid = mysql_result($dummypost, 0, "InboxID");
mysql_query("INSERT INTO Attachments_tbl(FileUrl,FileName,AttachType,AttachID)
VALUES('$fileurl','$name','Message',$msgid)");
$countto++;
}
//----------------------------------------------
$count++;
}
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
now the result after I put multiple recepients and multiples is that... The first recepient will get the attachments.. meaning the folder of attachment will be randomy generated and the files would be put in there.... but on the next recepient the attachments would not be moved on their respective folder.. I can see the folder have been made but the files arent moved..
MY question is.. does the "temp_name" disappear after you use the "move_uploaded_file" code? Because I think thats is the reason the files arent not move.. Is so can you suggest any alternate code i can use?
move_uploaded_file() relocates the file to the set target location with rendering the tmp_name useless afterwards.
What you should do is to create a "puffer" folder where you originally move the uploaded file, and then call copy() as many times as you need to deliver the file to the recipient folders. When the file is put to every needed location, you can unlink() the file from this puffer folder.
Alternatively, you might put the file to only one location (to eliminate redundancy and overuse of storage space), and make links in your Attachments_tbl to this same file in a set attachments folder. However, this needs remodelling of how your system works to make sure that the (now one and only) attachment file is only removed after every record pointing to it is removed also.
Yes, the file is moved, this is why you can't find it. I suggest that you:
Move the inner while loop (the one for the uploaded files) before the first while loop (for the recipients), and move the uploaded files to a location that you specify
Create a new inner while loop that copies the files from the location you specified earlier to each user's attachments folder

Categories