Hello I am using the following code to upload files on my server and to write the filename inside the database. My question is how I can achive when the file is uploaded the name of the file to be changed ? Right now I am facing a problem if the filename have space sbetween the words if it is not a whole word the file is not uploading correctly.
here is the code:
$target = "../images/";
$target = $target . basename( $_FILES['photo']['name']);
$filename = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
//resize function
createThumbnail($filename);
You need to parse the filename removing all unwanted characters. The easiast way is to use preg_replace forbidden characters. Here's an example:
// List of forbidden chars (\ and / need to be escaped with \)
$forbiddenChars = "\/\\?%*:|\"<>. ";
//Characters not allowed are replaced by this var
$replaceStr = "_";
$filename = preg_replace("/[$forbiddenChars]/", $replaceStr, $_FILES['photo']['name']);
//DEBUG: Test if everything is ok (should be deleted in production)
var_dump($filename);
Related
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
I'm having a strange issue with a component I'm working on. The component has a form that includes a file upload. The code checks for duplicate filenames and appends a counter to the end. All of this works perfectly except with I try and modify the record and change the associated file.
I used component creator to build the skeleton at that code works for updates -
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = '/var/www/plm_anz/' . $filename;
$fileTemp = $file['tmp_name'];
if(!JFile::exists($uploadPath)){
if (!JFile::upload($fileTemp, $uploadPath)){
JError::raiseWarning(500, 'Error moving file');
return false;
}
}
$array['ping_location'] = $filename;
When I update the code to remove the MD5 sum and append the counter it all falls apart..
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
$originalFile = $finalFile = $file['name'];
$fileCounter = 1;
//Rename duplicate files
$fileprefix = pathinfo($originalFile, PATHINFO_FILENAME);
$extension = pathinfo($originalFile, PATHINFO_EXTENSION);
while (file_exists( '/var/www/plm_anz/'.$finalFile )){
$finalFile = $fileprefix . '_' . $fileCounter++ . '.' . $extension;
}
$uploadPath = '/var/www/plm_anz/' . $finalFile;
$fileTemp = $file['tmp_name'];
if (!JFile::upload($fileTemp, $uploadPath)){
$fileMessage = "Error moving file - temp file:". $fileTemp . " Upload path ". $uploadPath;
JError::raiseWarning(500, $fileMessage);
return false;
}
I've narrowed down the cause to the filename that the while loop creates but cannot figure out why it only breaks the form update and not the new form submission.
The error I get in Joomla (3.4) is:
Error
Error moving file - temp file:/tmp/phpgwag5r Upload path
/var/www/plm_anz/com_hotcase_6.zip
Save failed with the following error:
I know it's something simple but I've been staring at it too long to see it!
Thanks!
Ok as it is I can not see any good reason why is failing.
The only thing I can suggest you is that JFile::upload is failing go to debug in /libraries/joomla/filesystem/file.php#449 and step by step try to understand what's wrong.
That's actually the file and line of JFile::upload.
In there probably the only line that matter to you is line 502 which is :
if (is_writeable($baseDir) && move_uploaded_file($src, $dest))
Especially try to see what's going on the variable $ret.
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.
I am using the code bellow to upload a file using php and inserting file name into database. Actually I want to rename of file on uploading and want to insert new renamed name into database. I know how to insert name into database but I don't know how to rename uploaded file name. Please help.
I am using code bellow:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']);
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
$add_file = $_FILES['uploaded']['name'];
Thank you so much..
Is this what you are looking for?
<?php
rename("/tmp/uploaded_file.txt", "/home/user/login/uploaded/67A7466B576.txt");
?>
So new code will be:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']);
rename($_FILES['uploaded']['tmp_name'], $target);
$add_file_to_db = $target;
This might be helpful for you:
$uploaded_file = time()."__".$_FILES['uploaded']['name'];
This simply adds time before the name of the file.
Example:
If I uploaded the AnalysisReport.doc file, then it simply becomes like 1354173106__AnalysisReport.doc
Hi I have a file upload field with name="file1" and code in a phpmailer script:
if (isset($_FILES['file1']))
{
$file1_path = $_FILES['file1']['tmp_name'];
$file1_name = $_FILES['file1']['name'];
$file1_type = $_FILES['file1']['type'];
$file1_error = $_FILES['file1']['error'];
$mail->AddAttachment($file1_path);
}
And for some reason, it attached like php45we34 (each time diff, seems that its the temp name path, not the actual file)
Any help?
Strip spaces from your filename!
Blue hills.jpg should be Blue_hills.jpg
do
$fileName = str_replace(' ', '_', $fileName);
I suggest you to use function move_uploaded_file before adding attachment.
This is sample code that will move file from temporary location somewhere at your server
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
After that AddAttachment should work fine.
$mail->AddAttachment(basename($target_path . $_FILES['uploadedfile']['name']));
What you see is what should happen. You do not specify the attachment name, so phpMailer uses the name of the temporary file it's attaching.
If you want the file to have a different name, you have to specify it. The accepted answer works because it goes the other way round -- it changes the file name so that the file has the desired name.
The usual way to proceed would be to issue
$mail->AddAttachment($file1_path, $_FILES['file1']['name']);
to override the attachment name.