Any way to generate random file name when uploading? - php

I have created a website that uploads anything. The problem I have is that I'm new to all this. I have tried every code that generates random strings but I have nothing. Here is the code anyway:
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")) {
echo '<a href="uploads/'.$fileName.'"><input type="button" class="button"
value="Download" /></a>';
} else {
echo "move_uploaded_file function failed";
}
?>
Could there be a way to generate random file names so that when someone uploads the same name as a file already on the server, it does not overwrite the existing file?

$fileName = "image_".uniqid();
The uniqid() function generates a unique ID based on the microtime
(current time in microseconds).
About uniqid function: http://www.php.net/manual/en/function.uniqid.php

You can use md5(microtime()) to get unique file name even you uploading more than one file at a time

you can use microtime time to make sure file name is unique.
$file_name = "custom_name_" . microtime();

Because a folder is limited to 65535 files, you need to create subfolders. This technique creates 3 subfolders (with 3 characters each) depending on the timestamp then creates a random filename.
For more randomness and future-proofness (because using time() and microtime() is weak if you have multiple users uploading at the same time) :
//Get the extension of the file
$fileExtension = end(explode(".", $_FILES['item']['name']));
$randOctalName = openssl_random_pseudo_bytes(5);
$randName = bin2hex($randOctalName).".".$fileExtension;
//Save it into uploads/123/456/789/
$path = "";
$timestamp = time();
$path = substr($timestamp,0,3)."/".substr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;$timestamp = time();
$path = substr($timestamp,0,3)."/".ubstr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;
_r_mkdir($relativePath);
And the mkdir recursive function :
private function _r_mkdir($path, $mode = 0755, $recursive = true)
{
if(empty($path)){
return false;
}
if($recursive) {
$toDo = substr($path, 0, strrpos($path, '/'));
if($toDo !== '.' && $toDo !== '..'){
_r_mkdir($toDo, $mode);
}
}
if(!is_dir($path)){
mkdir($path, $mode);
}
return true;
}

use the timestamp (or microtime), so you know it is necessarily different every time
$fileName = "image_".time();
TimeStamp
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Microtime
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

//you can use both random and time function to get more unique no count:
$fileName = 'mypic'.mt_rand(100000, 999999).'_'.time(). $_FILES["file1"]["name"];
use are:-
mt_rand(100000, 999999)// for randm no.
time()// for timestring
$_FILES["file1"]["name"]//also you can give your file name

