PHP generating a .php.vcf file instead of .vcf file - php

I have a feature in my PHP website where a user can download a vcard file for an employee, however the file being generated is .php.vcf and isn't supported on mobile.How can i change the file format to .vcf, The simplified PHP code for the vcf generation is below.
function generate_vcard($fn,$ln){
$text = 'BEGIN:VCARD' . "\r\n";
$text .= 'VERSION:3' . "\r\n";
$text .= 'Firstname:'.$fn . "\r\n";
$text .= 'Firstname:'.$fn . "\r\n";
$text .= "END:VCARD"."\r\n";
return $text;
}
$generated_text = generate_vcard('John', 'Smith');
header('Content-Type: text/vcard');
echo $generated_text;
The vcard is downloading, the problem is with the extension as mentioned above that is '.php.vcf' is being generated instead of '.vcf'.

You may try to add content disposition and put filename there:
header('Content-Disposition: attachment; filename="filename.vcf"');
Look at header() documentation, specifically in the "Example #1"

Related

Php Vcard shows empty on outlook

I am trying to create a vcard link download that creates the vcard on-the-fly.
if(isset($_POST)){
header("Content-type: text/vcard");
header("Content-Disposition: attachment; filename=" . get_the_title() . ".vcf");
$content = "\rBEGIN:VCARD\r";
$content .= "VERSION:2.1\r";
$content .= "N:Vicon;Barry;S.\r";
$content .= "FN:Barry S. Vicon\r";
$content .= "ORG:sample\r";
$content .= "TITLE:Partner\r";
$content .= "NOTE;ENCODING=QUOTED-PRINTABLE: =0D=0A\r";
$content .= "TEL;WORK;VOICE:(516) 999-9999\r";
$content .= "TEL;WORK;FAX:(516) 999-9999\r";
$content .= "URL;WORK:http://www.sample.com\r";
$content .= "EMAIL;PREF;INTERNET:bcohen#sample.com\r";
$content .= "REV:TZ\r";
$content .= "END:VCARD";
echo $content;
}
the file downloads fine and the file format is correct as well but when opened in outlook, not a single info is imported.
here is the output file of the_title.vcf
BEGIN:VCARD
VERSION:2.1
N:Vicon;Barry;S.
FN:Barry S. Vicon
ORG:sample
TITLE:Partner
NOTE;ENCODING=QUOTED-PRINTABLE: =0D=0A
TEL;WORK;VOICE:(516) 999-9999
TEL;WORK;FAX:(516) 999-9999
URL;WORK:http://www.sample.com
EMAIL;PREF;INTERNET:bcohen#sample.com
REV:TZ
END:VCARD
another pre-existing vcard has the exact same info and everything seems to be working when outlook opens that file.
what am I missing here?
$content = "BEGIN:VCARD\n\r";
Solves the issue. thanks to Marc's comment

Trying to add a line break in output file from a string

I have PHP saving an output file all from one very long string. I want this code that is being outputted to be formatted properly, so I am trying to add linebreaks in at certain points.. I have been trying to use "\n", but for some reason that is not doing the trick.. Here's the relevant code:
foreach($headerColumn as $hColumn) {
$outputString .= '<td>' . $hColumn . '</td>' . "\n";
};
Here I have the "\n" added to the end of the string, but for some reason it is being outputted like this:
<thead>
<tr><td>Name</td><td>Ticker</td><td>Buy Date</td><td>Current Yield</td>
</tr>
</thead>
When, in actuallity, I want each on its' own line.. any ideas? in case it has something to do with the content type of the file, here is my file write call:
header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($outputString));
header('Connection: close');
echo $outputString;
Thanks!
I think what you want to use is PHP_EOL:
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2
So, for your example:
$outputString .= '<td>' . $hColumn . '</td>' . PHP_EOL;
I don't know if this is the best practice... but you can actually put a newline into the code by simply not ending the string quotation until the next line:
foreach($headerColumn as $hColumn) {
$outputString .= '<td>' . $hColumn . '</td>' . "
";
};

How to display a download link instead of displaying the file itself in php along with another form

