PHP Backup database and send email [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I found a PHP script that backups the database of my website and sends the file to an emailadress of my choice. I implemented it on my website, but it fails.
The Backup Class. This handles the backup and the email:
<?php
class Backup
{
/**
* #var stores the options
*/
var $config;
/**
* #var stores the final sql dump
*/
var $dump;
/**
* #var stores the table structure + inserts for every table
*/
var $struktur = array();
/**
* #var zip file name
*/
var $datei;
/**
* this function is the constructor and phrase the options
* and connect to the database
* #return
*/
public function Backup($options)
{
// write options
foreach($options AS $name => $value)
{
$this->config[$name] = $value;
}
// check mysql connection
mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
}
/**
* this function start the backup progress its the core function
* #return
*/
public function backupDB()
{
// start backup
if(isset($_POST['backup']))
{
// check if tables are selected
if(empty($_POST['table']))
{
die("Please select a table.");
}
/** start backup **/
$tables = array();
$insert = array();
$sql_statement = '';
// lock tables
foreach($_POST['table'] AS $table)
{
mysql_query("LOCK TABLE $table WRITE");
// Read table structure
$res = mysql_query('SHOW CREATE TABLE '.$table.'');
$createtable = mysql_result($res, 0, 1);
$str = "\n\n".$createtable."\n\n";
array_push($tables, $str);
// Read table "inserts"
$sql = 'SELECT * FROM '.$table;
$query = mysql_query($sql) or die(mysql_error());
$feld_anzahl = mysql_num_fields($query);
$sql_statement = '--
-- Data Table `$table`
--
';
// start reading progress
while($ds = mysql_fetch_object($query)){
$sql_statement .= 'INSERT INTO `'.$table.'` (';
for ($i = 0;$i <$feld_anzahl;$i++){
if ($i ==$feld_anzahl-1){
$sql_statement .= mysql_field_name($query,$i);
} else {
$sql_statement .= mysql_field_name($query,$i).', ';
}
}
$sql_statement .= ') VALUES (';
for ($i = 0;$i <$feld_anzahl;$i++){
$name = mysql_field_name($query,$i);
if (empty($ds->$name)){
$ds->$name = 'NULL';
}
if ($i ==$feld_anzahl-1){
$sql_statement .= '"'.$ds->$name.'"';
} else {
$sql_statement .= '"'.$ds->$name.'", ';
}
}
$sql_statement .= ");\n";
}
// insert "Inserts" into an array if not exists
if(!in_array($sql_statement, $insert))
{
array_push($insert, $sql_statement);
unset($sql_statement);
}
unset($sql_statement);
}
// put table structure and inserts together in one var
$this->struktur = array_combine($tables, $insert);
// create full dump
$this->createDUMP($this->struktur);
// create zip file
$this->createZIP();
/** end backup **/
// send an email with the sql dump
if(isset($this->config['email']) && !empty($this->config['email']))
{
$this->sendEmail();
}
// output
echo '<h3 style="color:green;">Backup war erfolgreich</h3>Download Backup
<br />
<br />';
}
}
/**
* this function generate an email with attachment
* #return
*/
protected function sendEmail()
{
// start sending emails
foreach($this->config['email'] AS $email)
{
$to = $email;
$from = $this->config['email'][0];
$message_body = "This email contains the database backup as a zip file.";
$msep = strtoupper (md5 (uniqid (time ())));
// set email header (only text)
$header =
"From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed; boundary=" . $msep ."\r\n\r\n" .
"--" . $msep . "\r\n" .
"Content-Type: text/plain\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n" .
$message_body . "\r\n";
// file name
$dateiname = $this->datei;
// get filesize of zip file
$dateigroesse = filesize ($dateiname);
// open file to read
$f = fopen ($dateiname, "r");
// save content
$attached_file = fread ($f, $dateigroesse);
// close file
fclose ($f);
// create attachment
$attachment = chunk_split (base64_encode ($attached_file));
// set attachment header
$header .=
"--" . $msep . "\r\n" .
"Content-Type: application/zip; name='Backup'\r\n" .
"Content-Transfer-Encoding: base64\r\n" .
"Content-Disposition: attachment; filename='Backup.zip'\r\n" .
"Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
$attachment . "\r\n";
// mark end of attachment
$header .= "--" . "$msep--" . ";
// eMail Subject
$subject = "Database Backup";
// send email to emails^^
if(mail($to, $subject, '', $header) == FALSE)
{
die("The email could not be sent. Please check the email address.");
}
echo "<p><small>Email was successfully sent.</small></p>";
}
}
/**
* this function create the zip file with the database dump and save it on the ftp server
* #return
*/
protected function createZIP()
{
// Set permissions to 777
chmod($this->config['folder'], 0777);
// create zip file
$zip = new ZipArchive();
// Create file name
$this->datei = $this->config['folder'] . $this->config['mysql'][3] . "_" . date("j_F_Y_g:i_a") . ".zip";
// Checking if file could be created
if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <".$this->datei.">\n");
}
// add mysql dump to zip file
$zip->addFromString("dump.sql", $this->dump);
// close file
$zip->close();
// Check whether file has been created
if(!file_exists($this->datei))
{
die("The ZIP file could not be created.");
}
echo "<p><small>The zip was created.</small></p>";
}
/**
* this function create the full sql dump
* #param object $dump
* #return
*/
protected function createDUMP($dump)
{
$date = date("F j, Y, g:i a");
$header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}
--
-- Datenbank: `{$this->config['mysql'][3]}`
--
-- --------------------------------------------------------
HEADER;
foreach($dump AS $name => $value)
{
$sql .= $name.$value;
}
$this->dump = $header.$sql;
}
/**
* this function displays the output form to select tables
* #return
*/
public function outputForm()
{
// select all tables from database
$result = mysql_list_tables($this->config['mysql'][3]);
$buffer = '
<fieldset>
<legend>Select some tables</legend>
<form method="post" action="">
<select name="table[]" multiple="multiple" size="30">';
while($row = mysql_fetch_row($result))
{
$buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
}
$buffer .= '</select>
<br /><br />
<input type="submit" name="backup" value="Backup Tables" />
</form>
</fieldset>';
echo $buffer;
}
}
?>
Next is the handler that it called when a user pushes the Backup button on the website:
<?php
//You can add as many email addresses as you like
$options = array( 'email' => array('email1, email2'),
'folder' => './backup/',
'mysql' => array('localhost', 'root', '', 'database')
);
$b = new Backup($options);
// if submit form start backup
if(isset($_POST['backup']))
{
// start backup
$b->backupDB();
}
// display tables
$b->outputForm();
?>
The last script works as far as I can tell. But the other gives the following error message
Parse error: syntax error, unexpected T_VARIABLE in /home/u164555197/public_html/ChiroDB2/Scripts/PHP/backupdb.php on line 170
Line 170 is located in the function that handles the generation of the email (function SendEmail())
Can someone help me locate this error and maybe has a solution?

