PHP renaming of input file issues - php

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?".

Related

How to copy image from DB to new path

I'm trying to copy an image using the path which is stored in my DB. I tried this but it throws "Array To String Conversion" error. I've never dealt with this before. Here's my code.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));
You're attempting to convert an array from explode('.', $img_name); to a string in the final line.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name); // This is an array like ['image_name', 'ext]
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext[count($ext)-1])
); // You'll need to address the last item in the array by its index like this
That said, pathinfo(...) is the safer option here.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext
);
I think its a simple problem of using explode as it will return an array of strings based on the dividing parameter.
I'm not too savvy with OOP but I can suggest using str_replace or trim to remove the '.'s in the $img_name variable.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = str_replace('.',"",$img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));

Adding random number to uploaded file in 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);

PHP - move_uploaded_file not working to copy file in same folder

Having some trouble with rewriting a photo file. I need the file name to get rewritten as a random string. The file uploads fine - I can't seem to get it copy the file and rewrite the file name to the random string. The file is going to stay in the directory.
The function is working fine and I can rewrite file name in the database, but it will not rewrite the actual file in the folder. The folder permissions are rwxr-xr-x (755).
Any thoughts?
function AfterUpdate(){
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . $newFilename;
if (move_uploaded_file($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}
}
$newFilename contains a path location I guess by looking at the $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];.
$newFilename should just be the new file name with extension.
move_uploaded_file will only move files from one folder to another or the same, that already exists. But will not create a folder for you.
Simple fix. Replace move_uploaded_file with rename. The file will not be moved, just renamed.
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $newFilename;
if (rename($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}

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);

Remove image extension, rename and restore

Say the image is called:gecko.jpg
Can I first remove ".jpg" and add "-100x100" after "gecko", and then put the extension back, so it would be "gecko-100x100.jpg"?
use pathinfo
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
$new = $path_parts['filename'] . '-100x100.' .$path_parts['extension'];
Yes, quite simply with PHP's string functions in conjunction with basename()
$base = basename($filename, ".jpg");
echo $base . "-100x100" . ".jpg";
Or to do it with any filetype using strrpos() to locate the extension by finding the last .
// Use strrpos() & substr() to get the file extension
$ext = substr($filename, strrpos($filename, "."));
// Then stitch it together with the new string and file's basename
$newfilename = basename($filename, $ext) . "-100x100" . $ext;
--
// Some examples in action...
$filename = "somefile.jpg";
$ext = substr($filename, strrpos($filename, "."));
$newfilename = basename($filename, $ext) . "-100x100" . $ext;
echo $newfilename;
// outputs somefile-100x100.jpg
// Same thing with a .gif
$filename = "somefile.gif";
// outputs somefile-100x100.gif

Categories