Adding random number to uploaded file in PHP - php

I have my upload php code where my intent is , obtained file from $_files,
add a random number between 0 and 9999 to the name of image like this:
image sent : image.jpg
before saving : image321.jpg
the image is saved in my upload folder but the filename are like
"php2983204tmp"
if ($file !== null) {
$rand = rand(0000,9999);
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
any ideas to fix?

The filename in your example is php and your extension is tmp. None of them have the . that you are missing.
You need to add the dot . as a string after the $file_name and $rand, before the $extension like this:
$file->move($path, $file_name.$rand. "." .$extension);

TIME is always unique identity, use it as below (maybe helpful):
if ($file !== null) {
$rand = rand(0000,9999).time();
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);

You need add in the desired chars to the actual string.
$file->move($path, $file_name.$rand.".".$extension);
But I have to say, I am against how you've done this, you don't even check if the "newly" created string already exists in the directory. Its better to hash the time of upload with the original filename, rename the file to the new hash and use a database to point to the file as this way the filename collisions don't occur.
$fn = md5(microtime(true) . $extension . $file_name);
$file->move($path, $fn);

Related

Digital Ocean 403 Forbidden when i'm upload from laravel local

I have a problem when I want to upload a file to digital ocean, there is a 403 error, even though I'm sure the key, secret and endpoint are correct
this is my simple code
$tes= Storage::disk('digitalocean')->putFileAs('url', request()->file('url'), time().'.'.$extension);
dd($tes);
if ($request->hasFile('url')) {
$file = $request->file('url');
$ext1 = $file->getClientOriginalExtension();
// $st_random = str_random(10);
//dd($file);
$st_random = Str::random(10);
$filename = $file->getClientOriginalName();
$filename = explode(".", $filename);
$ext = $ext1;
$filename = $filename[0] . $st_random . "." . $ext;
Storage::disk('digitalocean')->put('/' . $filename, File::get($file));
$csv = 'digitalocean/' . $filename;
}
note
use Storage;
use Str;
use File;
you have to try this file uploading . it may solve your problem .

Laravel: The file was not uploaded due to an unknown error

I am trying to upload a file to two different locations. The lcoations being /2x/ adn /3x/. It uploads the file on 3x but doesn't on 2x and throws this error:
The file was not uploaded due to an unknown error
Here is what i am doing:
$photo = $request->file('photo');
if (isset($photo)) {
if ($photo != null || $photo != '') {
$imageSize = getimagesize($photo);
$resolution = $imageSize[0] . 'x' . $imageSize[1];
if ($resolution == '300x300' || $resolution == '450x450') {
if (!file_exists(base_path('uploads/custom_avatar'))) {
mkdir(base_path('uploads/custom_avatar'), 0777, true);
}
$resolution = "3x";
$uploadPath = base_path('uploads/custom_avatar/' . $resolution . '/');
$otherImageResolution = '2x';
$otherImagePath = base_path('uploads/custom_avatar/' . $otherImageResolution . '/');
//echo $otherImagePath;exit;
// saving image
$fileName = $child->id . '_' . time() . '.png';
$photo->move($uploadPath, $fileName);
$photo->move($otherImagePath, $fileName);
// creating records
$childImage = Images::addPhoto($child->id, $fileName, $resolution);
$otherImage = Images::addPhoto($child->id, $fileName, $otherImageResolution);
if ($childImage && $otherImage) {
$result = Child::createChildResponseData($child);
\Log::info('Child avatar added Successfully' . json_encode($childImage));
return response()->json([
'status' => $this->SUCCESS,
'response' => $result,
], $this->SUCCESS);
}
Any help?
Check your code if your file upload code is running two times.
I was facing the same issue & then I find that my file upload code is running two times.
after commenting one of them it's working fine.
You can try this:
$request->file('photo')->move($destination_path, $file_name);
Add DIRECTORY_SEPARATOR between path and filename if needed and
copy that file at new location
copy($destination_path.$file_name, $new_path.$new_file_name);
Check your code if your file upload code is running two times.
You can check this part of the code. Make sure you type it correctly and not repeat it twice.
// Original size upload file
$section_image_file->move($folder, $section_image_name);

Rename a file if already exists - php upload system

I this PHP code:
<?php
// Check for errors
if($_FILES['file_upload']['error'] > 0){
die('An error ocurred when uploading.');
}
if(!getimagesize($_FILES['file_upload']['tmp_name'])){
die('Please ensure you are uploading an image.');
}
// Check filesize
if($_FILES['file_upload']['size'] > 500000){
die('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if(file_exists('upload/' . $_FILES['file_upload']['name'])){
die('File with that name already exists.');
}
// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'upload/' . $_FILES['file_upload']['name'])){
die('Error uploading file - check destination is writeable.');
}
die('File uploaded successfully.');
?>
and I need to act like a "windows" kind of treatment for existing files - I mean the if the file exists, i want it to be changed to the name of the file with the number 1 after it.
for example: myfile.jpg is already exists, so if you'll upload it again it will be myfile1.jpg, and if myfile1.jpg exists, it will be myfile11.jpg and so on...
how can i do it? i tried some loops but unfortunately without success.
You could do something like this:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
// add a suffix of '1' to the file name until it no longer conflicts
while(file_exists($name . '.' . $extension)) {
$name .= '1';
}
$basename = $name . '.' . $extension;
To avoid very long names, it would probably be neater to append a number, e.g. file1.jpg, file2.jpg etc:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$increment = ''; //start with no suffix
while(file_exists($name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
You uploaded a file called demo.png.
You tried to upload the same file demo.png and it got renamed to demo2.png.
When you try to upload demo.png for 3rd time, it gets renamed to demo1.png once again and replaces the file you upload in (2).
so you won't find demo3.png
For user6930268;
i think your code should be:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$dirname = pathinfo($_FILES['file_upload']['name'], PATHINFO_DIRNAME);
$dirname = $dirname. "/";
$increment = ''; //start with no suffix
while(file_exists($dirname . $name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
$resultFilePath = $dirname . $name . $increment . '.' . $extension);
Here is a my function i'm using. It will generate file (1).txt , file (2).txt , file ...
function getFilePathUnique($path) {
while ($this->location->fileExists($path)) {
$info = pathInfo($path);
//extract the current number of file
preg_match("/\([0-9]+\)$/",$info["filename"], $number);
$number = str_replace(["(" , ")"] , ["" , ""] , $number[0]);
//remove the old number
$info["filename"] = trim(preg_replace( "/\([0-9]+\)$/" , "" , $info["filename"] ));
//append new number
$info["filename"] .= " (" . (++$number) . ")";
//build path
$path = ($info["dirname"] != "." ? $info["dirname"]: "" ).
$info["filename"] . "." . $info["extension"];
}
return $path;
}

PHP renaming of input file issues

I'm trying to rename the input file to be a .jpg after conversion, but for some reason I'm getting a file.png.jpg when I'm really looking for file.jpg
Here is my code:
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
Use pathinfo():
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$path_parts = pathinfo( $_FILES['t1']['name'] );
$destination = $path . $_POST['username']. "-" . $path_parts['filename'] . ".jpg";
Let's say that the variable $filename contains your image name with the png extension.
In order to change the extension to jpg , simply run it through this function :
function replace_extension($filename) {
return preg_replace('/\..+$/', '.' . '.jpg', $filename);
}
The basename() function includes the original files extension
Use the pathinfo() function to return an array of informatino about the file and use the filename with out the extension
Replace
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
with
$info = pathinfo($_FILES['t1']['name']);
$destination = $path . $_POST['username']. "-" . $info['filename'] . ".jpg";
You can either use the second parameter to basename to kill the suffix
$filename = basename($_FILES['t1']['name'], ".png");
or you could do some string manipulation
$filename = substr($_FILES['t1']['name],0, strrpos($_FILES['t1']['name'], ".") -1);
basename returns you the whole filename, including the file type suffix (i.e. ".jpg"). If you want to strip the suffix, you can call the function with a second parameter: basename($_FILES['t1']['name'], 'png').
But if you want to convert a png to a jpg, you can't just change the filename, you have to convert the file using special functions, see "Use PHP to convert PNG to JPG with compression?".

Having trouble with explode() in uploadify.php

I have this snippet from my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
// this portion here will be true if and only if the file name of the uploaded file does not contain '.', except of course the dot(.) before the file extension
$count = 1;
list( $filename, $ext) = explode( '.', $name, );
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$count . ')' . '.' . $ext;
}
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Basically this is quite working. Uploading the file and getting the path of the file which will then be inserted on the database and so on. But, I tried uploading a file which file name looks like this,
filename.1.5.3.pdf
and when succesfully uploaded, the file name then became filename alone, without having the file extension and not to mention the file name is not complete. From what I understood, the problem lies on my explode(). It exploded the string having the delimiter '.' and then assigns it to the variables. What will I do to make the explode() cut the string into two where the first half is the filename and the second is the file extension? PLease help.
Don't use explode, use a function designed for the job: pathinfo()
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);

Categories