Change the lines so they are
// mark end of attachment
$header .= "--" . $msep . "--";
// eMail Subject
$subject = "Database Backup";
This is line 202 of the class you pasted.
<?php
class Backup
{
/**
* #var stores the options
*/
var $config;
/**
* #var stores the final sql dump
*/
var $dump;
/**
* #var stores the table structure + inserts for every table
*/
var $struktur = array();
/**
* #var zip file name
*/
var $datei;
/**
* this function is the constructor and phrase the options
* and connect to the database
* #return
*/
public function Backup($options)
{
// write options
foreach($options AS $name => $value)
{
$this->config[$name] = $value;
}
// check mysql connection
mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
}
/**
* this function start the backup progress its the core function
* #return
*/
public function backupDB()
{
// start backup
if(isset($_POST['backup']))
{
// check if tables are selected
if(empty($_POST['table']))
{
die("Please select a table.");
}
/** start backup **/
$tables = array();
$insert = array();
$sql_statement = '';
// lock tables
foreach($_POST['table'] AS $table)
{
mysql_query("LOCK TABLE $table WRITE");
// Read table structure
$res = mysql_query('SHOW CREATE TABLE '.$table.'');
$createtable = mysql_result($res, 0, 1);
$str = "\n\n".$createtable."\n\n";
array_push($tables, $str);
// Read table "inserts"
$sql = 'SELECT * FROM '.$table;
$query = mysql_query($sql) or die(mysql_error());
$feld_anzahl = mysql_num_fields($query);
$sql_statement = '--
-- Data Table `$table`
--
';
// start reading progress
while($ds = mysql_fetch_object($query)){
$sql_statement .= 'INSERT INTO `'.$table.'` (';
for ($i = 0;$i <$feld_anzahl;$i++){
if ($i ==$feld_anzahl-1){
$sql_statement .= mysql_field_name($query,$i);
} else {
$sql_statement .= mysql_field_name($query,$i).', ';
}
}
$sql_statement .= ') VALUES (';
for ($i = 0;$i <$feld_anzahl;$i++){
$name = mysql_field_name($query,$i);
if (empty($ds->$name)){
$ds->$name = 'NULL';
}
if ($i ==$feld_anzahl-1){
$sql_statement .= '"'.$ds->$name.'"';
} else {
$sql_statement .= '"'.$ds->$name.'", ';
}
}
$sql_statement .= ");\n";
}
// insert "Inserts" into an array if not exists
if(!in_array($sql_statement, $insert))
{
array_push($insert, $sql_statement);
unset($sql_statement);
}
unset($sql_statement);
}
// put table structure and inserts together in one var
$this->struktur = array_combine($tables, $insert);
// create full dump
$this->createDUMP($this->struktur);
// create zip file
$this->createZIP();
/** end backup **/
// send an email with the sql dump
if(isset($this->config['email']) && !empty($this->config['email']))
{
$this->sendEmail();
}
// output
echo '<h3 style="color:green;">Backup war erfolgreich</h3>Download Backup
<br />
<br />';
}
}
/**
* this function generate an email with attachment
* #return
*/
protected function sendEmail()
{
// start sending emails
foreach($this->config['email'] AS $email)
{
$to = $email;
$from = $this->config['email'][0];
$message_body = "This email contains the database backup as a zip file.";
$msep = strtoupper (md5 (uniqid (time ())));
// set email header (only text)
$header =
"From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed; boundary=" . $msep ."\r\n\r\n" .
"--" . $msep . "\r\n" .
"Content-Type: text/plain\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n" .
$message_body . "\r\n";
// file name
$dateiname = $this->datei;
// get filesize of zip file
$dateigroesse = filesize ($dateiname);
// open file to read
$f = fopen ($dateiname, "r");
// save content
$attached_file = fread ($f, $dateigroesse);
// close file
fclose ($f);
// create attachment
$attachment = chunk_split (base64_encode ($attached_file));
// set attachment header
$header .=
"--" . $msep . "\r\n" .
"Content-Type: application/zip; name='Backup'\r\n" .
"Content-Transfer-Encoding: base64\r\n" .
"Content-Disposition: attachment; filename='Backup.zip'\r\n" .
"Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
$attachment . "\r\n";
// mark end of attachment
$header .= "--" . $msep . "--";
// eMail Subject
$subject = "Database Backup";
// send email to emails^^
if(mail($to, $subject, '', $header) == FALSE)
{
die("The email could not be sent. Please check the email address.");
}
echo "<p><small>Email was successfully sent.</small></p>";
}
}
/**
* this function create the zip file with the database dump and save it on the ftp server
* #return
*/
protected function createZIP()
{
// Set permissions to 777
chmod($this->config['folder'], 0777);
// create zip file
$zip = new ZipArchive();
// Create file name
$this->datei = $this->config['folder'] . $this->config['mysql'][3] . "_" . date("j_F_Y_g:i_a") . ".zip";
// Checking if file could be created
if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <".$this->datei.">\n");
}
// add mysql dump to zip file
$zip->addFromString("dump.sql", $this->dump);
// close file
$zip->close();
// Check whether file has been created
if(!file_exists($this->datei))
{
die("The ZIP file could not be created.");
}
echo "<p><small>The zip was created.</small></p>";
}
/**
* this function create the full sql dump
* #param object $dump
* #return
*/
protected function createDUMP($dump)
{
$date = date("F j, Y, g:i a");
$header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}
--
-- Datenbank: `{$this->config['mysql'][3]}`
--
-- --------------------------------------------------------
HEADER;
foreach($dump AS $name => $value)
{
$sql .= $name.$value;
}
$this->dump = $header.$sql;
}
/**
* this function displays the output form to select tables
* #return
*/
public function outputForm()
{
// select all tables from database
$result = mysql_list_tables($this->config['mysql'][3]);
$buffer = '
<fieldset>
<legend>Select some tables</legend>
<form method="post" action="">
<select name="table[]" multiple="multiple" size="30">';
while($row = mysql_fetch_row($result))
{
$buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
}
$buffer .= '</select>
<br /><br />
<input type="submit" name="backup" value="Backup Tables" />
</form>
</fieldset>';
echo $buffer;
}
}
?>

