php is_file not detecting image with period in name - php

I have a function which checks if image files exist. It works for all images, except when a period is inside the filename. The filenames are user uploaded, and many already exist that are not sanitized. Here is an example:
$img = 'nice_name.jpg'; // detects
$img = 'bad_name.7.jpg'; // doesn't detect
if (is_file($path . $img)) {
return $path . $prefix . $img;
}
I'm not sure how to escape this or make it work. I have doubled checked and the file does exist at that path. The function works for other image names in the same folder.
edit: This was marked a duplicate and linked to a question about uploading files. I am using is_file() to check if a file already exists. There is no uploading occurring, and the file already has the extra "." in its name on the server, so this is a different issue.

You can use basename() to get the file name, and then do something with it, like rename it if it contains a period.
$testfile = "test.7.img";
$extension = ".img";
$filename = basename($testfile, $extension);
if(strpos($filename,".") > 0) {
$newname = str_replace(".","",$filename) . $extension ;
rename($testfile,$newname);
}
//... then continue on with your code

Related

PHP move_uploaded_file doesn't work occasionally?

I now there are lots of same questions here, but I didn't find my answer.
I want to upload an image using move_uploaded_file() function in PHP. Here is my logic?
//check if file uploaded
if (!isset($_POST) || !isset($_FILES)) {
return back();
}
// allowed extensions
$extensions = ['jpg', 'jpeg', 'gif', 'png'];
$fileName = pathinfo($_FILES['profile-image']['name'], PATHINFO_FILENAME);
// save file extension into a variable for later use
$parts = explode('.',$_FILES['profile-image']['name']);
$extension = strtolower(end($parts));
$fileSize = $_FILES['profile-image']['size'];
// check the extension
if (!in_array($extension, $extensions)) {
return back()->withErrors(['File Extension is not valid']);
}
// check if file size is less than 2MB
if ($fileSize >= 2e+6) {
return back()->withErrors(['File Size is too large.']);
}
//check if there is other errors
if ($_FILES['profile-image']['error']) {
return back()->withErrors(['You have anonymus error']);
}
// generate a unique file name
$profile_image = Hash::make($fileName) . '-' . time() . '.' . $extension;
// make a directory if there isn't one
if (!is_dir('public/img')) {
mkdir('public/img');
}
// if current user has an image then delete it
$user = App::get('database')->find('users', compact('id'));
if ($user->profile_image) {
unlink('public/img/' . $user->profile_image);
}
// move image into directory and final check for errors
if( ! move_uploaded_file($_FILES['profile-image']['tmp_name'], 'public/img/' . $profile_image) ) {
return back()->withErrors(['Your file doesn\'t uploaded']);
}
// Insert Uploaded Image into DB.
App::get('database')->update('users', compact('id'), compact('profile_image'));
return redirect('dashboard')->withMessage('Thank for uploading the file.');
I try this code, everything works properly but just sometimes. I don't know why sometimes my uploaded file doesn't move to the directory and sometimes it does. I tried for the same image, sometimes it uploaded and sometimes it failed. This is interesting, because when I upload an image and it fails, can't catch any errors at all.
Did you check max_file_uploads and post_max_size in your php.ini file ?
Maybe the file is bigger than the maximum size allowed.
Regards.
OK, I find the problem. When I hash the image name and save it to DB, sometimes it includes / inside file name, then when I use the file name in image src attribute, it considers the part before the / as another directory.
It might have trouble with,
Your Destination Directory have some writing permission issue.
Try this for manage file permission,
if (!is_writable($url)) {
try {
chmod($url, 0644);
} catch (Exception $e) {
die($e->getMessage() . ' | File : ' . $url . ' | Needs write permission [0644] to process !');
}
}
All the Best !

How do I get a File Extension in PHP if I only have the File Name?

