Sep 14

Although I expect this article to cause a few ruffled feathers amongst the programming community (since most of them are against HTML email), there are times when the client will ask for it anyway, so you have to know how to do it. We had run into difficulty finding a straight answer on this topic, and many of the articles we had found on it gave us bizarre results in the HTML mail… so once we figured out what worked, we decided to post it.

We have tested this on several different email clients (including but not limited to: Hotmail, Yahoo, AOL, Outlook Express, Outlook, and various text-only email clients such as Mutt).

In the email clients that render HTML (ie – not text-only) the only real difference we found was that Outlook (regular Outlook, not Express) showed the background color from the BODY tags, but not the background image. Yahoo and Hotmail stripped out the background color and images, but if your HTML mail is designed with this in mind, you can easily design around that.

Make sure the email will still look nice if the background color and/or images are stripped out of it.

Obviously, you would change the email addresses and messages to fit your own needs.

 <?php
/* ---------------------------------------------- */
/* ------------ BEGIN PHP SNIPPET ----------------*/
/* ---------------------------------------------- */

$headers .= "FROM: jayar@bauson.com\n";
$headers .= "Reply-To: jayar@bauson.com\n";

// This is the important part!
// This content type identifies the content of the message.
// The boundary delimits the plain text and html sections.
// The value of the boundary can be anything – you can even
// use the same one we used here
$headers .= "Content-Type: multipart/alternative; boundary=\"—-=_NextPart_000_002C_01BFABBF.4A7D6BA0\"\n\n";

// Now begin your message, starting with the delimiter we specified in the boundary
// Notice that two extra dashes (–) are added to the delimiters when
// They are actually being used.
$message = '——=_NextPart_000_002C_01BFABBF.4A7D6BA0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Your plaintext email content here.';

// Now begin your HTML message, starting with the delimiter
// Also notice that we add another content-type line which
// lets the mail client know to render it in HTML
$message .= '——=_NextPart_000_002C_01BFABBF.4A7D6BA0
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

Your HTML email here

——=_NextPart_000_002C_01BFABBF.4A7D6BA0–';

// Now send the mail.
// The additional header, "-f jayar@bauson.com" is
// only required by certain server configurations.
mail($v, "My Multipart Subject", $message ,$headers,"-f jayar@bauson.com");
?>
Sep 11

A friend ask me to send some of my previous work regarding email parser, I don’t have time to go home and search it to my backup drive. This friend is really desperate to finish his task and so by browsing web, I found this really good mailbox class.

Download: receivemail.class

Usage:

<?

include("receivemail.class.php");

$obj= new receiveMail('jayar+bauson.com','mypassword', 'jayar@bauson.com','mail.bauson.com','pop3','110',false);

$obj->connect();         

$tot=$obj->getTotalMails(); 

echo "Total Mails:: $tot<br>";

for($i=$tot;$i>0;$i--)
{
	$head=$obj->getHeaders($i);
	echo "Subjects :: ".$head['subject']."<br>";
	echo "TO :: ".$head['to']."<br>";
	echo "To Other :: ".$head['toOth']."<br>";
	echo "ToName Other :: ".$head['toNameOth']."<br>";
	echo "From :: ".$head['from']."<br>";
	echo "FromName :: ".$head['fromName']."<br>";
	echo "<br><br>";
	echo "<br>***************************************** **************************************************<BR>";
	echo $obj->getBody($i);  

	$str=$obj->GetAttach($i,"./");
	$ar=explode(",",$str);
	foreach($ar as $key=>$value)
		echo ($value=="")?"":"Atteched File :: ".$value."<br>";
	echo "<br>--------------------------------------------------- ---------------------------------------<BR>";

	//$obj->deleteMails($i); // Delete Mail from Mail box
}
$obj->close_mailbox();  

?>
Tagged with:
Sep 09

With a basic knowledge of cURL, you will probably start thinking to design your own class. Check this class to have an idea of what should we have for a basic cURL object, like requesting-browser-like, posting values and crawling pages.

class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.google.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

         $this->createCurl($this->_url);
     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         //curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
Tagged with:
Sep 08

I just found out that my free link checking tool is being blocked by some websites. My guess is that it’s because it’s sending a blocked User-Agent string. I’m going to tweak it to say it’s FireFox or something. Here’s how to do that with cURL and PHP:

// spoofing FireFox 2.0
$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";

$ch = curl_init();

// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
// set the rest of your cURL options here
Tagged with:
Aug 27

Wondering how to check the content of an FCKEditor? You will love this simple code!!!

<?php
include("fckeditor/fckeditor.php") ;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
	<head>
		<title>FCKeditor - Sample</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="robots" content="noindex, nofollow">
		<script>

function getRTEText(fckinst){
  var oEditorHTML = FCKeditorAPI.GetInstance(fckinst).GetHTML();
  alert(oEditorHTML);
}
</script>
	</head>
	<body>

		<form action="request.php" method="post">

<?php
	$oFCKeditor = new FCKeditor('content');
	$oFCKeditor->BasePath = "fckeditor/";
	$oFCKeditor->Value = $content['message'];
	oFCKeditor->Config['UserFilesPath'];
	$oFCKeditor->Height = "440";
	$oFCKeditor->Create();
?>

			<br>
			<input type="button" onclick="javaScript:getRTEText('content');" value="check">
			<input type="submit" value="Submit">
		</form>
	</body>
</html>
Tagged with:
Aug 27

I found mysql tuning is a pain. This script is a good tool to adjust your mysql variables. It evaluates the following variables:

