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.
Related
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?
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);
}
}
}
}
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.
I've got a script running when a certain email address receives an email, procmail pipes to a PHP script, which is then parsed by Plancake, not many problems there. I've got an if statement on strpos, depending on if the body contains a certain text. For some reason, when I add the MySQL code, the entire thing stops working. Unfortunately the way it's setup I'm not quite sure how to add error checking. Here's the code:
<?php
require_once("PlancakeEmailParser.php");
$rawEmail = '';
if (($fp = fopen('php://stdin', 'r')) !== false) {
while (!feof($fp)) {
$rawEmail .= fread($fp, 1024);
}
fclose($fp);
}
$emailParser = new PlancakeEmailParser($rawEmail);
$emailSubject = $emailParser->getSubject();
$emailBody = $emailParser->getPlainBody();
$emailHeader = $emailParser->getHeader('From');
$message = "FROM: ".$emailHeader."\n\nSubject: ".$emailSubject."\n\nBody: ".$emailBody;
$status = 4;
preg_match("/\d+/", "$emailSubject", $matches);
$number = $matches[0];
$short = substr($message, 0, strpos( $message, 'Begin'));
if (stripos($short,'approve') !== false) {
echo 'true';
$msg = approve;
//file_put_contents('/home/symantec_mail/task' . $number . 'short.php',$msg);
file_put_contents('/home/symantec_mail/task' . $number . 'approve_short_reply.txt',$message);
file_put_contents('/home/symantec_mail/task' . $number . 'approve_reply.txt',$rawEmail);
}
if (stripos($short,'complete') !== false) {
echo 'true';
$msg = complete;
when I uncomment the following mysqli code, everything stops.
//$mysqli = new mysqli("localhost", "user", "pass", "db");
//$update = $mysqli->prepare("UPDATE task_overview SET status = ? WHERE task_id = ?");
//$update->bind_param('ii', $status, $number");
//$update->execute();
rest of the code.
//file_put_contents('/home/symantec_mail/task' . $number . 'short.php',$msg);
file_put_contents('/home/symantec_mail/' . $number . 'complete_short_reply.txt',$message);
file_put_contents('/home/symantec_mail/' . $number . 'complete_reply.txt',$rawEmail);
}
?>
Really not sure why I can't execute these commands. I will point out that it's on a different shell account than my normal web server, although the PHP is still executing, I'm really not sure if I'm communicating with the MySQL server. Please if you have any suggestions, even if it's for error checking I'll greatly appreciate it.
I'm using the following php script to receive and process emails, putting the various pieces into variables to handle later on.
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
Im wondering where would i start in order to accept a picture attachment and isolate that into a variable so i can process it however i needed to.
I would use MimeMailParse (http://code.google.com/p/php-mime-mail-parser/)
Then you could simply say
$parser = new MimeMailParser();
$parser->setStream(STDIN);
// Handle images
$path = '/tmp/';
$filename = '';
$attachments = $parser->getAttachments();
foreach ($attachments as $attachment) {
if (preg_match('/^image/', $attachment->content_type, $matches)) {
$pathinfo = pathinfo($attachment->filename);
$filename = $pathinfo['filename'];
if ($fp = fopen($path.$filename, 'w')) {
while ($bytes = $attachment->read()) {
fwrite($fp, $bytes);
}
fclose($fp);
}
}
}
You would need to do alot more than what you are doing. You have to detect the mime boundaries in the header, then find the multipart boundary and unbase64 the text. You would be much better off using a library for this sort of thing.