Changing php image upload filename to a specific name - php

I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>

Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.

Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;

Related

Change name of uploaded file

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

PHP assign each multiple uploaded files to variable

How can I separate multiple uploaded files ($new_file_name) out of foreach loop for sql query process? How to assign each files to its variable?
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.$new_file_name;
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', $new_file_name);
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//here I needed to get each of the uploaded images to update database (max 3 images)
//how to explode above $new_file_name into variable here?
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
I can get each of the file by
$var0 = $_FILES['files']['name'][0];
$var1 = $_FILES['files']['name'][1];
$var2 = $_FILES['files']['name'][2];
but I can't
$var0 = $new_file_name[0];
$var1 = $new_file_name[1];
$var2 = $new_file_name[2];
Thanks for advise!
Use this to set the name:
$new_file_name[] = rand(1, 999999).'.'.$ext;
and inside the for loop use:
end($new_file_name)
for the current file. E.g:
$pathfile = $output_dir.'/'.end($new_file_name);
The problem you are having is because in every iteration through the loop you setup the $new_file_name to a new random string. By using $new_file_name[] you are adding an element to $new_file_name which is then becoming an array. Using the end() functions returns the last element of the array so in the current iteration of the loop it will return the last added random string which corresponds to your current file;
EDIT:
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name[] = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.end($new_file_name);
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', end($new_file_name));
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//Getting the variables
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
You could also use: $new_file_name[0] inside the SQL query.

Upload images and file extension missing on mysql field

I have this piece of code that executes a multi image upload and renaming it.
it works, The file is renamed correctly, but I do not understand why in the mysql database I do not have the file extension but only the name.
Example:
file name (folder): abcdefg.jpg
pd_image (mysql field): abcdefg
$resultname is the same for both
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image);
$extension = end($parts);
$resultname = str_replace("." . $extension,"",$image);
$handle->file_new_name_body = $resultname;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 800;
$handle->image_y = 600;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (pd_id, file_name, pd_image) VALUES('$pd_id','$mainame','$resultname')";
$result2 = dbQuery($query_img);
I am using the class "class.upload.php"
Check this line, You are replacing the extension with the "".
$resultname = str_replace("." . $extension,"",$image);
Replace this line to
$resultname = $image.'.'.$extension;
your are giving variable $db_name as string.Correct way to concatenate the variable to another string is
$image = md5(rand() * time()).$db_name;

how to add number in picture when upload if same file name of picture

I have this code for upload
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photo/" . $_FILES["image"]["name"]);
$location="photo/" . $_FILES["image"]["name"];
then the insert $location code for sql to add
The Question is how to have my picture file name number add ex: if i have "Picture.jpg "uploaded if i will upload again and same file name the output of the filename will be Picture(1).jpg and if I upload again with the same file name the output filename will be Picture(2).jpg and so on I want the "()" to increment if ever i will upload same file name. thanks in advance ^^
This can be achived with loop:
$info = pathinfo($_FILES['image']['name']);
$i = 0;
do {
$image_name = $info['filename'] . ($i ? "_($i)" : "") . "." . $info['extension'];
$i++;
$path = "photo/" . $image_name;
} while(file_exists($path));
move_uploaded_file($_FILES['image']['tmp_name'], $path);
You should also sanitize input file name:
string sanitizer for filename
Sanitizing strings to make them URL and filename safe?
If you want to have a unique image name after upload even if they have same name or they are uploading in loop means multiple upload.
$time = time() + sprintf("%06d",(microtime(true) - floor(microtime(true))) * 1000000);
$new_name=$image_name.'_'.$time.'.'.$extension
You can add the image name with a unique time stamp which differ each nano seconds and generate unique time stamp
This code is untested, but I would think something along the lines of:
if (file_exists('path/to/file/image.jpg')){
$i = 1;
while (file_exists('path/to/file/image ('.$i.').jpg')){
$i++;
}
$name = 'image ('.$i.');
}
And then save the image to $name. (which at some point will result in image (2).jpg)
try this
$path = "photo/" . $_FILES["image"]["name"];
$ext = pathinfo ($path, PATHINFO_EXTENSION );
$name = pathinfo ( $path, PATHINFO_FILENAME ] );
for($i = 0; file_exists($path); $i++){
if($i > 0){
$path = "photo/" .$name.'('.$id.').'.$ext;
}
}
echo $path;
Can you try this,
$name = $_FILES['image']['name'];
$pathinfo = pathinfo($name);
$FileName = $pathinfo['filename'];
$ext = $pathinfo['extension'];
$actual_image_name = $FileName.time().".".$ext;
$location="photo/".$converted_name;
if(move_uploaded_file($tmp, $location))
{
}

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