How to solve header - error -PHP

Hi Friends
While running my application i got this error. How to solve this error.
Warning: Cannot modify header information - headers already sent by somefile.php (output started at somefile.php:###) in somefile.php on line ###
This Warning is shown by PHP when you use the header function to output headers or use the setcookie function to set cookies after any echo or content which is not inside PHP tag.
echo "Hello World";
header("Location: /redirect.php");
Hello World !!! 
<?php header("Location: /redirect.php");?>
Both should throw this warning.
You can disable this warning by turning the error_reporting to OFF using error_reporting(0);, which is pretty much the not way of doing things. In HTTP Headers are sent before the actual content so if you are going to use header function after outputting the contents, it is likely to not work.

How do I solve this Warning Cannont Modify Header Information ?

In order to solve this issue you have to make sure you dont echo or print any output before using header or setcookie function. Make sure the control passes through these functions and then to the output part.

I am sure I dont output anything before calling header or setcookie

Just see all your files for white spaces or empty new lines. For example if you include a file before using the header or setcookie functions, make sure the file does not have a closing php tag (?>) at the end of the file. This is recommended by PHP so that stray white space or new line characters at the end of this included file gets outputted.
//<-- A new line on top ! Oops.
<?php header("Location: /redirect.php");?>
// <-- A blank line at the end? 

I still want to output first and then use header function

In that case you can use output buffering functions to buffer your output automatically before senting any output and the output is sent as a chunk at the end. The following code snippet shows this :

<?php
ob_start(); ?>
Hello World !!! 
<?php 
setcookie("name","value",100); 
?>
Again !!!
<?php
ob_end_flush();
?>

But my code is already done and I dont want to add ob_* functions to it !

You can turn on buffering in PHP on by default using php.ini.
Look for output_buffering , The following shows the mentioned part of the php.ini file.
Set the value as On and restart Apache server.
; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit.  You can enable output buffering during runtime by calling the output
; buffering functions.  You can also enable output buffering for all files by
; setting this directive to On.  If you wish to limit the size of the buffer
; to a certain size - you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = On
Hope this solves all your annoying
Warning Cannot Modift Header Informatio

Backup all MySQL databases automagicly with the PHP admin script

Backup all MySQL databases automagicly with the PHP admin script

Server administration software like Cpanel, Plesl, Webmin etc have already their backup solutions. But they are runned mostly once a week or max a day because of performance reasons. Let say we just want to backup all of our mysql-databases every 2 hours.

#!/usr/bin/php
<?php
// use this if your php.ini does not allow shell etc #!/usr/bin/php -n

$mysql_root_pwd = "YOUR-MYSQL-ROOT-PASSWORD";

function formattime() { return date("Y-m-d H:i:s"); }

echo "Starttime: ". formattime();

mysql_connect("localhost","root","$mysql_root_pwd");
$r = mysql_query("show databases");

while( $arr = mysql_fetch_array($r) ){
 $db = $arr[0];
 echo "\n\nExporting $db\n" . formattime() . "\n";
  
 echo shell_exec("/usr/bin/mysqldump  -u root --password='$mysql_root_pwd' $db > /backup/mysql/".$db.".sql");
}

echo "\n\nEndtime: ". formattime() . "\n\n";

echo mysql_error();
mysql_close();

Backlink Checker


Backlink Checker

 Edit these variables and replace with your own (see source code comments for description):
$url - your website URL
$email - your email
$fromEmail - your email
$subject - subject of report
$body - No need to really modify
$backlinkSources - The sources that have your site URL

 <?php
/* Your Website URL. Leave out the http://
 * and only include the base domain
 */
$url 'free-php-script.blogspot.com';
/*
 * Your email, the place you want the report
 * to arrive at
 */
$email   'your@email.com';
/*
 * Email the report is being sent from
 */
$fromEmail 'from@email.com';
/*
 * Subject of the report email when a backlink
 * is not found on a source
 */
$subject "Backlink not found on Source: $url";
/*
 * Body header text
 */ 
$body "Hai, a source that was suppose to contain a backlink to your website no longer does. Please see below.\r\n\r\n";

/*
 * Backlink Sources
 */
$backlinkSources = array ('http://google.com/',
                          
'http://yahoo.com/',
                          
'http://free-php-script.blogspot.com'
                         
);
/*
 * This is a place holder variable which will
 * be used to hold the true/false variables
 * for report generation
 */
$reportArray = array();
/*
 * Bool value used to determine if any false
 * values are found
 */
$falseFound false;
/*
 * Begin checking the backlinks for the target
 * URL
 */
foreach ($backlinkSources as $source) {
    
// Get the HTML source Code
    
$html file_get_contents $source );

    
// Extract all Links
    
$links ExtractHrefLinks($html);
  
    
// Determine if the links contain your site URL
    
if (CheckForTargetUrl($links$url) === false) {
        
$falseFound true;
        
$reportArray[$source] = 0;
    } else {
        
$reportArray[$source] = 1;
    }
}
/*
 * Dump our results for browser output
 */
