PHP has a built-in function to create unique files on your server. This function is called tempnam () . If you carefully read the comments on this website, there is a small chance that you will get unwanted behavior from this function if many processes call it at the same time. Thus, the modification of this function will 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; } ?>
Since the file remains open during its creation, it cannot be accessed by another process, and therefore it is impossible to create 2 files with the same name, simply because several visitors to your site accidentally uploaded images at exactly the same moment. Therefore, 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"); ?>
icecub May 29 '16 at 23:18 2016-05-29 23:18
source share