Use MysqlDumper. Its the best suggestion I can give.
I also use it for my website.
There is an own interface to configure it. And there is also the option to automaticly backup your database and send a mail at a specific time with a success-message. If you want to, you can append the backup to the mail (not suggested with big dbs).
Heres a link.
Unfortunately I can provide any code for this as there isnt anything you need to setup by php-code itself.
How to install:
Just copy & paste the folder to your webserver and open the index-page. A setup will start automaticly that asks for a database-setup (login-details, connection etc). After that its ready to use.

Related

Send two attachments in email, PHP

Need your advice on how to make a mail with two attachments (one-time downloadable links) and send it using PHP.
For now, I have a code that sends only one link and it works fine. Actually how I've built my program is that I have two PHP files: url.php and get_file.php. In get_file.php I create a one-time downloadable URL to the document I want to send via email using url.php.
Here is a code of get_file.php:
<?php
/* Retrieve the given token: */
$token = $_GET['q'];
if( strlen($token)<32 )
{
die("Invalid token!");
}
/* Define the file for download: */
$secretfile = "file1.pdf";
/* This variable is used to determine if the token is valid or not: */
$valid = 0;
/* Define what file holds the ids. */
$file = "urls.txt";
/* Read the whole token-file into the variable $lines: */
$lines = file($file);
/* Truncate the token-file, and open it for writing: */
if( !($fd = fopen("urls.txt","w")) )
die("Could not open $file for writing!");
/* Aquire exclusive lock on $file. */
if( !(flock($fd,LOCK_EX)) )
die("Could not equire exclusive lock on $file!");
/* Loop through all tokens in the token-file: */
for( $i = 0; $i < count($lines); $i++ )
{
/* Is the current token the same as the one defined in $token? */
if( $token == rtrim($lines[$i]) )
{
$valid = 1;
}
/* The code below will only get executed if $token does NOT match the
current token in the token file. The result of this will be that
a valid token will not be written to the token file, and will
therefore only be valid once. */
else
{
fwrite($fd,$lines[$i]);
}
}
/* We're done writing to $file, so it's safe release the lock. */
if( !(flock($fd,LOCK_UN)) )
die("Could not release lock on $file!");
/* Save and close the token file: */
if( !(fclose($fd)) )
die("Could not close file pointer for $file!");
/* If there was a valid token in $token, output the secret file: */
if( $valid )
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($secretfile).'"';
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
/*header('Content-Length: ' . filesize($file));*/
readfile($secretfile);
}
else
{
print "Invalid URL!";
}
?>
Here is a code of url.php:
<?php
$token = md5(uniqid(rand(),1));
$file = "urls.txt";
if( !($fd = fopen($file,"a")) )
die("Could not open $file!");
if( !(flock($fd,LOCK_EX)) )
die("Could not aquire exclusive lock on $file!");
if( !(fwrite($fd,$token."\n")) )
die("Could not write to $file!");
if( !(flock($fd,LOCK_UN)) )
die("Could not release lock on $file!");
if( !(fclose($fd)) )
die("Could not close file pointer for $file!");
$cwd = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],"/"));
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$a = "http://".$_SERVER['HTTP_HOST']."$cwd/get_file.php?q=$token";
$email_to = $_POST['email'];
$email_to_bcc = "mail#mail.com";
$email_from = "mail#mail.com";
$email_subject = "download link";
$email_message = "Thank you for your purchase.\n\n";
$comments = $a;
$email_message .= "Here is your one-time link to download the file:\n".clean_string($comments);
$headers = 'From: '.$email_from."\r\n" .
'BCC: '.$email_to_bcc."\r\n" .
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
?>
The question is whether in my get_file.php I can define two files for download, create two downloadable links and than create two attachments in the header?

