opening attachment from db

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

opening attachment from db

Post by cjkeane »

hi everyone.

i have emails saved into a db with the following data:
date, from, to, message, and filename.
the filename is just that. it doesn't contain the path. files are stored in an attachment folder.

i can display the email message and all the data on a page, but when the filename is clicked on, i want them to be able to download the file. i've done searches on the net but i can't seem to locate examples of how to accomplish what i need to do.

does anyone have any examples on how to accomplish this or do you have a resources i can lookup?

thanks.
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: opening attachment from db

Post by cwheel3915 »

Can I see the code your using to output the data?

EDIT: Here is what I would do anyway. Assuming that your getting the attachment, and emai, and all that by storing it in a a mysql_fetch_assoc.

Code: Select all

$query = "some query to find the needed rows" 

while($emaildata = mysql_fetch_assoc($query))
{

echo "<a href=\"attachmentfolder/\"" . $emaildata['attachment'] . ">" . $emaildata['attachment'] . "</a>";

}
Hope that makes sense. All i did was put a link with the path to the attachment folder in the echo, so when the filename is added you only need to right click, and save as to download the file.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: opening attachment from db

Post by Eran »

It seems to me what you want is to force a download. Read the docs on the readfile() function, especially the first example, it should give you what you need.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: opening attachment from db

Post by cjkeane »

i'm using the following code to display the data to the screen. my issue is that when attachments are saved into the db, they are all saved within the same field:

for e.g.:
subject: test
sender: john smith <johnsmith@home.ca>
toaddress: peter smith <psmith@home.ca>
date: 2011-01-01
originalmsg= test
attachments: filename1.jpg, filename2.doc

i'm not sure how allow users to download each file. any ideas?

Code: Select all

if (isset($_GET['id']))
{
	// query db
	$id = $_GET['id'];
	$result = mysql_query("SELECT *	FROM email WHERE id='$id'") or die(mysql_error()); 
 
 	$row = mysql_fetch_array($result);
	
 	if($row)
 	{
 
 	// get data from db
	$id = $row['id'];
	$subject = $row['subject']; 
	$sender = $row['sender']; 
	$toaddress = $row['toaddress']; 
	$date = $row['date']; 
	$originalmsg = $row['body'];
	$attachments = $row['attachments'];
	}
}

cwheel3915 wrote:Can I see the code your using to output the data?

EDIT: Here is what I would do anyway. Assuming that your getting the attachment, and emai, and all that by storing it in a a mysql_fetch_assoc.

Code: Select all

$query = "some query to find the needed rows" 

while($emaildata = mysql_fetch_assoc($query))
{

echo "<a href=\"attachmentfolder/\"" . $emaildata['attachment'] . ">" . $emaildata['attachment'] . "</a>";

}
Hope that makes sense. All i did was put a link with the path to the attachment folder in the echo, so when the filename is added you only need to right click, and save as to download the file.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: opening attachment from db

Post by flying_circus »

I was kinda bored at work waiting for windows to "update", so I wrote a little snippet for you.

This is a little more robust than what you were trying to do. First, this allows you to change the database query and return all emails based on criteria. For example, say you want to display all emails going to joe@example.org, this snippet can be easily modified to do that. My script also depends on the "attachments" field as being comma-delimited. It must follow the format of a filename followed by a comma (no spaces after the comma. If you have spaces, you'll need to use trim() to remove leading or trailing whitespace: 'attachment1.zip,attachment2.zip,etc.pdf,my_attachment.jpg'

Code: Select all

<?php
  /* -- Server Side: Fetch Emails -- */
  # Define an array to hold emails
    $emails = array();
    
  # Basic Data Validation
    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
  
  # Escape query data and execute query
    $results = mysql_query(sprintf("SELECT `id`, `subject`, `sender`, `toaddress`, `date`, `body`, `attachments` FROM `email` WHERE `id`='%d';",
                                   mysql_real_escape_string($id)));
  # Fetch Results
    if(mysql_num_rows($results)) {
    # There are emails, lets get each...
      while($result = mysql_fetch_array($results)) {
        $emails[$result['id']]['to'] = $result['toaddress'];
        $emails[$result['id']]['from'] = $result['sender'];
        $emails[$result['id']]['date'] = $result['date'];
        $emails[$result['id']]['subject'] = $result['subject'];
        $emails[$result['id']]['body'] = $result['body'];
        $emails[$result['id']]['attachements'] = explode(',', $result['attachments']);
      }
    }
    
    
  /* -- Client Side: Display To User -- */
  // Debug: Uncomment to display array structure (remove before release)
  // print_r($emails);
  
  # For Each Email, display it and each attachment
    foreach($emails as $id => $email) {
    # Display Strings:
      print "Id: {$id}<br />\n";
      print "To: {$email['to']}<br />\n";
      print "From: {$email['from']}<br />\n";
      print "Date: {$email['date']}<br />\n";
      print "Subject: {$email['subject']}<br />\n";
      print "Body: {$email['body']}<br />\n";
      
    # Display Array of attachments:
      foreach($email['attachments'] as $key => $attachment) {
        print "Attachment_{$key}: {$attachment}<br />\n";
      }
    }
?>
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: opening attachment from db

Post by cjkeane »

thanks for the reply. it has been helpful.
to go into further details, file names stored in the db appear as:
ODm0QCVFEsAOHriuFvfS.pdf[test.pdf],XHprKsLP0J1EddvUGgpa.doc[test.doc]

i need to separate the string the commas. Then strip out the name in the []. Then create the href link to the random string name which is what the file is saved as in the attachments folder.

for e.g. the attachments above need to appear as:

<a href="attachments/ODm0QCVFEsAOHriuFvfS.pdf" name="test.pdf">test.pdf</a>
<a href="attachments/XHprKsLP0J1EddvUGgpa.doc" name="test.doc">test.doc</a>

whats the best way to accomplish that?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: opening attachment from db

Post by Weirdan »

Code: Select all

// $attachments = "ODm0QCVFEsAOHriuFvfS.pdf[test.pdf],XHprKsLP0J1EddvUGgpa.doc[test.doc]";
preg_match_all('/([^\[]+)\[([^\]]+)\],?/', $attachments, $matches, PREG_SET_ORDER);
$attachments = array();
foreach ($matches as $file) {
   $attachments[$file[1]] = $file[2];
}

foreach ($attachments as $file => $filename) {
    echo '<a href="folder/' . htmlspecialchars($file, ENT_QUOTES) . '" name="' . htmlspecialchars($filename, ENT_QUOTES) . '">' . htmlspecialchars($filename, ENT_QUOTES) . '</a>' . PHP_EOL;
}
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: opening attachment from db

Post by cjkeane »

thanks for the reply. it is most helpful.
will this work for any number of attachments?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: opening attachment from db

Post by Weirdan »

Should work for several hundreds per email no problem. For more the pcre backtracking may become an issue. You're unlikely to have that many attachments though.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: opening attachment from db

Post by cjkeane »

attachments open in the same browser window, is there a way to prompt for 'save file as' instead?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: opening attachment from db

Post by Weirdan »

Post Reply