print_r($reportArray);
/*
 * If a backlink is not found on a source,
 * Generate an email.
 */
if ($falseFound === true) {
    
GenerateReportEmail($email$fromEmail$subject$body$url$reportArray);
}

/**
 * Send the report email when a source is found that does
 * not have a backlink
 *
 * @var email string
 * @var fromEmail string
 * @var subject string
 * @var body string
 * @var url string
 * @var reportArray array
 *
 * @return null
 */
function GenerateReportEmail($email$fromEmail$subject$body$url$reportArray) {
    
// Create an email header
    
$header "From: " $fromEmail "\r\n"//optional headerfields
  
    /*
     * Loop through the results to form the
     * report
     */
    
foreach ($reportArray as $key => $report) {
        if (
$report == false) {
            
$body .= "Backlink to $url not found on: $key\n";
        }
    }
  
    
// Send the email
    
mail($email$subject$body$header);
}
/**
 * Determine if the array of links contain the
 * target URL (your URL)
 *
 * @var links array of source URLs
 * @var target URL of target website (your website)
 * @return bool
 */
function CheckForTargetUrl($links$target) {  
    
/*
     * Loop through all of the links in the array. Use
     * strpos to test if string is found in link text
     */
    
foreach ($links as $link) {
        if (
strpos($link$target) !== false) {
            return 
true;
        }
    }

    
// Return
    
return false;
}
                          
/**
 * Extract all href Links from an HTML
 * document/text
 *
 * @vars html source code of site
 * @return array
 */
function ExtractHrefLinks($html) {
    
//Create a new DOM document
    
$dom = new DOMDocument;
    
$linkUrls = array();
   
    
/*
     * Parse the HTML. The @ is used to suppress any parsing errors
     * that will be thrown if the $html string isn't valid XHTML.
     */
    
@$dom->loadHTML($html);
   
    
/*
     * Get all links. You could also use any other tag name here,
     * like 'img' or 'table', to extract other tags.
     */
    
$links $dom->getElementsByTagName('a');
   
    
//Iterate over the extracted links and display their URLs
    
foreach ($links as $link){
        
//Extract and show the "href" attribute.
        
$linkUrls[] = $link->getAttribute('href');
    }
  
    return 
$linkUrls;
}?>

AD text

  AD text
<?
if (!isset($title)){ $title = "<b>Sponsored Links:</b>";} // set to "" to exclude title.
if (!isset($adsfile)){ $adsfile = "ads1.txt";} // file containing one hyperlink per line
if (!isset($maxads)) { $maxads = 4; } //max ads to show
if (!isset($spacing)){ $spacing = 3; } //spacing count between ads
if (!isset($spacer)) { $spacer = "&nbsp;"; }  //set to <br> for a vertical list, to &nbsp; for a space
if (!isset($titlespacing)){ $titlespacing = 2; } //spacing count between title and ads


