Tag: chris cook

Mac OS X Server Rejects Mail with No Subject Line

Is Mac OS X Server 10.6 (Snow Leopard) rejecting your e-mail messages which lack a subject line? Mine was, and so does the default setting on Snow Leopard Server.

Here’s a quick fix:

1) First, stop the mail service.

2 Now, you’ll want to edit the header_checks file that’s utilized by postfix.

Select Code
sudo nano /etc/postfix/custom_header_checks

3) Next, you’ll see a line which says:

Select Code
/^subject: *$/ REJECT empty subject header

Comment out this line by adding a pound sign (#) at the beginning of the line.

4) Once you comment out this line, it should appear as:

Select Code
#/^subject: *$/ REJECT empty subject header

5) If you’re using nano or pico to edit the file, click Control+O to write the file. (Save and Exit).

6) Now, restart the Mail service and the server will no longer reject email with no subject line.


Let me know if this solution works for you! Enjoy!

PHP: Session Timeouts

Defining session timeout thresholds for PHP scripts is a security “must”. I recommend that you consider the purpose of your script before applying a session timeout function. For instance, if your site has a secure login and security requirements, it’s important to include the timeout function. However, it’s often an inconvenience to end-users.

Use the code below to create a function which can be used to implement a secure timeout threshold.

Select Code
/* Set timeout threshold to 10 minutes (600 seconds) */
$timeout = 600;
$_SESSION["expires_by"] = time() + $timeout;

Clear Tower Consulting

Looking for a company to help you manage your web development project? Need a website? Are you a looking for eLearning or online training?

Clear Tower Consulting is a progressive, innovative firm which provides custom consulting solutions.

Take a look at their services below (Excerpt from ClearTowerConsulting.com)

eCommerce Solutions

If you’re company sells products and services, you need an eCommerce option on your web presence. Clear Tower Consulting has helped customers create shopping carts, customer management tools, and purchasing scripts since our establishment in 2003. We can integrate an existing 3rd party shopping cart with your website or we can develop a custom solution for your company. In addition, we’ll help you understand how merchant service providers operate and help you integrate your chosen provider with your web presence.

We’re profficient in many, many 3rd party eCommerce solutions including:
– osCommerce
– X-Cart
– PHP Web Commerce
– ClientExec
– ModernBill (Parallels)

Web Development and Management

Websites are a critical element of every company’s business. We specialize in these services:
– Website design (Web 2.0 technologies – CSS, XHTML)
– Web Hosting
– Web Application Development (PHP, MySQL, ASP, Access, MSSQL, Oracle)
– Web Analytics
– Web Surveys
– Web Content Management

Process Streamlining

We’ve often heard the phrase, “a business is only as strong as its weakest link.” We agree, but we’re here to help. We specialize in facilitating group meetings, identifying process inefficincies, change management consulting, human resources strategies, project management streamlining, and much more. Ask one of our sales advisors about how we can help your business.

eLearning Development

We understand that today’s business environment requires companies (small and large) to re-think training and employee development. eLearning makes sense — it’s cost effective and allows the latest learning techniques.

Our custom eLearning courses feature:
– Latest ISD technologies
– Rich text
– Rich media (videos, pictures, animations)
– Quizzes, tests, and data capture
– Interactive elements (drag and drop technology, memory clicks, etc.)
– SCORM or AICC compliance
– Integration with Learning Management Systems (LMS)

Use PHP to Backup your MySQL Database

If you don’t backup your databases regularly, shame on you. You should!

The code below will allow you to generate a backup as often as you’d like. It only makes sense to run this via a CRON job. This is pretty easy to do and you can set the frequency as you wish.

The backup files will be stored in the same directory as this script.

Please leave feedback and let me know if this works for you!

Here’s the PHP code:

Select Code

// Backup the entire database or just a specific table.  
function backup_tables($host,$user,$pass,$name,$tables = '*')
    $link = mysql_connect($host,$user,$pass);
    //get all of the tables
    if($tables == '*')
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
            $tables[] = $row[0];
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    //This method is completed for each table
    foreach($tables as $table)
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);
        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        for ($i = 0; $i < $num_fields; $i++) 
            while($row = mysql_fetch_row($result))
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) 
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                $return.= ");\n";
    //Now, we'll save the file
    $handle = fopen('backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');

Return Random Record via MySQL

There are many practical and frequently used methods requiring a random record to be called. For instance, when you see “featured profiles” or random customer comments on a website, they are most likely using a function to call a random record.

In addition, this function can allow you to display data in a random order.

Here’s how it works:

Select Code
SELECT field_1, field_2, field_3, field_4
FROM table_name
WHERE parameter = 1

