Tag: tutorial

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!

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.