//==============================SCRIPT STARTS HERE
if (file_exists($adsfile))
{
    $ads = array_filter(file($adsfile)); // get the list from the file
   
    if (count($ads) > 0 && $maxads > 0) //only go on if the ads file isn't empty, and maxads has is > 0
    {
        if (count($ads) > $maxads) // there are plent of ads to choose from, so get a random selection
        {
           
            if ($title != "")
            {
                echo "$title" . str_repeat($spacer,$titlespacing);
            }
           
            $selectedkeys = array_rand($ads,$maxads); //get a mixed random list of keys from the ads   
           
            if ($maxads > 1)
            {           
                //print each link in the shuffled order
                foreach ($selectedkeys as $key)
                {
                    if ($ads[$key] != "")
                    {
                        print "$ads[$key]" . str_repeat($spacer,$spacing);
                    }
                }
            }
            else // maxads is "1" just get the one link
            {
                print "$ads[$selectedkeys]" . str_repeat($spacer,$spacing);
            }
       
        }
        else //if maxads is greater than ads, just print whatever is in ads
        {
            if ($title != "")
            {
                echo "$title" . str_repeat($spacer,$titlespacing);
            }
           
            if ($maxads > 1)
            {
                foreach ($ads as $ad)
                {
                    if ($ad != "")
                    {
                        print "$ad" . str_repeat($spacer,$spacing);
                    }
                }
            }
            else
            {
                print "$ads[0]" . str_repeat($spacer,$spacing);
            }
        }//end if count(ads) > maxads
   
    }//end if count and max ads > 0
   
}
else
{
    //nothing to do here.  replace with banner or alternate ad code if you want!
}


?>

Get the Current Page URL

 Get the Current Page URL 

<? $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?>

Scale an image using PHP


Scale an image using PHP


<form action="/upload.php" enctype="multipart/form-data" method="post">
<input id="upload" name="upload" type="file" />
<input id="final-upload" type="submit" value="Upload Image" /></form>