I have a form to display which have file attachments at the time of form filling, I succeeded in attaching the file, but at the time of displaying the form it also showing the attached file in some binary/etc form, instead I want it to show just a file name and whenever we click on the file name it has to download the file... Please do help for this
My Code is:
<?php
...
$id = htmlentities($_GET['id'], ENT_QUOTES);
// Get the details of the risk
$risk = get_risk_by_id($id);
$status = htmlentities($risk[0]['status'], ENT_QUOTES);
$subject = $risk[0]['subject'];
//file retrival fields
$filename = $risk[0]['name'];
$mimetype = $risk[0]['type'];
$filedata = $risk[0]['content'];
...
?>
<html>
...
<?php
...
echo "<label>Risk Assessment</label>\n";
echo "<textarea name=\"assessment\" cols=\"50\" rows=\"3\" id=\"assessment\" disabled=\"disabled\">" . htmlentities(stripslashes($assessment), ENT_QUOTES). </textarea>\n";
echo "<label>Additional Notes</label>\n";
echo "<textarea name=\"notes\" cols=\"50\" rows=\"3\" id=\"notes\" disabled=\"disabled\">" . htmlentities(stripslashes($notes), ENT_QUOTES) . "</textarea>\n";
echo "<label>Files attached:\n</label>";
echo $filedata;
...
?>
...
</html>
and the o/p is displaying the file content... :(
you are echoing the $filedata content. you should echoing the $filedata location, not its content.
Here's an example of how to download a pdf file instead of displaying it:
You're Page:
<a href="dl.php?filnam=xyz.pdf>Download the file</a>
dl.php
<?php
$filnam = str_replace(" ", "%20", basename($_GET['filnam']));
header ("content-type: application/pdf");
header ("Content-Disposition: attachment; filename*=UTF-8'en'$filnam");
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($_GET['filnam']));
readfile($_GET['filnam']);
?>
So there are a few steps
Get the name of the file
Get the local path of the file
Respond with a link.
It's been a while since I used PHP but I believe you can get the name of the file with
//basename takes /a/b/c/d.jpg and returns d.jpg
$filename = basename($risk[0]['name']);
$localpath = $risk[0]['tmp_name'];
and then for your output do
echo " . $filename . "" . PHP_EOL
That will create a link with the label of the filename and the url of the local path on the server.
Update: Apparently the file doesn't actually exist yet. If this is the case, then you should write the contents of the file stored in your db. To do this, do
$handle = fopen($filename, "wb");
You can use whatever filename you want. You should add something like the timestamp or user ID or something to make the file unique so it's not overwritten by multiple requests. This will create the file. You can then fill in the file by doing
fwrite($handle, $risk[0]['content']);
finally close the file with
fclose($handle);
to output this new link you can just use the same filename if you like
echo " . $filename . "" . PHP_EOL
If you specified the filename by including some unique value then you can get the original name by using
echo " . $risk[0]['name'] . "" . PHP_EOL
Hope that helped!

Warnings preventing file_get_content from reading properly

In appending an attachment I am receiving a warning message preventing me attaching an existing pdf file to my e-mail. I know it isn't my headers since the script is successfully attaching a vcard generated by a string earlier within it.
Since I am not editing the file, TDPDF & FPDF shouldn't be required. (not 100% on that though) Here is the code I've been working with. I've included my output testing lines & comments.
//File Definition
$filepath = "docs/";
//$filepath = "./docs/"; //tried: same result
$fullpath = $filepath . $filename; //$filename defined earlier
//File Manipulation
$file = fopen($fullpath,'rb');
$pdfdata = fread($file, filesize($fullpath));
fclose($file);
//Testing
echo $fullpath . "<br />\n";
echo "Filename: " .$filename . "<br />\n";
echo "Filesize: " .filesize($fullpath). "<br />\n";
echo "String Length: " .strlen($pdfdata). "<br />\n";
//The Following line proved the variable is dumping properly,
//but its content cannot be used for file_get_contents...huh?
//var_dump($pdfdata); //Only used for proofing
echo "Probable Errors for file_get_contents<br />\n";
$data = file_get_contents($pdfdata);
// The following line: Sends File, but is 0 bytes
//$attachment = chunk_split(base64_encode($pdfdata));
//default
$attachment = chunk_split(base64_encode(file_get_contents($pdfdata)));
This outputs:
docs/pdf-to-send.pdf
Filename: pdf-to-send.pdf
Filesize: 37907
String Length: 37907
Probable Errors for file_get_contents
Warning: file_get_contents(%PDF-1.5 % ... (truncated by me)
... ) [function.file-get-contents]: failed to open stream: No such file or directory in /my/hosting/directory/mailer.php on line 337
Warning: file_get_contents(%PDF-1.5 % ... (truncated by me )
... ) [function.file-get-contents]: failed to open stream: No such file or directory in /my/hosting/directory/mailer.php on line 339
Its telling me the file size, that can be found in 2 different variables: $pdfdata & $filesize. They match up. I will mention that the response that I truncated (due to the charset) is already truncated by the server. Its why I started checking the length.
Finally, just in case it could possibly be my headers since I was able to successfully send a 0 byte file, here are those lines...
$body .= "--". $mime_boundary. "\r\n" ;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"". "\r\n";
$body .= "Content-Transfer-Encoding: base64" . "\r\n";
$body .= "Content-Disposition: attachment;" . "\r\n";
$body .= "filename=\"".$filename."\"" . "\r\n\n";
$body .= $attachment . "\n\n";
I am aware that I can change (and have tried) the "Content-Type" to "application/pdf".
My charset is UTF-8. I may be misunderstanding "binary-safe" descriptions for fopen() & fread(), but that shouldn't cause the script to fail. Should it?
Any help resolving this would be greatly appreciated.
Ok. I fixed it. Oddly enough it WAS in my headers.
The header command I posted was actually correct. Sadly I posted my vcard attachment body ammendment. So the question already had my answer in it. ::bonk::
This line is correct.
$body .= "filename=\"".$filename."\"" . "\r\n\n";
$body .= $attachment . "\n\n";
This is what I actually had.
$body .= "filename=\"".$filename."\"" . "\r\n";
This explains why I had a 0 byte attachment.
And, just to show the snippet that actually worked:
//File Manipulation
$file = fopen($fullpath,'rb');
$pdfdata = fread($file, filesize($fullpath));
fclose($file);
//Testing
// echo $fullpath . "<br />\n";
//echo "Filename: " .$filename . "<br />\n";
//echo "Filesize: " .filesize($fullpath). "<br />\n";
// echo "String Length: " .strlen($pdfdata). "<br />\n";
//var_dump($pdfdata); // Don't remove this (as a comment) again. LOL
// echo "Probable Errors for file_get_contents<br />\n";
//$data = file_get_contents($pdfdata, true);
$attachment = chunk_split(base64_encode($pdfdata));
//$attachment = chunk_split(base64_encode(file_get_contents($pdfdata)));
Sorry if I wasted anyone's time.