Php email attachment extraction

I'm trying to create a piece of code that will go into the mailbox and take out the attachments of a specific file. So far I am only able to view if there is an attachment or if there is not an attachment on the e-mail.
But I want it to be able to take the attachments out of the e-mail and then save them to a specified directory. The type of attachment I'm trying to take out is a .jpg
I've tried a bunch of different pieces of code that I've found on google and I've been trying to tailor it to fit into my code, but so far I have been unsuccessful in finding anything that works correctly.
I was wondering if anyone would be able to help me create a piece of code that would be able to take the attachments out of the emails and store them in a directory.
Thanks.
<?php
/* connect to email */
$hostname = '{*****.com:110/pop3}INBOX';
$username = '*****';
$password = '*****';
// try to connect
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());
// grab emails
$emails = imap_search($inbox,'ALL');
// Search for the 39th email, which has an attachment
$count = 39;
// Fetch all the information about an email
$attachment = imap_fetchstructure($inbox, $count);
// find out how may parts the object has
$numparts = count($attachment->parts);
// find if if multipart message
if ($numparts >= 2) {
foreach ($attachment->parts as $part) {
if ($part->disposition == "INLINE") {
// inline message. Show number of lines
printf("Inline message has %s lines<BR>", $part->lines);
} elseif ($part->disposition == "ATTACHMENT") {
// an attachment
echo "Attachment found!";
// print out the file name
echo "Filename: ", $part->dparameters[0]->value;
}
}
}
//}
else {
// only one part so get some useful info
echo "No attachment";
}
imap_close($imap);
?>
Instead of imap_search I used imap_check to retrieve messages overview, and the following worked.
Go over messages found with imap_check, and this is how you extract the binary data of attachment:
$mbox = imap_open( . . . . );
$IMAPobj = imap_check($inbox);
$start = $IMAPobj->Nmsgs-30;
$end = $IMAPobj->Nmsgs;
$result = imap_fetch_overview($inbox,"$start:$end",0);
$count = $end;
foreach ($result as $overview) {
$parts = mail_mime_to_array($inbox, $count);
foreach($parts as $part) {
if(#$part['filename'] || #$part['name'] ) {
$partName = $part['filename'] ? $part['filename'] : $part['name'];
echo "Attachment name is " . basename($partName);
echo "\n";
if(preg_match( . . . write here a regex to detect ".jpg" in $partName . . .)) {
echo "Found file! Extracting binary data...";
$fileContents = $part['data'];
file_put_contents("attachment.jpg", $fileContents);
}
}
}
}

