Category: Web Development

FreelanceSuite – Version 2.0

We’re extremely excited to announce the release of Version 2.0 for FreelanceSuite.  FreelanceSuite is a clean, stylish web application to manage all of your customers, projects, and billing. Simple, yet powerful.

Version 2 is a foundational release for FreelanceSuite. This update provides key features, enhances the application’s framework, and creates APIs for future integration. All users should upgrade to Version 2.

  • New Payment Gateway: Stripe
  • Real-Time Task Timer
  • Web-based Email Templation Configuration
  • Leads Feature (External input, plus import features)
  • reCAPTCHA integration for Lead Input Feature
  • Calendar Feature
  • Search Tool (Clients, Projects, Support Tickets)
  • Revenue Report (Chart Framework)
  • Clean Date Selection Tool
  • Staff can now Reset & Email Client Passwords
  • Emails sent to clients upon account creation
  • Configurable Currency Symbol integrated
  • Visual Enhancements to Invoice (HTML & PDF)
  • Quick “Add” Features
  • Various Bug Fixes
  • More

Visit the product website at http://freelancesuite.com

Detecting iPad Visitors: PHP, Javascript, and .htaccess

It’s been a while since I posted a tutorial on how to detect iPhone visitors on your site.  Since then, there are many more iDevices out on the market.

In some instances, it makes sense to identify and redirect iPad users to provide a unique viewing experience.

JAVASCRIPT:

The following code can help you detect if the user is using an iPad:

Select Code
// Check for iPad
var isiPad = navigator.userAgent.match(/iPad/i) != null;

You can (and should) also do this check via PHP.

PHP:

Select Code
$isiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');

.htaccess

Lastly, once you know your web visitor is viewing the page from an iPad, you can use a simple .htaccess file to redirect the visitor to your desired location.

Select Code
RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://YourDomain.com/iPad [R=301]

Of course, you’ll want to replace “YourDomain.com/iPad” with the intended URL.

 

I realize that I didn’t outline each specific step — just the essential code.  If you have any questions about these functions, just comment below.

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) */
@session_start();
$timeout = 600;
$_SESSION["expires_by"] = time() + $timeout;

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_tables('localhost','username','password','blog');


// Backup the entire database or just a specific table.  
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
    
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);
    
    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $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";
            }
        }
        $return.="\n\n\n";
    }
    
    //Now, we'll save the file
    $handle = fopen('backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

Return Random Record via MySQL

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
ORDER BY RAND()
LIMIT 1

It’s that simple. Please post your feedback!

Detecting iPhone visitors with PHP

More and more internet traffic is generated by the iPhone and iPod touch.

The PHP snippet below shows you how to automatically redirect your users to a page which is optimized for the iPhone Safari browser.

Select Code
if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
{
// Change your URL below
header('Location: http://www.domain.com/iphone');
exit();
}

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,
Chris

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);
xmlhttp.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.