PHP - Php Imap Nightmare
Hey guys,
Been developing a bespoke "helpdesk" system for work and, while it works well on the whole, I am having major problems with base64 encoded email bodies. Admittedly, this might be due to my misunderstanding of imap body parts. It seems in my current setup, the system thinks that all mails are either "type" 0 or 4. As a result, base64 emails don't get decoded and display as an unreadable long string. Here is what my code for the body decoding looks like just now - can provide more on request. $from=$overview[0]->from; $subject=$overview[0]->subject; $subdb=mysql_real_escape_string($subject); $lookingfor=explode("~#",$body); $result=$from; $find=strrpos($ir, $lookingfor[1]); $findreplystream=mysql_query("SELECT * FROM tickets WHERE ticket_md5='$lookingfor[1]'") or die(''.mysql_error().''); $stream=mysql_fetch_array($findreplystream); $now=time(); if($structure->encoding == 0){ $arr1=array("=A3", "=80"); $arr2=array("£", "€"); $newcontent=$explodeunder[0]; define("CHARSET", "ISO-8859-1"); $dbcontenta=str_replace($arr1, $arr2, $newcontent); $r=mb_detect_encoding($dbcontenta); if($r=="UTF-8"){ $dbcontents=mb_convert_encoding($dbcontenta, "ISO-8859-1", "UTF-8"); $dbcontent1=addslashes($dbcontents); $dbcontent2=strip_tags($dbcontent1); } elseif($r=="ASCII"){ $dbcontentb=mb_convert_encoding($dbcontenta, "UTF-8", "ASCII"); $dbcontents=mb_convert_encoding($dbcontentb, "ISO-8859-1", "UTF-8"); $dbcontent1=addslashes($dbcontents); $dbcontentf=strip_tags($dbcontent1); $dbcontent2=quoted_printable_decode($dbcontentf); } } elseif($structure->encoding == 4) { $dbcontent=$explodeunder[0]; $dbcontentf=quoted_printable_decode($dbcontent); $dbcontent2=mb_convert_encoding($dbcontentf, "ISO-8859-1", "UTF-8"); } elseif($structure->encoding == 3) { $dbcontent2=imap_base64($explodeunder[0]); } elseif($structure->encoding == 1){ $dbcontent3=imap_8bit($explodeunder[0]); $dbcontent2=quoted_printable_decode($dbcontent3); } Can anyone advise me with this? I'd be greatful for any assistance at all, as it's causing me nightmares! All the best Similar TutorialsThe imap code below displays the date like this: Sat, 18 Feb 2012 19:22:02 +0100 I want the date to be displayed like this instead: 2012-02-18 Any idea how I can achieve this? Thanks in advance Code: [Select] <?php date_default_timezone_set ("Europe/Stockholm"); /* connect to mail */ $hostname = '{xxx.xxxx.com:143/notls}INBOX'; $username = 'xxxxx@xxxxx.com'; $password = 'xxxxxx'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Anslutning till mail misslyckades: ' . imap_last_error()); /* grab emails */ $emails = imap_search($inbox,'ALL'); /* if emails are returned, cycle through each... */ if($emails) { /* begin output var */ $output = ''; /* put the newest emails on top */ rsort($emails); /* for every email... */ foreach($emails as $email_number) { /* get information specific to this email */ $overview = imap_fetch_overview($inbox,$email_number,0); $message = imap_fetchbody($inbox,$email_number,2); $date = date('d m Y'); $swedate = $overview[0]->date; /* output the email information */ $output.= '<li>'; $output.= '<a href="#"><strong>'.$swedate.'</strong> '; $output.= ''.$overview[0]->subject.'<br> '; $output.= '<small> Från: '.$overview[0]->from.'</small></a>'; $output.= '</li>'; } echo $output; } /* close the connection */ imap_close($inbox); ?> How do u work with .jpg file attachments using the IMAP mail functions... i already know how to read the body text from an e-mail with IMAP but I haven't worked with attachments and don't know where to start... i basically want to get the .jpg attachment and save it to a folder on my server. I'm using imap_open and when I use imap_headerinfo and output the info, I want to be able to have an array of words to match the fromaddress to.... case-insensitive. I tried ton of different ways... array_search array_filter stripos stristr And tried adding strtolower in a few Tried setting the object as a var and comparing it that way... but it either chokes on the object or the array... Or ignores it completely For example setting an array like this: Code: [Select] $blacklist_array = array("wl_partners@cupid.com", "Replica Shop", "CJ Adams", "eharmony", "Dr.Maxman", "Credit Check"); And the fromaddress has this in it: Credit Check <check@iamaspammer.com> I can't get it to work to match the Credit Check only part. I got it to work if I do a foreach through the messages and then a foreach through the array then process a good or bad result, but it takes too long if there are a ton of messages to process... The code is a mess right now with all the trial and errors. Any ideas? I'm kinda brain dead at this point and have been up way to long... Thanks... Ok I am having one of those php nightmare. The kind that you simply say, 'WHAT the *^$%*&YU'? I have formed a php called a_user_page.php that is called for by index.php?a=user_page Uses same format as various others that have no problem being viewed on screen. Ok did this some time ago. The page came up and worked perfectly. Now I want to add content to this page. So i naturally save the updated page in a different folder. I am use to things not going my way. Uploaded through ftp program. Page will not view. Strange. So I up loaded the original file and it works. OK So I redue the change I want done making only one word change in heading USER PAGE to USER PROFILE PAGE. Only change. Uploaded. Still Not work SO upload original file and works. OK? So enter into the cpanel and file manager and edit the file online. Put one word change in heading USER PAGE to USER PROFILE PAGE Save View NOT WORK??? Uploaded original file, views!!! What the ? I have tried clear cache and cookies and different browsers. I am Hey,
I have an issue where the below script doesnt appear to be working. It doesnt actually display anything on the page, it seems as though after the first PHP tag is just ignores the rest of the script. when looking at the page source all it shows is:
<HTML> <HEAD> <TITLE>Logs</TITLE> </HEAD> <BODY>The actual code is below: <HTML> <HEAD> <TITLE>Logs</TITLE> </HEAD> <BODY> <?PHP $mysqlserver="localhost"; $mysqlusername="root"; $mysqlpassword="test"; $dbname = 'test'; $con=mysqli_connect($mysqlserver, $mysqlusername, $mysqlpassword, $dbname); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con, "SELECT * FROM forwardtable"); echo "<table border='1'> <tr> <th>Acc Num</th> <th>Send Date</th> <th>Send Time</th> </tr>"; while($rowContent = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $rowContent['Acc'] . "</td>"; echo "<td>" . $rowContent['Date'] . "</td>"; echo "<td>" . $rowContent['Time'] . "</td>"; echo "</tr>"; } echo "</table>" ?> </BODY> </HTML>If I remove the PHP from within the code the source code goes as it should and shows the </BODY> and </HTML> tags. Any ideas anyone? Thanks, Matt Good Afternoon, I wonder if anybody can help me with a couple of PHP issues I am having. I am a Junior Web Designer and have very basic PHP knowledge. I have already done most of the work but I'm having an issue that is driving me mental. I purchased a html template which has a pre-configured contact form that uses jquery validation and "sendmail function." I have made the relevant changes to the PHP file (recipient address and subjet line) however when I go live with the system it only works once and then the html page doesn't process the message. If I go to the PHP location I get a 500 Internal Server Error message. I have contacted my hosting provider (mellowhost) and they have said that my script will only work if I add SMTP Authentication to it, which I have no idea how to do. Here is my script: Code: [Select] <?php // Chnage this according to your settings $to = 'support@gainfordstevens.co.uk'; // Change the mail according to your need. $subject = "Contact Form"; // Mail Subject $success_msg = '<strong style="color:#0033CC">Your Message has been submitted and we will get back to you ASAP.</strong><br /><br />'; // The message displayed after successful mail delivery $failure_msg = '<h2>Contact Form Submitted!</h2> <p>Due to some reason mail is not sent.</p>'; // The message displayed after mail delivery failure //Do not edit below this line. if ( trim($_POST['names']) != '' ) { $names = stripslashes(strip_tags($_POST['names'])); } else { $names = 'No name entered'; } if ( trim($_POST['emails']) != '' ) { $emails = stripslashes(strip_tags($_POST['emails'])); } else { $emails = 'No email entered'; } if ( trim($_POST['phone']) != '' ) { $phone = stripslashes(strip_tags($_POST['phone'])); } else { $phone = 'No phone number entered'; } if ( trim($_POST['comments']) != '' ) { $comments = nl2br(stripslashes(strip_tags($_POST['comments']))); } else { $comments = 'No comments entered'; } ob_start(); ?> <html> <head> <style type="text/css"> .style3 {color: #000000} </style> </head> <body> <table width="550" border="1" cellspacing="2" cellpadding="2"> <tr bgcolor="#eeffee"> <td width="132"><span class="style3">Name</span></td> <td width="398"><?=$names;?></td> </tr> <tr bgcolor="#eeeeff"> <td>Email</td> <td><?=$emails;?></td> </tr> <tr bgcolor="#eeffee"> <td>Comments</td> <td><?=$comments;?></td> </tr> </table> </body> </html> <? $body = ob_get_contents(); ob_end_clean(); $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: '.$names.' <'.$emails.'>' . "\r\n"; if(mail($to, $subject, $body, $headers)) { echo $success_msg; } else { echo $failure_msg; } ?> Please can somebody help me find some PHP solace? Thanks-in-advance. Liam Hello, Here's little script that should get all email's subject via IMAP: Code: [Select] <?php $imap = imap_open("{imap.gmail.com:993/imap/ssl}", "user@gmail.com", "password"); $message_count = imap_num_msg($imap); for ($i = 1; $i <= $message_count; ++$i) { $header = imap_fetchheader($imap,$i,0); $first=strstr($header, "Subject: "); $second=strstr($header, "From: "); $fc=strlen($first); $sc=strlen($second); $le=$fc-$sc-9; $subject=substr($first,8,$le); echo $subject."\n"; } imap_close($imap); ?> Well it works just fine on inbox with few emails, else, if you have lots of mail with attachments, it will give 30 sec timeout warning. How the the would i bypass downloading the whole message+body, but just a header (subject). Thank's in advance! I've got a snippet of code that accesses an email account using the the imap function. In my class file I can use 'sender' => $headerArr->sender[0]->mailbox . "@" . $headerArr->sender[0]->host, and it gives me the senders email address. However when I try to use 'reply_to' => $headerArr->reply_to[0]->mailbox. "@" .$headers->reply_to[0]->host, it does not give me the reply to address (which can be different when receiving e-mails from groups, forums, etc). Any help would be appreciated. Jess I want to read an imap message with all the headers, and body, what would be the best way to do that? Howdy. I'm trying to get UTF8 Encoded text out of an email from an imap server. I can read the mail, but the encoding seems to be jacked up. Code: [Select] Hi I'm trying to get Japanese text out of an email from an imap server. PHP is somehow mangling it though. for ( $i = 1; $i <= $mails; $i++ ) { $struct = imap_fetchstructure( $imap, $i ); // $struct->encoding is 0 // The text is UTF8 $body1 = imap_utf8( imap_body( $imap, $i ) ); $body2 = imap_body( $imap, $i ); } In the above code, $body1 and $body2 are the same, and not any Japanese encoding. They're just garbage. Any ideas? My server is fastmail if that helps. I am terribly confused... I am trying to display the html body of a message pulled through imap. I thought that if I did this: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> in the html head, that everything would be pretty much figured out for me, but... When I look at the original message in gmail (prior to being pulled with imap), I get an ellipses(...), but once I display it in my browser, I get a black diamond question mark thingy... Help! I've tried all manners of conversion, but suspect I'm completely missing the boat here. Thanks Hello Everyone... I'm having an issue with my looping and parsing of email via imap... Here is my code: Code: [Select] <? require "connection.inc"; $mailbox = imap_open("{serverinformation}INBOX", "email@emailaddress.com", "thepassword"); if ($mailbox == false) { echo "<p>Error: Can't open mailbox!</p>"; echo imap_last_error(); } else { $num = imap_num_msg($mailbox); for ($i=0; $i < $num; $i++) { $content = imap_body($mailbox, $num); $siteid = stripos($content,"MOU"); $gwon = stripos($content, "MOSLXX-"); $TempSiteID = substr($content, $siteid, 7); $TempGraniteWorksOrderNumber = substr($content, $gwon, 13); echo '<p>Message #: '.$i.' - Site ID: '.$TempSiteID.' - Granite Works Order #: '.$TempGraniteWorksOrderNumber.'</p>'; } } imap_close($mailbox); ?> The result I get is unexpected... The output gives me each mail message number as expected, however, the information that I parsed for is always that of the last email message... Here's an example of the output: Message #: 0 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 1 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 2 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 3 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 4 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 5 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Message #: 6 - Site ID: MOU3963 - Granite Works Order #: MOSLXX-247119 Anybody tell me what I'm doing wrong here? Hey guys so Ive been messing with a number of .ini files (im sure this isnt a good thing) because Ive been trying to write a script that uploads files as big as 1GB and in doing so Ive edited the my suhosin.ini because in looking at my php_info() it said that all my pot max, get max, request etc were all undesirably low. Anyways I edited the file and then restarted apache but the changes that I made in suhosin.ini arent being displayed when i go to my php_info(). Cant anyone tell me if I missed a step and how do I get the server to recognize the changes as I believe it is these settings that are buggering up my upload script. -SB basically its a design flaw but im too far into it so im going to have to find a way to get this to work. Basically i have an anonymous board, anyone can post as long as they have cookies enabled. Cookies are key because they help bans and keeping track. The problem is the following. The Admin i.e me needs to have the same cookie no matter where i login from. This is to stop the admin being banned by mods. as that cookie key cant be banned. now any new visitor to the site gets assigned a cookie. So if the admin went to the site he would get a cookie. But when he loggs in i want it to get rid of the old cookie and replace it with his admin cookie so say for argument sake. he goes to the site and gets assigned Cookie1 in the login confirm i have setcookie(cook,cookie1, time() -3600); setcookie(cook,$admincook,time() + 60 *24); after i log in as admin and check the cookie $_COOKIE[cook]; it still displays as cookie1 But for some strange reason when i post a thread the value of $admincook gets stored in the database. However this is only for posting a thread and not for any of the other options, such as asking a question etc. the method of getting the cookie value when posting a thread is the EXACT same... i really don't know why it wont work. my project is over several files and over 15 thousand lines of code. so im not sure what parts i should give you. my main problem is that expiring the cookie and resetting it again straight away doesn't seem to work. I have the " or the ' all wrong. Can someone tell me how to do the quoation marks correctly so I dont get a syntax error: as can be seen, the date 10/5/14 is not a variable but I want to convert it to a format that can go into a DATE field. Code: [Select] $query = "update table set expir_date = date("Y-m-d", 10/5/14) where id = '$id' "; OK, I have been having issues with this query for some time now, I (finaly) have the query working absoloutly fine when run directly in the database, however, when I try and run it through a PHP page I just get a completly empty result set back. I have done a print_r($row) and there is nothing, absoloutly nothing. I have ran the SQL that comes from print_r($sql) in the database and it's completly fine as well. I was getting an error previously because I had missed the "IS" out before NOT NULL for the PadPrefix, so it is parsing the SQL to some level (I now have no errors showing either). I am wondering if there is something I am missing that is needed for when the SQL is creating cached tables and/or using a counter? Here's the code, any and all suggestions welcome, Cheers <?php @SESSION_START(); require_once 'connect.php'; $bp = $_SESSION['bp']; if ($_SESSION['id'] < 99){ $tbl_top = '<table><tr><th>SheetID</th></tr>'; $WHERE = " = '$bp'"; } else{ $tbl_top = '<table><tr><th>SheetID</th><th>Prefix</th></tr>'; $WHERE = "IS NOT NULL"; } $sql = "DECLARE @badSheets TABLE (ID int, batchMax int) ". "DECLARE @list TABLE (maxsheet int, lastsheet int) ". "DECLARE @sheet int ". "DECLARE @batch int ". "DECLARE @endBatch int ". "declare @batchIndex int ". "INSERT INTO @list (maxsheet, lastsheet) ". "SELECT sheetList.maxsheet, padlist.lastSheet ". " FROM( ". " SELECT sheet.padID, MAX(sheet.SheetID) as maxsheet FROM jim.dbo.sheet as sheet ". " INNER JOIN jim.dbo.files as files on sheet.sheetID = files.sheetid ". " where sheet.sheetid > 100000 ". " group by sheet.padID) ". "AS sheetList ". "INNER JOIN( ". "SELECT pads.padID, pads.padID+(count(pads.padID)-1) as lastSheet ". "From jim.dbo.sheet as pads ". "Group By pads.PadID) ". "AS padList ". "ON (sheetList.padID = padList.padID) ". "WHERE maxsheet != lastSheet ". "DECLARE bad_batch CURSOR FOR ". "SELECT DISTINCT maxsheet FROM @list ORDER BY MaxSheet ". "OPEN bad_batch ". "FETCH NEXT FROM bad_batch ". "INTO @batchIndex ". "WHILE @@FETCH_STATUS = 0 ". "BEGIN ". "SELECT @batch = lastSheet FROM @List where maxsheet= @batchIndex ". "SELECT @sheet = maxSheet FROM @List where maxsheet= @batchIndex ". "WHILE (@sheet <= @batch) ". "BEGIN ". "INSERT INTO @badsheets(ID, batchMax) VALUES (@sheet, @batch) ". "SET @sheet = (@sheet + 1) ". "END ". "Fetch Next FROM bad_batch INTO @batchIndex ". "END ". "close bad_batch ". "deallocate bad_batch ". "SELECT sheetID, padprefix ". "FROM JIM.dbo.sheet AS sheet LEFT OUTER JOIN jim.dbo.pad AS pads ". "ON sheet.padID = pads.padID ". "WHERE ( ". "(padprefix $WHERE) ". "AND (sheet.sheetID > 100000) ". "AND (sheet.SheetID NOT IN (SELECT SheetID FROM jim.dbo.files)) ". "AND (sheet.sheetID NOT IN (SELECT ID FROM @badSheets)) ". ")"; $result = sqlsrv_query($sqlConnect, $sql) or die("error running : $sql <br><br>".print_r( sqlsrv_errors(), true)); echo "<table border=\"1\">"; echo $tbl_top; WHILE ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){ if ($_SESSION['id'] < 99){ $tbl_content = "<tr><td>{$row['sheetID']}</td></tr>"; echo $tbl_content; } else{ $tbl_content = "<tr><td>{$row['sheetID']}</td><td>{$row['padPrefix']}</td></tr>"; echo $tbl_content; } echo $tbl_content; } echo "</table>"; ?> I am having a nightmare with an explode and cant get it to work. I am posting a string using JQuery to a PHP form which needs to explode the string into an indexed array to be inserted into a database. This is what the string looks like "importance%5B101%5D=50&importance%5B100%5D=50&importance%5B99%5D=50&importance%5B98%5D=50" The original array has been serialised into the above string. The arrayname is importance. The array's index (inside the square brackets) is referenced from an ID from the page. The square brackets have been replaced by '%5B' and '%5D' and surround the array index by the JQuery. The value for each of these array items is shown as =50. So its basically the same as a GET when we have name=value&name1=value1etc') How would i explode the string above to remove the '%5B' and '%5D' to make the '[' and ']' reappear and then from then it can be read as a GET post? like 'name=value&name1=value1etc'. Using the new array of that index ready to be inserted into a MySQL database. Im going mad trying to solve this!!! The junk I've found on phpclasses is well junk and not to mention really old. I started writing my own, but I frankly don't like the plumbing involved. Anyone have a great IMAP class? Something that just does the work for you? How would I go about creating a new user email account that can be accessed via my cpanel mail scripts (RoundCube, SquirrelMail, etc.), in PHP. I seem to be having a difficult time saving the attachments to a folder on the server, all the examples I see show it to the browser, what I need to do is copy the attachment to a separate folder and do some processing on it. So far everything I get, then ftp to my desktop appears corrupt. It works I just can't seem to unzip the zipped attachments, any ideas? My Code: (Not mine, I used examples from the web and put it into a function) function get_attachments($message_number){ global $connection; $structure = imap_fetchstructure($connection, $message_number); $attachments = array(); if(isset($structure->parts) && count($structure->parts)) { for($i = 0; $i < count($structure->parts); $i++) { $attachments[$i] = array( 'is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '' ); if($structure->parts[$i]->ifdparameters) { foreach($structure->parts[$i]->dparameters as $object) { if(strtolower($object->attribute) == 'filename') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['filename'] = $object->value; } } } if($structure->parts[$i]->ifparameters) { foreach($structure->parts[$i]->parameters as $object) { if(strtolower($object->attribute) == 'name') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['name'] = $object->value; } } } if($attachments[$i]['is_attachment']) { $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1); if($structure->parts[$i]->encoding == 3) { // 3 = BASE64 $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']); } elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']); } } } } return $attachments; } Calling Code: $a = get_attachments(6); $fp = fopen($a[1]['filename'], 'w'); fwrite($fp, $a); fclose($fp); |