PHP recursive detect file system changes

I was looking for a practical way to detect file system changes. Than I found this pretty simple script from "Jonathan Franzone". But my problem is, it doesn't scan sub folders. Since I'm just a newbie in PHP, I would like to ask in here to have robust offers to solve.
Note: I made an extended search on site before writing. Many questions asked about this aproach to secure website. But no complete reply at all.
<?php
/**
* File : ftpMonitor.php
* Monitors a remote directory via FTP and emails a list of changes if any are
* found.
*
* #version June 4, 2008
* #author Jonathan Franzone
*/
// Configuration ///////////////////////////////////////////////////////////////
$host = 'ftp.domain.com';
$port = 21;
$user = 'username';
$pass = 'password';
$remote_dir = '/public_html';
$cache_file = 'ftp_cache';
$email_notify = 'your.email#gmail.com';
$email_from = 'email.from#gmail.com';
// Main Run Program ////////////////////////////////////////////////////////////
// Connect to FTP Host
$conn = ftp_connect($host, $port) or die("Could not connect to {$host}\n");
// Login
if(ftp_login($conn, $user, $pass)) {
// Retrieve File List
$files = ftp_nlist($conn, $remote_dir);
// Filter out . and .. listings
$ftpFiles = array();
foreach($files as $file)
{
$thisFile = basename($file);
if($thisFile != '.' && $thisFile != '..') {
$ftpFiles[] = $thisFile;
}
}
// Retrieve the current listing from the cache file
$currentFiles = array();
if(file_exists($cache_file))
{
// Read contents of file
$handle = fopen($cache_file, "r");
if($handle)
{
$contents = fread($handle, filesize($cache_file));
fclose($handle);
// Unserialize the contents
$currentFiles = unserialize($contents);
}
}
// Sort arrays before comparison
sort($currentFiles, SORT_STRING);
sort($ftpFiles, SORT_STRING);
// Perform an array diff to see if there are changes
$diff = array_diff($ftpFiles, $currentFiles);
if(count($diff) > 0)
{
// Email the changes
$msg = "<html><head><title>ftpMonitor Changes</title></head><body>" .
"<h1>ftpMonitor Found Changes:</h1><ul>";
foreach($diff as $file)
{
$msg .= "<li>{$file}</li>";
}
$msg .= "</ul>";
$msg .= '<em>Script by Jonathan Franzone</em>';
$msg .= "</body></html>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "To: {$email_notify}\r\n";
$headers .= "From: {$email_from}\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
mail($email_notify, "ftpMonitor Changes Found", $msg, $headers);
}
// Write new file list out to cache
$handle = fopen($cache_file, "w");
fwrite($handle, serialize($ftpFiles));
fflush($handle);
fclose($handle);
}
else {
echo "Could not login to {$host}\n";
}
// Close Connection
ftp_close($conn);
?>
Thanks for anyone have a solution or at least try to help.
EDIT: Actually I was willing to ask for deleting automatically but, I dont want to be too much demanding. Why not if it will not be a pain.

PHP email interception not sending email with attachments

