I created a page that can upload file to my database, but when a filename has (.), it doesnt save properly. For example I upload a file named imagefile.50.jpg, it just saves as image20.50
<?php
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = $extension[0] . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
To get the filename and extension of a file, you can use pathinfo, i.e.:
$file = "some_dir/somefile.test.php"; # $_FILES['user_image']['name']
$path_parts = pathinfo($file);
$fn = $path_parts['filename'];
$ext = $path_parts['extension'];
print $fn."\n";
print $ext;
Output:
somefile.test
php
Related
I'm using this code to upload files or images. It's working but can't upload a large file and I want to upload a file when selecting it from the local computer like the below image.
I use below PHP code in the controller.
$image = $request->file('file_upload');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
echo $new_name;
$image->move(public_path('images'), $new_name);
Try to use this code.
Change the $request->sharing_file with your field name.
You can increase the $size for image what you want, currently it is 16mb and working fine.
$myimage = $request->image;
$size = getClientSize();
if($sizes < 16777216){
$fileMimeType = explode('/', $myimage->getClientMimeType());
$fileType = $fileMimeType[0];
$originalFileName = substr($myimage->getClientOriginalName(), 0, strpos($myimage->getClientOriginalName(), "."));
$originalFileName = substr(str_replace(' ', '-', $originalFileName),0,10);
$rand = rand(9,1000);
$fileName = $rand.'-'.$originalFileName.'.'.$myimage->getClientOriginalExtension();
$upload = $values->move(public_path('images'), $fileName);
if($upload) {
$message = 'File Uploaded';
} else {
$message = "Failed to upload file";
}
}
else {
$message = 'Files size should be less than 16 MB.';
}
Try
if ($request->hasFile('file_upload')) {
$destinationPath = public_path().'/images/';
$file = $request->file_upload;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['your_databse_table_field_name'] = $fileName;
}
How can I change name of uploaded file in Laravel 4.
So far I have been doing it like this:
$file = Input::file('file');
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();
But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like (2) added at the end of the second file name or to change the file name completely
The first step is to check if the file exists. If it doesn't, extract the filename and extension with pathinfo() and then rename it with the following code:
$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
$filecounter = 1;
while (file_exists($destinationPath)) {
$img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
$destinationPath = $destinationPath . $img_duplicate;
}
The loop will continue renaming files as file_1, file_2 etc. as long as the condition file_exists($destinationPath) returns true.
I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:
(... in the controller: ... )
$path = public_path().'\\uploads\\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);
this function get an "unused" filename:
public function getNewFileName($filename, $extension, $path){
$i = 1;
$new_filename = $filename.'.'.$extension;
while( File::exists($path.$new_filename) )
$new_filename = $filename.' ('.$i++.').'.$extension;
return $new_filename;
}
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);
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
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";
}
}
?>