phpMailer sending attachment name, not attachment - php

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.

Related

Rename File before Storing in Server PHP

I need to know code how to rename file before it gets uploaded to my server in php script.Ill post the php code of mine.
I need it because I am uploading an image from phone and I don't want it to be overwritten.
Can I achieve that?
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
For renaming file in Android, you can do :
String file_path = <file path off your existing file you want to rename>
File from = new File(file_path,"from.txt");
File to = new File(file_path,"to.txt");
from.renameTo(to);
This code will work for both file stored in internal or external storage. Just for writing to external storage remember you need to have android.permission.WRITE_EXTERNAL_STORAGE to be added to your Android manifest.
write your code like below.
$filename = $_FILES['upload_file']['name'];
$newname = 'alteredtext'.$filename; // you can also generate random number and concat on start.
$tmp_path = $_FILES['upload_file']['tmp_name'];
if(move_uploaded_file($mp_path, $newname)) {
echo "success";
} else{
echo "fail";
}
You don't need to use the name passed in the $_FILES array when moving the file. You can create any name you want (assuming the path is valid) and pass it as the second argument of move_uploaded_file. If you want a semi-random name, you could generate a random number and then hash it or something to create the filename.
If you want to check first, if the file exists, then rename it to have a numeric suffix, you could do this:
<?php
$base_path = "uploads/";
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']);
if(file_exists($file_path)) {
$ctr = 0;
do { // increment an index to append to the filepath
$ctr++;
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']) . "_$ctr";
} while(file_exists($file_path));
}
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
The above snippet will keep incrementing until it finds a filename that doesn't exist. Of course, you'd want to add some bounds and error checking, while the above snippet demonstrates the concept, it isn't entirely production ready.

Changing name of uploaded file in php

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

PHP upload to specific folder

I am trying to do a php upload that will upload into a specific folder.
One would choose the file they wish to upload next to a dropdown box which is a folder list. This is because it organises files.
<?php
session_start();
if(!isset($_SESSION["USER"]["Admin"])){
header("Location: index.html?unath");
}
$folder = mysql_real_escape_string($_POST['loc']);
$target_path = "../../shared/docs/$folder";
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload2)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Currently the code uploads the file into the "docs" folder and not docs/folder. Instead it puts the folder name in front of the file. For example- if the folder is called "abc" and my file is called robs.docx it will upload it to the main Docs folder and call it abcrobs.docx
You have a missing slash
Replace this line:
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
with:
$upload2 = $target_path ."/". basename( $_FILES['uploadedfile']['name']);
OR:
Replace this line:
$target_path = "../../shared/docs/$folder";
with:
$target_path = "../../shared/docs/".$folder."/";
You do not need mysql_real_escape_string because there's no SQL involved here.
If no database connection is established, mysql_real_escape_string returns null. So you're probably throwing away the $_POST['loc'] value.
You should never ever use user supplied values for manipulating anything on the filesystem without really, really thorough inspection of what you're going to manipulate. See Security threats with uploads.
Use var_dump liberally to see what your values look like at various stages and do some debugging.
You are missing a slash after $target_path
Add a / on the end of your $target_path:
$target_path = "../../shared/docs/$folder/";
You should properly escape your variables:
$target_path = "../../shared/docs/". $folder ."/";

PHP file upload and passing diectory

Hi am sorry but I have difficulties solving the problem. What i want to do is to upload file and then pass the directory but its nbot working the way I expect. The upload goes to a server to a file called 'uploads' but I cannot pass the directory , cuz its what I need, in later decode function:
Here's the code for uploading file am using:
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$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!";
}
?>
and then I want to pass directory to here just after $json = $api->decode ( ):it shld be between the brackets I put ($target_path . basename( $_FILES['uploadedfile']['name'])) but its not working and I dont know how to solve it. The case decode is supposed to get directory of the file which was just uploaded and then decode what is inside:
case "decode":
$json = $api->decode ($target_path . basename( $_FILES['uploadedfile'] ['name']));
$start='{"content":"';
$pos_start = strpos($json, $start);
$end='"}';
$pos_end = strpos($json, $end);
thanx for any advice, please help me out if you know how, thanx
The way you build your JSON looks flawed. Typically it's best to accumulate the data first, and do a json_encode as the very last step. This way your JSON is never accidentally mangled. It may still not be semantically valid but at least you can see why ;)
$data = array(
"content" => $target_path . basename( $_FILES['uploadedfile']['name'])
);
return json_encode($data);
I hope this helps:
$json = $api->decode ($target_path . basename( $_FILES['uploadedfile'] ['name']));
$o=json_decode($json);
echo $o->content;
if that doesn't work try:
$json = $api->decode ($target_path);
$o=json_decode($json);
echo $o->content;
Since you are using $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); above.

Upload file to mySQL Database. Help with code

Okay so I am running into issues inserting a file into my database as a blob. I am able to upload the file to a folder on my database but I now want to insert the file into my database as a blob. I know this isnt generally ok to do but I WANT TO DO IT. Anyways I was wondering if anyone had any PHP code to insert a file into a blob table? I've tried using this to no avail maybe I am just not writing the SQL statement right?
<?php
$target = "./";
$target = $target . basename( $_FILES['uploadedfile']['name']);
$file=($_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!";
}
mysql_connect("localhost","root","");
mysql_select_db("ivrsupport");
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$file') where PHONE_NUMBER = ('15555215554')");
$r=mysql_query($sql);
if(!$r){
echo "Error in query: ".mysql_error();
}
mysql_close();
?>
I would avoid storing files in the database. That's what FileSystems are for and are much better at doing so. There are millions of posts out there in the blogosphere explaining why not to. Even for a small application I wouldn't do it. It just feels dirty. A blob in the database holds no metadata about the file itself where as a FS can be queried in many ways to gleem information like file size, modification times, permissions etc... My $0.02
You need to read the file into a variable and then insert it.. giving it the filename only wont do.
$fp = fopen($basename, 'r');
$content = fread($fp, filesize($basename));
fclose($fp);
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$content') where PHONE_NUMBER = ('15555215554')");
$file simply contains the name of the file not it's contents.
Try the following:
<?php
$target = "./";
$target = $target . basename( $_FILES['uploadedfile']['name']);
$file=($_FILES['uploadedfile']['name']);
$fileContents = file_get_contents($file);
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!";
}
mysql_connect("localhost","root","");
mysql_select_db("ivrsupport");
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$fileContents') where PHONE_NUMBER = ('15555215554')");
$r=mysql_query($sql);
if(!$r){
echo "Error in query: ".mysql_error();
}
mysql_close();

Categories