I have set email interception on my server.
following is my email forwarder set on server
testemail#my.server.com,"/home/server/php_pipe_mail.php"
following is my code for php_pipe_mail.php
#!/usr/bin/php -q
<?php
require_once('mimeDecode.php');
include('sql-connect.php');
error_reporting(E_ALL);
ob_start();
$raw_email = '';
if (!$stdin = fopen("php://stdin", "R"))
{
echo "ERROR: UNABLE TO OPEN php://stdin \n";
}
// ABLE TO READ THE MAIL
else
{
while (!feof($stdin))
{
$raw_email .= fread($stdin, 4096);
}
fclose($stdin);
}
$raw_email = preg_replace('/ +/', ' ', $raw_email);
var_dump($raw_email);
$buf = ob_get_contents();
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$params['input'] = $buf;
$params['crlf'] = "\r\n";
//Creating temp file on server
$myFile = "amail.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $buf);
fclose($fh);
//Generating mail structure in object format
$structure = Mail_mimeDecode::decode($params);
$attachment = array();
$mail_date= date( 'Y-m-d H:i:s', strtotime($structure->headers['date']) );
$from = $structure->headers['from'];
$to = $structure->headers['to'];
$subject = htmlentities($structure->headers['subject'],ENT_QUOTES);
if($structure->ctype_primary == "multipart")
{
$body_text = $structure->parts[0]->parts[0]->body;
$body_html = $structure->parts[0]->parts[1]->body;
$x = 0;
//fetch attachment
foreach ($structure->parts as $part) {
// only save if an attachment
if (isset($part->disposition) and ($part->disposition=='attachment')) {
$attachment[$x]["filename"] = $part->d_parameters['filename'];
$attachment[$x]["content_type"] = $part->ctype_primary . "/" . $part->ctype_secondary;
$attachment[$x]["body"] = addslashes($part->body);
$x++;
}
}
}
else
{
$body_text = $structure->parts[0]->body;
$body_html = $structure->parts[1]->body;
}
$qry1 = "insert into mail_buffer(mail_date,mail_from, mail_to,mail_subject,mail_text_body,mail_html_body) Values('". $mail_date ."','".$from."','".$to."','".$subject."','".$body_text."','".$body_html."')";
mysql_query($qry1) or die(mysql_error($con));
$last_id = mysql_insert_id();
if(count($attachment) > 0)
{
for($i=0; $i < count($attachment); $i++)
{
$qry = "insert into mail_attachment(email_id,content_type, file_name,body) Values('". $last_id ."','".$attachment[$i]['content_type']."','".$attachment[$i]['filename']."','".$attachment[$i]['body']."')";
mysql_query($qry) or die(mysql_error($con));
}
}
mysql_close($con);
ob_end_clean();
?>
Now above script works perfectly fine.
I am able to fetch message header, body and attachments and can store them in database without any problems.
When email without attachments come everything works fine and email is delivered to email address I am intercepting.
But following is not working.
When email with attachments comes than email content is being stored in database but email is not delivering to email address I am intercepting and I am getting following error message in bounce back email.
A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:
pipe to |/home/server/php_pipe_mail.php
generated by testemail#my.server.com
Can anyone help me regarding the matter.
Thanks.
Could it be that, when an attachment is present, your script is echoing something? I have had problems piping emails before, and seen failure messages returned to senders, and they have been due to the piping script producing some kind of output. Maybe your error_reporting(E_ALL); is allowing the script to produce an output - try error_reporting(0);

Forcing file download in PHP - inside Joomla framework