I have the path to an image file /files/uploads/1 but as you can see, I don't have an extension so I can't display the image. How can I get the extension of the file so I can display it? Thanks!
EDIT: Here is come code I have tried. BMP, PNG, JPG, JPEG and GIF are the only possible extensions, but $path ends up never getting assigned a value.
$exts = array('bmp','png','jpg','jpeg','gif');
foreach ($exts as $ext) {
if (file_exists("/files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
Personally, I had a problem where I had an unnecessary slash (/) before my path in the file_exists check, but the solution to the question is still the same.
$exts = array('bmp','png','jpg','jpeg','gif','swf','psd','tiff','jpc','jp2','jpx','jb2','swc','iff','wbmp','xbm','ico');
foreach ($exts as $ext) {
if (file_exists("files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
You don't need a file extension to show an image.
<img src="/files/uploads/1">
Will show the image. It's the same way the placehold.it images work
<img src="http://placehold.it/350x150">
First of all , I think when you get the file name for the image that means no need to add extension , so you have the file name and image folder
it should simply look like this :
$fullpath = ('uploadword/'.$filename);
// then call it
<img src='".$fullpath."'>
The normal scenario to upload all the images in specific folder then get the filename and save it in data base
move_uploaded_file($file_tmp,"upload/".$filename);
Some professional make it more sophisticated to make filename unique ,because they expected some duplicated values and many reasons , here is one simple technique :
$anynameorfunction = "";// random number etc...
$newname = $anynameorfunction.$filename;
move_uploaded_file($file_tmp,"upload/".$newname);
So, when they call it again it should be simple like this
$fullpath = ('uploadword/'.$newname);
// then call it
<img src='".$newname."'>
This is in very simple way and i wish you get what i mean

How do i change my file name after i have removed all '?

SORRY CAUGHT MY OWN ERROR AFTER POST
I have this code that i am running after a HTML from uploads a file to my .uploadAdmin.php section. Im having a lot of trouble with this.
$clientname = $_SESSION['MM_USERNAME'];
$extension = end(explode(".", $_FILES["file"]["name"]));
$myText = (string)$_FILES["file"]["name"];
$myText = str_replace("'", "", $myText);
print $myText; // This does come out with no '
My question is how do i change to file name after i have a new file name with no ' I have tried a few things including
$_FILES["file"]["name"] = $myText;
I had a comparison operator == instead of =,
Thanks Amy :)
Once you've uploaded your file you need to move it from the temporary directory to the place you want to store it. This is a security feature. The uploaded file will have a temporary file name. You can change the real filename as part of the move_uploaded_file() operation.
// where to store file
$uploads_dir = '/uploads';
// name of temporary file after upload.
$tmp_name = $_FILES["file"]["tmp_name"];
// original name of file, with apostrophes replaced
$name = str_replace("'", "", $_FILES["file"]["name"]);
// move the file
if (move_uploaded_file($tmp_name, "$uploads_dir/$name") === false) {
// do something if the file isn't an uploaded file.
}
Read the PHP reference Handling File Uploads for the complete reference.

uploadifive - change filename on upload

I am using uploadifive to upload images - however I want to change the name of the images to "newimage" I am not sure where or how to do this with what is provided - this is the last modification I need to deploy.
You're going to need to do the name change in the PHP script that handles the uploading (I'm assuming your using PHP since that's uplidfy's standard). It can be a bit tricky because you have to separate the incoming file name from it's extension. This should be enough to get you started.
$theFile = $_FILES['file_upl']['name'];
$tempFile = $_FILES['file_upl']['tmp_name'];
$newName = "newname";
$saveDir = $_SERVER['DOCUMENT_ROOT']."/images/";
//Function returns the extension from the '.' on
function get_ext($from_file) {
$ext = strtolower(strrchr($from_file,'.'));
return $ext;
}
//This will rename the file to $newname + the extension
$theFile = $newname.get_ext($theFile);
//Save the file
move_uploaded_file($tempFile,$saveDir.$theFile);
$file = 'uploaded_img.jpg';
$remote_file = 'Saved.txt';
ftp_put($conn_id, $remote_file, $file, FTP_ASCII)
just change the name of the remote file

Problem to upload audio file in php

Here is my code:
if ($_FILES['music']['name'] != '')
{
$file_name = time() . $_FILES['music']['name'];
copy($_FILES['music']['tmp_name'], "music/" . $file_name);
}
else
{
$file_name = "";
}
I want to upload audio file. the file name is insert into database. but its not insert into folder.
try move_uploaded_file instead. You may want to check file size limits too.
I think you want to use move_uploaded_file(), not copy
I guess the folder in which you are trying to copy the uploaded file is not the one you expect. Possibly this is what you need:
copy($_FILES['music']['tmp_name'], __DIR__ . "/music/" . $file_name);
By the way move_uploaded_file() works faster and safer than copy().

Categories