Study this code thoroughly. This is all you need.
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "")
{
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileError = $_FILES["avatar"]["error"];
$kaboom = explode(".",$fileName);
$fileExt = end($kaboom);
list($width,$height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10)
{
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 5048576)
{
header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
exit();
}
else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) )
{
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
}
else if ($fileErrorMsg == 1)
{
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx,$sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != "")
{
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl))
unlink($picurl);
}
$moveResult = move_uploaded_file($fileTmpLoc,"../user/$log_username/$db_file_name");
if ($moveResult != true)
{
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>

try this
$now=date('d/m/y');
if(move_uploaded_file($fileTmpLoc, "uploads/$now.$fileName"))
it will add date infront of the filename

Related

Get image width while uploading image PHP

in my code, while a user is uploading a pic, in my php code i want to read the width of the image while its getting uploaded, below is my code --
<?php
require_once('config.php');
$file_path = $_SERVER['DOCUMENT_ROOT']."AndroidApp/VideoUploads/Thumbnails/";
$emailid=$_GET['emailid'];
$randNum=$_GET['randNum'];
$ext = findexts ($_FILES['uploaded_file']['name']) ;
$thumb_url="DoUpNow_Funny_Video_Thumb"."_".$randNum.".".$ext;
$file_path = $file_path.$thumb_url;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
list($width) = getimagesize($_FILES['uploaded_file']['tmp_name']);
$stmt2 = $linkID1->prepare("update VideoUploads set video_thumb=?, width=? where emailid=? and randNum=?");
$stmt2->bind_param("ssss", $thumb_url,$width,$emailid,$randNum);
$stmt2->execute();
$stmt2->close();
echo "success";
} else{
echo "fail";
}
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
?>
The file is getting uploaded, but there is no value in the width variable, is anything wrong, or my approach is wrong.
After move_uploaded_file(), the tmp_name variable refers to a file which no longer exists, it was moved.
If the file is valid, it will be moved to the filename given by destination.
So, use $file_path to get your file informations :
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
list($width) = getimagesize($file_path);
try this code it's working fine
check this and let me
<?php
$image_info = getimagesize($_FILES["uploaded_file"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];
?>

Hash and upload an image file at the same time using php

I am trying to upload an image to a server using PHP and calculate the hash of the same image using md5_file. but somehow it is not referring to the directory either and not calculating the hash of the image.
Code:-
<html><body style="background-color:powderblue;">
<?php
session_start(); //declare you are starting a session
if(isset($_POST['submit'])){
include'connect.php';
$fname = $_POST['fi'];
$filename = $_FILES['fileupload']['name'];
$filetmp = $_FILES['fileupload']['tmp_name'];
$filesize = $_FILES['fileupload']['size'];
$file_basename = basename($_FILES['fileupload']['name']);
$dir = "upload/";
$final_dir = $dir.$file_basename;
$hash = md5_file($final_dir);
$_SESSION['hash'] =$hash;
$upload = move_uploaded_file($filetmp,$final_dir);
}
/* image_name= "$file_basename";
image_path ="$final_dir";
*/
/*Database Query*/**strong text**
if($filesize > 1024000){
echo("Greater then expected");
}
if($selected){
echo nl2br("Operation successful\n");
echo nl2br("URL Record successfully\n");
echo nl2br("$fname \n \n");
}
else{
echo("No No No ...");
}
?>
Just hash the temporary file before moving it to the final destination.
$hash = md5_file($filetmp);
...
$upload = move_uploaded_file($filetmp,$final_dir);

Saving Multiple File path to mysql using PHP

Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer

Issue with image uploading PHP

I'm trying to create a form where users can select an image and set their profile picture. After this I want to get this specific information and display it within HTML.
I have the following code inside profile.php;
if(isset($_POST['submit']) ){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$mysql->setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email);
}
I have the following code inside mysql.php (this code is inside a class name mysql):
function setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email){
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "Image is too small";
exit();
}
$db_file_name = rand(100000000000,999999999999) . "." . $fileExt;
echo $db_file_name;
if($fileSize > 1048576) {
echo "Image can't be larger than 1MB";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "The file extension should be .gif, .jpg or .png";
exit();
} else if ($fileErrorMsg == 1) {
echo "An unknown error occurred";
exit();
}
$sql = "SELECT avatar FROM users WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$s_email/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, SITE_ROOT . "/../user/$s_email/". $db_file_name);
if ($moveResult != true) {
echo "File upload failed";
exit();
}
$sql = "UPDATE users SET avatar='$db_file_name' WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
}
After this is done, I want to do something like:
<img src="user/" . $s_email . "/" . $data['avatar'] . " />
How ever, when I try to reach the avatar element from the MySQL database, I always get the same number, which is: 2147483647 (but in the user folder everything went right). So there is a problem with the value that is getting inserted into the database. Any suggestions what this problem might be?
EDIT: I've fixed the issue by decreasing the length of the random number. However, the problem is still that the value in the database hasn't receive the extension? The column datatype of avatar is VARCHAR.
It's this line:
$db_file_name = rand(100000,999999) . "." . $fileExt;
Yes, a nice feature of most random number generators is that they produce repeatable results unless you tell them not to.
In the case of PHP you tell it not to start at the same place using srand()
Your number is to big. and not very random.
$db_file_name = rand(100000000000,999999999999)
Your min and max are very close to each other/in wrong order, and to large because the number your getting 2147483647 = 2^30 -1 is most likely the size limit for the type of column input you decided to use for the name.
rand documentation http://php.net/manual/en/function.rand.php
Change your column type to something like varchar(40)
I'd also recommend not using random numbers greater than php's signed 32 bit integer rand(0,2147483647);

How to change name of uploaded file without changing extension

i'd like to change the name of uploaded file to md5(file_name).ext, where ext is extension of uploaded file. Is there any function which can help me to do it?
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
Use this function to change the file name to md5 with the same extension
function convert_filename_to_md5($filename) {
$filename_parts = explode('.',$filename);
$count = count($filename_parts);
if($count> 1) {
$ext = $filename_parts[$count-1];
unset($filename_parts[$count-1]);
$filename_to_md5 = implode('.',$filename_parts);
$newName = md5($filename_to_md5). '.' . $ext ;
} else {
$newName = md5($filename);
}
return $newName;
}
<?php
$filename = $_FILES['file']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = rand(0000,9999);
$newfilename=$new.$filename.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'],$newfilename))
{
//advanced code
}
?>
Find below php code to get file extension and change file name
<?php
if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') {
$ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1);
$imageName = time().$ext;
$normalDestination = "Photos/Orignal/" . $imageName;
move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination);
}
?>
This one work
<?php
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(0000,9999);
//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables
$new_file_name=$random_digit.$file_name;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
?>

Categories