How to get email and their attachments from PHP

I'm writing a photo gallery webapp for a friend's wedding and they want a photo gallery for guests to submit the digital photos they take on the day.
After evaluating all the options, I've decided the easiest thing for users would be to let them use a familiar interface (their email) and just have them send in the pictures as attachments.
I've created an mailbox but now I need to connect and retrieve these attachments for automated processing for adding to the gallery system. But how? Are there any tutorials or prefab classes you've seen for doing this?
I used to do a lot of this before, but I can't find the code, here's a scaled down version I found. It should put you on the correct path. I used to run this type of script from a cronjob. Sorry I can't find the final version. ;(
// Open pop mailbox
if (!$mbox = imap_open ("{localhost:110/pop3/notls}INBOX", "user", "tester")) {
die ('Cannot connect/check pop mail! Exiting');
}
if ($hdr = imap_check($mbox)) {
$msgCount = $hdr->Nmsgs;
} else {
echo "Failed to get mail";
exit;
}
$MN=$msgCount;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
for ($X = 1; $X <= $MN; $X++) {
$file = imap_fetchbody($mbox, $X, 1);
imap_delete($mbox, $X);
}
imap_expunge($mbox);
imap_close($mbox);
Good luck!
Have you considered using Google's Picasa Web Albums?
You can set up an email address to send photos to and share them online.
You can then get an RSS feed of these photos, which most programmers are
more familiar with than MTAs.
If you're creating a dedicated mailbox for this purpose, using a filtering mechanism is almost definitely not what you want. Instead, you want to have the mailbox be a pipe to the application, and have the application simply read in the message from stdin, parse out the body, and MIME parse the body to get the attachments.
Having a mailbox be a pipe is supported by all the popular unix-based MTAs that I know of, such as sendmail, postfix, and qmail. Generally you define it in your aliases file, like so:
# sendmail or postfix syntax
msgsubmit: "| /usr/bin/php ~path/to/example.php"
Then mails to msgsubmit# get routed to a php program for delivery.
This has the advantage of not relying on an IMAP server or any other server beyond the MTA being alive, and it works fine as long as you have control over the MTA of the destination host. Filtering is what you'd want if you wanted all messages on a system to be inspected by the script, which I'm guessing is not the case.
If you want a copy kept in a mailbox somewhere (not a bad idea) simply define the alias to go to multiple addresses, like so:
msgsubmit: "| /usr/bin/php ~path/to/example.php", msgsubmit-box
Or postfix virtual format:
msgsubmit
"| /usr/bin/php ~path/to/example.php"
msgsubmit-box
What MTA are you using? If you use postfix + maildrop you can create a filtering rule that pipes certain messages through a PHP script that then handles the incoming mails. (google for maildrop and xfilter).
I think you want a MIME message parser.
I've used this one before and it seems to work fine, although I haven't tested it on really big attachments (i.e. 2-3MB files you might get from digital cameras).
Have you already got a system for reading POP3 / IMAP mailboxes? There is another class on the same site which also works on POP3 (I believe there is also an IMAP one) - however if you will be downloading a fair volume maybe you'll want to investigate a few C-based solutions as I believe that one is pure PHP.
Majordomo, could be an alternative to handle emails, but there are some limitations on file attachment handling.
<?php
//make sure that submit button name is 'Submit'
if(isset($_POST['Submit'])){
$name = $_POST['visitorname'];
$email = $_POST['visitoremail'];
$message = $_POST['visitormessage'];
$to="youremail#yourdomain.com";
$subject="From ".$name;
$from = $email;
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// next, we'll build the invisible portion of the message body
// note that we insert two dashes in front of the MIME boundary
// when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
foreach($_FILES as $userfile)
{
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name))
{
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name))
{
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$ok = #mail($to, $subject, $message , $headers);
if ($ok) {
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
}
else
{
}
echo "<span class='red'>E-mail has been sent successfully from $mail_name to $to</span>"; }
else{
echo "<span class='red'>Failed to send the E-mail from $from to $to</span>";
}
}
?>
p/s:I used this code.hope its work and assist you.just copy and paste.make sure your textfield name is same as in this page.its work for all types of files.for further questions,just email me at shah#mc-oren.com.anyway,i also in learning process.=).thanks.

Categories