<?php
define( 'MAX_FILESIZE', 20000 );
define( 'UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . 'uploads/' );
    
if( !empty( $_FILES['upload'] ) && $_POST )
{

//some error code checking
if( !empty( $_FILES['upload']['error'] ) )
{
switch( $_FILES['upload']['error'] )
{
 case '1':
 $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
 break;
case '2':
     $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
  break;
case '3':
  $error = 'The uploaded file was only partially uploaded';
  break;
  case '4':
     $error = 'No file was uploaded.';
       break;
 case '6':
      $error = 'Missing a temporary folder';
      break;
 case '7':
        $error = 'Failed to write file to disk';
            break;
    case '8':
        $error = 'File upload stopped by extension';
       break;
      case '999':
        default:
            $error = 'No error code avaiable';
        }
    }
elseif( empty( $_FILES['upload']['tmp_name'] ) )
{
    $error = 'No file was uploaded.';
    }
    // Is the file an image?
    elseif( !preg_match( '|image/|', $_FILES['upload']['type'] ) )
    {
        $error = 'File is not an image.';
    }
    // Is the file small enough?
    elseif( $_FILES['upload']['size'] > MAX_FILESIZE )
    {
        $error  = 'File is too big.';
    }


if( !$error )
    {
        // Find the uploaded file extension
        $ext    = substr( $_FILES['upload']['name'], strrpos( $_FILES['upload']['name'], '.' ) + 1 );
   
        // If the main file has uploaded, proceed to create the thumbnail
    if( move_uploaded_file( $_FILES['upload']['tmp_name'], UPLOAD_PATH . $_FILES['upload']['name'] ) )
        {
            $main_image = UPLOAD_PATH . $_FILES['upload']['name'];
   
            // Create the thumbnail
            $make_thumb = create_thumb( $main_image, 100, 100, UPLOAD_PATH . 'thumb_' . $_FILES['upload']['name'], $ext );
   
            // Check that the thumbnail was created
            if( !$make_thumb )
            {
                $error = 'Thumbnail was unable to be created.';
            }
        }
        else
        {
            $error  = 'Failed to upload image. Ensure directories are created properly.';
        }
    }
function create_thumb( $imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext )
    {
        //getting the image dimensions
        list( $width_orig, $height_orig ) = getimagesize( $imgSrc );

        // Check if the images is a gif
        if( $ext == 'gif' )
        {
            $myImage = imagecreatefromgif($imgSrc);
        }
        // Check if the image is a png
        elseif( $ext == 'png' )
        {
            $myImage = imagecreatefrompng($imgSrc);
        }
        // Otherwise, file is jpeg
        else
        {
            $myImage = imagecreatefromjpeg($imgSrc);
        }
   
        // Find the original ratio
        $ratio_orig = $width_orig / $height_orig;
   
        // Check whether to scale initially by height or by width
        if( $thumbnail_width / $thumbnail_height > $ratio_orig )
        {
            $new_height = $thumbnail_width/$ratio_orig;
            $new_width  = $thumbnail_width;
        }
        else
        {
            $new_width      = $thumbnail_height*$ratio_orig;
            $new_height = $thumbnail_height;
        }
   
        $x_mid = $new_width / 2;  //horizontal middle
        $y_mid = $new_height / 2; //vertical middle
   
        $process = imagecreatetruecolor( round( $new_width ), round( $new_height ) );
   
        // Scale the image down and the reduce the other axis to create the thumbnail
        imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
        $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)),   $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
   
        // Depending on the file extension, save the file
        if( $ext == 'gif' )
        {
            imagegif( $thumb, $dest_src );
        }
        elseif( $ext == 'png' )
        {
            imagepng( $thumb, $dest_src );
        }
        else
        {
            imagejpeg( $thumb, $dest_src, 100 );
        }
   
        // Remove rubbish file data
        imagedestroy($process);
        imagedestroy($myImage);
   
        // Return thumb ( success / fail )
        return $thumb;
    }
}?>

Valid URL

Valid URL

$url = http://www.tutorialcadet.com

if (!preg_match('/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/', $url)) {
 
echo 'The URL you entered was invalid. Be sure to include <strong>http://</strong>';
 
}

 

Integer contain between 1 and 16 characters

 Integer contain between 1 and 16 characters
$int = 4;
 
if (!preg_match('#^[0-9]{1,16}$#', $int)) {
 
echo 'That is not a valid integer.';
 
}

string contain between 4 and 28 characters

string contain between 4 and 28 characters


$string = "tutorial";
 
if (!preg_match('#^(.){4,128}$#', $string)) {
 
echo 'The string you entered is invalid.';
 
}

E-mail Validation

E-mail Validation

$email = 'editor@thedaily.com'
 
if (!preg_match('^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$^', $email)) {
 
echo 'The email address you entered was invalid.';
 
}

Cross browser Chat

 table
create table chat(
time int(11) NOT NULL,
name varchar(30) NOT NULL,
ip varchar(15) NOT NULL,
message varchar(255) NOT NULL,
PRIMARY KEY (time)
)

 For the rest of the Chat script we will need 3 more files:
chat.php
send.php
show-messages.php


chat.php
<html>
<head>
<style>
.message {
overflow:hidden;
width:498px;
margin-bottom:5px;
border:1px solid #999;
}
.messagehead {
overflow:hidden;
background:#FFC;
width:500px;
}
.messagecontent {
overflow:hidden;
width:496px;
}
</style>
</head>

<body>
<div id="chat" style="width:500px;margin:0 auto;overflow:hidden;">
//This div will contain the messages
<div id="messages"></div>
//This div will contain an eventual error message
<div id="error" style="width:500px;text-align:center;color:red;"></div>
//This div contains the forms and the send button
<div id="write" style="text-align:center;"><textarea id="message" cols="50" rows="5"></textarea><br/>Name:<input type="text" id="name"/><input type="button" value="Send" onClick="send();"/></div>
</div>