It’s that simple. Please post your feedback!

PHP: Preventing typical XSS attacks

XSS attacks plague beginner programmers and are a significant vulnerability for commercial web hosts & website operators.  XSS means “cross-site scripting“.  These exploits work on the client side. Often, hackers put some type of JavaScript in content that users submit that allow them to steal the data from a cookie.  XSS attacks are pretty difficult to prevent.  Hackers have been successful with XSS attacks on most, if not all, of the biggest sites on the net.

To help prevent XSS attacks, it’s best to restrict and filter the data that you get from a user through your site.  Have you ever wondered why popular bulletin boards, such as vB or phpBB, use custom tag formats like [url] or [b]?  They’re trying to prevent attacks.

This tutorial is a very basic example of a way to help prevent XSS attacks.  There are other methods — and more comprehensive methods out there.

okHTML function:
Let’s start with a simple function that converts any HTML code (or character) into literals.

Select Code
// ChrisCook.me
function ok_HTML($string, $length = null)
// get rid of the extra space
$string = trim($string);

// avoid unicode codec issues
$string = utf8_decode($string);

// convert HTML characters
$string = htmlentities($string, ENT_NOQUOTES);
$string = str_replace("#", "#", $string);
$string = str_replace("%", "%", $string);

$length = intval($length);
if($length &gt; 0) {
$string = substr($string, 0, $length);
return $string;

The Explanation:
One  of the  most important components of that function is the htmlentities() funcion call that converts &, <, and > into &amp;, &lt;, and &gt;. This helps resolve the simple hacks.  We’re not done yet, though.  All XSS attacks aren’t basic.  Hackers know programmers have implemented these attacks to they tend to encode their hacks and malicious scripts in UTF-8 or hexadecimal instead of using the normal ASCII text.

To help prevent this, transform_HTML() takes the additional step of converting # and % signs into the correct entities.

In my readings on preventing XSS attacks, many experts recommend that you limit the  string length in case some goober tries to overload your string with a very, very long input in hopes that they’ll crash the server or your database. You can edit the $length parameter to help control this.

That’s it for today,

Disclaimer: As always, I want to add my handy-dandy disclaimer.  Please understand that this tutorial is intended to demonstrate a specific function.  Please review the code and add appropriate security measures before using it in a production environment.

PHP/AJAX: Call PHP function by clicking a link

This tutorial demonstrates how to execute an external PHP function by clicking a simple link within HTML. The method uses AJAX so that the page doesn’t refresh and doesn’t require a form submission.

1) Paste the following code into a .js file. For demonstration purposes, we have named it “ajax_link.js”.

Select Code
* ajax_link.js
* chriscook.me

function loadurl(dest) {

try {
// Moz supports XMLHttpRequest. IE uses ActiveX.
// browser detction is bad. object detection works for any browser
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// browser doesn't support ajax. handle however you want

// the xmlhttp object triggers an event everytime the status changes
// triggered() function handles the events
xmlhttp.onreadystatechange = triggered;

// open takes in the HTTP method and url.
xmlhttp.open("GET", dest);

// send the request. if this is a POST request we would have
// sent post variables: send("name=aleem gender=male)
// Moz is fine with just send(); but
// IE expects a value here, hence we do send(null);

function triggered() {
if ((xmlhttp.readyState == 4) (xmlhttp.status == 200)) {

document.getElementById("ajaxlink").innerHTML = xmlhttp.responseText;

2) Next, add the following code in the section of your HTML file.

Select Code
<script src="ajax_link.js" type="text/javascript"></script>

3) The following code should be placed in the HTML body of a PHP file.

Select Code
<div id="ajaxlink" onclick="loadurl('ajax_function.php')">Click Here</div>

Replace ‘ajax_function.php’ with the correct file you want to execute. For instance, if you want your users to “click here” in order to send themselves a copy of their monthly invoice, you’d code the mailer function in ‘ajax_function.php’.

4) That’s it. Ensure that you keep the <div> id as “ajaxlink”. Once you click the link, it will disappear (until the page is refreshed).

Feedback: I’d love to hear how you’ve used this tool. Please feel free to post a comment on my blog.

Disclaimer: This tutorial is provided to demonstrate how to perform the function. Please ensure that you review the code and add security measures before using this in a production environment.

“Lock Desktop” – New Mac OS X App

I’ve uploaded one of my first applications for a Mac. It’s extremely easy to use. The tool allows you to lock your desktop when you’re away from the computer and requires a password when you get back.  This is something you can run on demand, instead of waiting for a screen-saver, or logging off.  Lock Desktop 1.0 even keeps your programs running in the back.  Read more →