I have some PHP code that runs a query on a database, saves the results to a csv file, and then allows the user to download the file. The problem is, the csv file contains page HTML around the actual csv content.
I've read all the related questions here already, including this one. Unfortunately my code exists within Joomla, so even if I try to redirect to a page that contains nothing but headers, Joomla automatically surrounds it with its own navigation code. This only happens at the time of download; if I look at the csv file that's saved on the server, it does not contain the HTML.
Can anyone help me out with a way to force a download of the actual csv file as it is on the server, rather than as the browser is editing it to be? I've tried using the header location, like this:
header('Location: ' . $filename);
but it opens the file in the browser, rather than forcing the save dialog.
Here's my current code:
//set dynamic filename
$filename = "customers.csv";
//open file to write csv
$fp = fopen($filename, 'w');
//get all data
$query = "select
c.firstname,c.lastname,c.email as customer_email,
a.email as address_email,c.phone as customer_phone,
a.phone as address_phone,
a.company,a.address1,a.address2,a.city,a.state,a.zip, c.last_signin
from {$dbpre}customers c
left join {$dbpre}customers_addresses a on c.id = a.customer_id order by c.last_signin desc";
$votes = mysql_query($query) or die ("File: " . __FILE__ . "<br />Line: " . __LINE__ . "<p>{$query}<p>" . mysql_error());
$counter = 1;
while ($row = mysql_fetch_array($votes,1)) {
//put header row
if ($counter == 1){
$headerRow = array();
foreach ($row as $key => $val)
$headerRow[] = $key;
fputcsv($fp, $headerRow);
}
//put data row
fputcsv($fp, $row);
$counter++;
}
//close file
fclose($fp);
//redirect to file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Transfer-Encoding: binary");
readfile($filename);
exit;
EDITS
Full URL looks like this:
http://mysite.com/administrator/index.php?option=com_eimcart&task=customers
with the actual download link looking like this:
http://mysite.com/administrator/index.php?option=com_eimcart&task=customers&subtask=export
MORE EDITS
Here's a shot of the page that the code is on; the generated file still is pulling in the html for the submenu. The code for the selected link (Export as CSV) is now
index.php?option=com_eimcart&task=customers&subtask=export&format=raw
Now here is a screenshot of the generated, saved file:
It shrank during the upload here, but the text highlighted in yellow is the html code for the subnav (list customers, add new customer, export as csv). Here's what my complete code looks like now; if I could just get rid of that last bit of html it would be perfect.
$fp= fopen("php://output", 'w');
$query = "select c.firstname,c.lastname,c.email as customer_email,
a.email as address_email,c.phone as customer_phone,
a.phone as address_phone, a.company, a.address1,
a.address2,a.city,a.state,a.zip,c.last_signin
from {$dbpre}customers c
left join {$dbpre}customers_addresses a on c.id = a.customer_id
order by c.last_signin desc";
$votes = mysql_query($query) or die ("File: " . __FILE__ . "<br />Line: " . __LINE__ . "<p>{$query}<p>" . mysql_error());
$counter = 1;
//redirect to file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=customers.csv");
header("Content-Transfer-Encoding: binary");
while ($row = mysql_fetch_array($votes,1)) {
//put header row
if ($counter == 1){
$headerRow = array();
foreach ($row as $key => $val)
$headerRow[] = $key;
fputcsv($fp, $headerRow);
}
//put data row
fputcsv($fp, $row);
$counter++;
}
//close file
fclose($fp);
UPDATE FOR BJORN
Here's the code (I think) that worked for me. Use the RAW param in the link that calls the action:
index.php?option=com_eimcart&task=customers&subtask=export&format=raw
Because this was procedural, our link was in a file called customers.php, which looks like this:
switch ($r['subtask']){
case 'add':
case 'edit':
//if the form is submitted then go to validation
include("subnav.php");
if ($r['custFormSubmitted'] == "true")
include("validate.php");
else
include("showForm.php");
break;
case 'delete':
include("subnav.php");
include("process.php");
break;
case 'resetpass':
include("subnav.php");
include("resetpassword");
break;
case 'export':
include("export_csv.php");
break;
default:
include("subnav.php");
include("list.php");
break;
}
So when a user clicked on the link above, the export_csv.php file is automatically included. That file contains all the actual code:
<?
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=customers.csv");
header("Content-Transfer-Encoding: binary");
$fp= fopen("php://output", 'w');
//get all data
$query = "select
c.firstname,c.lastname,c.email as customer_email,
a.email as address_email,c.phone as customer_phone,
a.phone as address_phone,
a.company,a.address1,a.address2,a.city,a.state,a.zip, c.last_signin
from {$dbpre}customers c
left join {$dbpre}customers_addresses a on c.id = a.customer_id order by c.last_signin desc";
$votes = mysql_query($query) or die ("File: " . __FILE__ . "<br />Line: " . __LINE__ . "<p>{$query}<p>" . mysql_error());
$counter = 1;
while ($row = mysql_fetch_array($votes,1)) {
//put header row
if ($counter == 1){
$headerRow = array();
foreach ($row as $key => $val)
$headerRow[] = $key;
fputcsv($fp, $headerRow);
}
//put data row
fputcsv($fp, $row);
$counter++;
}
//close file
fclose($fp);
This is a piece of sample code that I just cooked up to help you out. Use it as an action method in your controller.
function get_csv() {
$file = JPATH_ADMINISTRATOR . DS . 'test.csv';
// Test to ensure that the file exists.
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
// Send file headers
header("Content-type: text/csv");
header("Content-Disposition: attachment;filename=test.csv");
// Send the file contents.
readfile($file);
}
This alone will not be enough, because the file you download will still contain the surrounding html. To get rid of it and only receive the csv file's contents you need to add format=raw parameter to your request. In my case the method is inside the com_csvexample component, so the url would be:
/index.php?option=com_csvexample&task=get_csv&format=raw
EDIT
In order to avoid using an intermediate file substitute
//set dynamic filename
$filename = "customers.csv";
//open file to write csv
$fp = fopen($filename, 'w');
with
//open the output stream for writing
//this will allow using fputcsv later in the code
$fp= fopen("php://output", 'w');
Using this method you have to move the code that sends headers before anything is written to the output. You also won't need the call to the readfile function.
Add this method to your controller:
function exportcsv() {
$model = & $this->getModel('export');
$model->exportToCSV();
}
Then add a new model called export.php, code below. You will need to change or extend the code to your situation.
<?php
/**
* #package TTVideo
* #author Martin Rose
* #website www.toughtomato.com
* #version 2.0
* #copyright Copyright (C) 2010 Open Source Matters. All rights reserved.
* #license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
jimport( 'joomla.filesystem.file' );
jimport( 'joomla.filesystem.archive' );
jimport( 'joomla.environment.response' );
class TTVideoModelExport extends JModel
{
function exportToCSV() {
$files = array();
$file = $this->__createCSVFile('#__ttvideo');
if ($file != '') $files[] .= $file;
$file = $this->__createCSVFile('#__ttvideo_ratings');
if ($file != '') $files[] .= $file;
$file = $this->__createCSVFile('#__ttvideo_settings');
if ($file != '') $files[] .= $file;
// zip up csv files to be delivered
$random = rand(1, 99999);
$archive_filename = JPATH_SITE.DS.'tmp'.DS.'ttvideo_'. strval($random) .'_'.date('Y-m-d').'.zip';
$this->__zip($files, $archive_filename);
// deliver file
$this->__deliverFile($archive_filename);
// clean up
JFile::delete($archive_filename);
foreach($files as $file) JFile::delete(JPATH_SITE.DS.'tmp'.DS.$file);
}
private function __createCSVFile($table_name) {
$db = $this->getDBO();
$csv_output = '';
// get table column names
$db->setQuery("SHOW COLUMNS FROM `$table_name`");
$columns = $db->loadObjectList();
foreach ($columns as $column) {
$csv_output .= $column->Field.'; ';
}
$csv_output .= "\n";
// get table data
$db->setQuery("SELECT * FROM `$table_name`");
$rows = $db->loadObjectList();
$num_rows = count($rows);
if ($num_rows > 0) {
foreach($rows as $row) {
foreach($row as $col_name => $value) {
$csv_output .= $value.'; ';
}
$csv_output .= "\n";
}
}
$filename = substr($table_name, 3).'.csv';
$file = JPATH_SITE.DS.'tmp'.DS.$filename;
// write file to temp directory
if (JFile::write($file, $csv_output)) return $filename;
else return '';
}
private function __deliverFile($archive_filename) {
$filesize = filesize($archive_filename);
JResponse::setHeader('Content-Type', 'application/zip');
JResponse::setHeader('Content-Transfer-Encoding', 'Binary');
JResponse::setHeader('Content-Disposition', 'attachment; filename=ttvideo_'.date('Y-m-d').'.zip');
JResponse::setHeader('Content-Length', $filesize);
echo JFile::read($archive_filename);
}
/* creates a compressed zip file */
private function __zip($files, $destination = '') {
$zip_adapter = & JArchive::getAdapter('zip'); // compression type
$filesToZip[] = array();
foreach ($files as $file) {
$data = JFile::read(JPATH_SITE.DS.'tmp'.DS.$file);
$filesToZip[] = array('name' => $file, 'data' => $data);
}
if (!$zip_adapter->create( $destination, $filesToZip, array() )) {
global $mainframe;
$mainframe->enqueueMessage('Error creating zip file.', 'message');
}
}
}
?>
Then go to your default view.php and add a custom buttom, e.g.
// custom export to set raw format for download
$bar = & JToolBar::getInstance('toolbar');
$bar->appendButton( 'Link', 'export', 'Export CSV', 'index.php?option=com_ttvideo&task=export&format=raw' );
Good luck!
You can use Apache's mod_cern_meta to add HTTP headers to static files. Content-Disposition: attachment. The required .htaccess and .meta files can be created by PHP.
Another way to output CSV data in a Joomla application is to create a view using CSV rather than HTML format. That is, create a file as follows:
components/com_mycomp/views/something/view.csv.php
And add content similar to the following:
<?php
// No direct access
defined('_JEXEC') or die;
jimport( 'joomla.application.component.view');
class MyCompViewSomething extends JViewLegacy // Assuming a recent version of Joomla!
{
function display($tpl = null)
{
// Set document properties
$document = &JFactory::getDocument();
$document->setMimeEncoding('text/csv');
JResponse::setHeader('Content-disposition', 'inline; filename="something.csv"', true);
// Output UTF-8 BOM
echo "\xEF\xBB\xBF";
// Output some data
echo "field1, field2, 'abc 123', foo, bar\r\n";
}
}
?>
Then you can create file download links as follows:
/index.php?option=com_mycomp&view=something&format=csv
Now, you would be right to question the 'inline' part in the Content-disposition. If I recall correctly when writing this code some years ago, I had problems with the 'attachment' option. This link which I just googled now seemed familiar as the driver for it: https://dotanything.wordpress.com/2008/05/30/content-disposition-attachment-vs-inline/ . I've been using 'inline' ever since and am still prompted to save the file appropriately from any browsers I test with. I haven't tried using 'attachment' any time recently, so it may work fine now of course (the link there is 7 years old now!)

Categories