<script type="text/javascript">
//This function will display the messages
function showmessages(){
//Send an XMLHttpRequest to the 'show-message.php' file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
//And here is the line what makes it cross-browser:
xmlhttp.open("GET","show-messages.php?" + Math.random(),false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","showmessages.php?" + Math.random(),false);
xmlhttp.send();
}
//Replace the content of the messages with the response from the 'show-messages.php' file
document.getElementById('messages').innerHTML = xmlhttp.responseText;
//Repeat the function each 30 seconds
setTimeout('showmessages()',30000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
function send(){
//Send an XMLHttpRequest to the 'send.php' file with all the required informations
var sendto = 'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';
//If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed
switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
document.getElementById('error').innerHTML = '';
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>

</body>
</html>

send.php
<?php
//Connect to MySQL
mysql_connect('host', 'database', 'password') or die (1);
//Select database
mysql_select_db('database') or die (2);
//Check if message is empty and send the error code
if(strlen($message) < 1){
echo 3;
}
//Check if message is too long
else if(strlen($message) > 255){
echo 4;
}
//Check if name is empty
else if(strlen($name) < 1){
echo 5;
}
//Check if name is too long
else if(strlen($name) > 29){
echo 6;
}
//Check if the name is used by somebody else
else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){
echo 7;
}
//If everything is fine
else{
//This array contains the characters what will be removed from the message and name, because else somebody could send redirection script or links
$search = array("<",">","&gt;","&lt;");
//Insert a new row in the chat table
mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);
}
?>

show-messages.php
<?php
//Connect to MySQL
mysql_connect('host','database','password');
//Select database
mysql_select_db('database') or die(2);
//Get the first 10 messages ordered by time
$result = mysql_query("select * from chat order by time desc limit 0,10");
$messages = array();
//Loop and get in an array all the rows until there are not more to get
while($row = mysql_fetch_array($result)){
//Put the messages in divs and then in an array
$messages[] = "<div class='message'><div class='messagehead'>" . $row[name] . " - " . date('g:i A M, d Y',$row[time]) . "</div><div class='messagecontent'>" . $row[message] . "</div></div>";
//The last posts date
$old = $row[time];
}
//Display the messages in an ascending order, so the newest message will be at the bottom
for($i=9;$i>=0;$i--){
echo $messages[$i];
}
//This is the more important line, this deletes each message older then the 10th message ordered by time is deleted, so the table will never have to store more than 10 messages.
mysql_query("delete from chat where time < " . $old);
?>

Create a POLL System

 table
create table poll(
vote tinyint(2) NOT NULL,
ip varchar(15) NOT NULL,
PRIMARY KEY (ip)
)

poll.php
<html>

<head>
<style>
.votes {
overflow:hidden;
background:#CCC;
height:20px;
width:100px;
margin:5px 0 0 23px;
float:left;
}
.percentage {
overflow:hidden;
background:#F00;
height:20px;
}
.option {
position:absolute;
width:100px;
height:20px;
}
.percentagetext {
overflow:hidden;
width:75px;
height:20px;
margin:5px 0 0 0;
float:left;
text-align:left;
}
</style>
</head>

<body>
<div id="poll" style="width:200px;overflow:hidden;text-align:center;">
Do you like this poll?<br/>
<div style="text-align:left;width:180px;margin:0 auto;">
<input type="radio" name="poll" id="poll1" checked>Yes, it`s great<br/>
<input type="radio" name="poll" id="poll2">Yes...<br/>
<input type="radio" name="poll" id="poll3">Not bad...<br/>
<input type="radio" name="poll" id="poll4">No!<br/>
</div>
<input type="button" value="Vote!" onClick="vote();"/>
</div>
<script type="text/javascript">
function vote(){
for(var i=1;i<=4;i++){
if(document.getElementById('poll' + i).checked){
//Check which one has been checked
var sendto = 'vote.php?vote=' + i;
}
}
// Call the vote.php file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest;
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
//Output the response
document.getElementById('poll').innerHTML = xmlhttp.responseText;
}
</script>

</body>
</html>

Simple Chat script

Simple Chat script 

 For the rest of the Chat script we will need 3 more files:
chat.php
send.php
show-messages.php
 chat.php 


<html>
<head>
<style>
.message {
overflow:hidden;
width:498px;
margin-bottom:5px;
border:1px solid #999;
}
.messagehead {
overflow:hidden;
background:#FFC;
width:500px;
}
.messagecontent {
overflow:hidden;
width:496px;
}
</style>
</head>

<body>
<div id="chat" style="width:500px;margin:0 auto;overflow:hidden;">
//This div will contain the messages
<div id="messages"></div>
//This div will contain an eventual error message
<div id="error" style="width:500px;text-align:center;color:red;"></div>
//This div contains the forms and the send button
<div id="write" style="text-align:center;"><textarea id="message" cols="50" rows="5"></textarea><br/>Name:<input type="text" id="name"/><input type="button" value="Send" onClick="send();"/></div>
</div>

<script type="text/javascript">
//This function will display the messages
function showmessages(){
//Send an XMLHttpRequest to the 'show-message.php' file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","show-messages.php",false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","showmessages.php",false);
xmlhttp.send();
}
//Replace the content of the messages with the response from the 'show-messages.php' file
document.getElementById('messages').innerHTML = xmlhttp.responseText;
//Repeat the function each 30 seconds
setTimeout('showmessages()',30000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
function send(){
//Send an XMLHttpRequest to the 'send.php' file with all the required informations
var sendto = 'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';
//If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed
switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
document.getElementById('error').innerHTML = '';
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>

</body>
</html>
send.php
<?php
//Connect to MySQL
mysql_connect('host', 'database', 'password') or die (1);
//Select database
mysql_select_db('database') or die (2);
//Check if message is empty and send the error code
if(strlen($message) < 1){
echo 3;
}
//Check if message is too long
else if(strlen($message) > 255){
echo 4;
}
//Check if name is empty
else if(strlen($name) < 1){
echo 5;
}
//Check if name is too long
else if(strlen($name) > 29){
echo 6;
}
//Check if the name is used by somebody else
else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){
echo 7;
}
//If everything is fine
else{
//This array contains the characters what will be removed from the message and name, because else somebody could send redirection script or links
$search = array("<",">","&gt;","&lt;");
//Insert a new row in the chat table
mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);
}
?>

Show-messages.php

<?php
//Connect to MySQL
mysql_connect('host','database','password');
//Select database
mysql_select_db('database') or die(2);
//Get the first 10 messages ordered by time
$result = mysql_query("select * from chat order by time desc limit 0,10");
$messages = array();
//Loop and get in an array all the rows until there are not more to get
while($row = mysql_fetch_array($result)){
//Put the messages in divs and then in an array
$messages[] = "<div class='message'><div class='messagehead'>" . $row[name] . " - " . date('g:i A M, d Y',$row[time]) . "</div><div class='messagecontent'>" . $row[message] . "</div></div>";
//The last posts date
$old = $row[time];
}
//Display the messages in an ascending order, so the newest message will be at the bottom
for($i=9;$i>=0;$i--){
echo $messages[$i];
}
//This is the more important line, this deletes each message older then the 10th message ordered by time is deleted, so the table will never have to store more than 10 messages.
mysql_query("delete from chat where time < " . $old);
?>
 data base&table
db=database
 //table
create table chat(
time int(11) NOT NULL,
name varchar(30) NOT NULL,
ip varchar(15) NOT NULL,
message varchar(255) NOT NULL,
PRIMARY KEY (time)
) ;