slow query count
long_query_time
query_cache_size
% query cache actually used
max_connections
thread_cache
key_buffer_size
ratio of sort_merge operations to sorts (sort_buffer_size)
number of full joins
ratio of disk tmp tables vrs in memory tmp tables (tmp_table_size)
table_cache
ratio of table locks immediate to table locks waited
ratio of table scans (read_buffer_size)

MySQL Tuner

To use the script add your user name and password to a [client] group in your ~/.my.cnf file

Tagged with:
Aug 20

1. Tab
The most handy shortcut and time saver for the linux command line. This actually makes navigating directories faster in the CLI than the traditional GUI browser. Simply start typing the command, filename, or directory and hit tab. Bash will automatically complete what you are typing. It even works at the lilo prompt and in some X applications.

2. Ctrl + c
Stop that program dead in its tracks. This is the command line version of end task.

3. Ctrl + z
Send the current process to background. This is useful if you have a program running, and you need the terminal for awhile but don’t want to exit the program completely.
Type the command fg to get the process back.

4. Ctrl + d
Log out from the current terminal. If you use this in an X terminal emulator such as xterm it will usually close it after logging out.

5. Ctrl + u
Erase the current line. I use this one all the time when I type the wrong command in.

6. Ctrl + Alt + F1, (F1-F6)
Switch to the first virtual terminal. In Linux, you can have several virtual terminals at the same time. The default is 6. (Ctrl + Alt + F7 to get back to X)

7. Ctrl + l (lowercase L)
Clear the terminal.

8. Ctrl + Alt + Backspace
Kill the X server. Use this if X crashes and you can’t exit it normally. If you’ve configured GDM to start automatically at bootup, this restarts the server and throws you back to the graphical login screen.

9. Ctrl + a
Move the cursor to the beginning of the current line. Usefull for those times you navigated all the way through 20 directories and forgot to add ‘cp’ to the beginning. Use this instead of the arrow keys.

10. Ctrl + e
Last but not least get that cursor back to the end of the line.

Tagged with:
Aug 19

Some developers are linking downloadable files directly on their pages and the reason why we get stucked when accidentally clicked a “.pdf” or large “.txt” files. The function below will allow the user to force download the file instead of opening it in the browser.

<?
function force_download($file)
{
    $dir      = "../log/exports/";
    if ((isset($file))&&(file_exists($dir.$file))) {
       header("Content-type: application/force-download");
       header('Content-Disposition: inline; filename="' . $dir.$file . '"');
       header("Content-Transfer-Encoding: Binary");
       header("Content-length: ".filesize($dir.$file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
       readfile("$dir$file");
    } else {
       echo "No file selected";
    } //end if

}//end function
?>
Tagged with:
Aug 18

This piece of code will help you strip links from a string.

<?php
function strip_urls($text, $repPat)
{
    if(!$repPat){
        $repPat = &quot;text [url]&quot;;
    }
    $aimpstr = 'STRIP_URL_IN_PHP';
    //change $aimpstr to anything you want.
    $impstr = md5($aimpstr);
    $text = str_replace('&lt;/a&gt;', '&lt;/a&gt;' . $impstr, $text);
    $text = explode($impstr, $text);
    $n = 0;
    $texta = array();
    $repPat = str_ireplace(array('text', 'url'), array('\\4', '\\2'), $repPat);
    foreach ($text as $text) {
        $texta[$n] = ereg_replace(&quot;&lt;a(.*)href=\&quot;(.*)\&quot;(.*)&gt;(.*)&lt;/a&gt;&quot;, $repPat, $text);
        $n++;
    }
    $textb = implode(&quot;&lt;/a&gt;&quot;, $texta);
    return $textb;
}

//EXAMPLES:
$string_of_text = '&lt;a href=&quot;http://blog.bauson.com/&quot;&gt;Jay-ar&lt;/a&gt; Bauson. &lt;a href=&quot;http://www.bosjef.com/&quot;&gt;Bosjef&lt;/a&gt; TEXT!';
echo strip_urls($string_of_text, &quot;text&quot;);
echo strip_urls($string_of_text, &quot;url&quot;);
echo strip_urls($string_of_text, &quot;text [url]&quot;);
echo strip_urls($string_of_text, NULL);
?>
Tagged with:
Aug 14

Have you tried using FCKEditor to allow your user to upload files? Its one of the best WYSIWYG(What You See Is What You Get), but how about considering FCKEditor to create their own gallery? User will have their own directory. Ahem!!!!

In your FCKeditor directory find the config.php for php connector:
fckeditor/editor/filemanager/browser/default/connectors/php/config.php
Add this code in the topmost of the file:

<?
php session_start();

then search for this code:

$Config['UserFilesPath'] = '';

and replace it with

$Config['UserFilesPath'] = '/userfiles/'.$_SESSION['member_id'].'/';

Note that $_SESSION['member_id'] can be changed to whatever youd like to be the identifier of your users. Be sure to authenticate your user and set their ID’s in the session variable.

**Some developers do have hard time configuring the filebrowser, they can upload but cannot browse what are in the server. To fix this issue, open the frmresourcelist.html
fckeditor/editor/filemanager/browser/default/frmresourcelist.html

Search for:

oListManager.GetFileRowHtml = function( fileName, fileUrl, fileSize )
{
	// Build the link to view the folder.
	var sLink = '<a href="#" onclick="OpenFolder(\'' + ProtectPath( folderPath ) + '\');return false;">' ;

and replace it to:

oListManager.GetFileRowHtml = function( fileName, fileUrl, fileSize )
{
	// Build the link to view the folder.
	var sLink = '<a href="#" onclick="OpenFile(\'http://YOURDOMAIN' + fileUrl.replace( /'/g, '\\\'') + '\');return false;">' ;
Tagged with:
preload preload preload
Bless CV