RSS

Monthly Archives: October 2013

How to run a script when user close the browser


I’ve heard that the body element attribute “onbeforeunload” can be used to detect when the window is about to close. You could use ajax to cause a php script to be executed with this attribute. For example:

in this code logout page only call when browser Tab Close .This logout page can’t call on page refresh.

HTML Code:

<html><head>
<script type="text/javascript">
function logout() {
 var xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET", "logout.php", true);
 xmlhttp.send();
}
</script></head>
<body onbeforeunload="logout()">
Your page here
</body></html>



Second Way:


<html>
<body>

<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      document.myForm.time.value=xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET","time.asp",true);
  xmlHttp.send(null);
  }
</script>

<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>

</body>
</html>
 
Leave a comment

Posted by on October 29, 2013 in PHP

 

Tags: , ,

Ajax File Upload with PHP and jQuery


phpupload

 

This Link Help you for uploading Types

http://www.asciitable.it/mimetypes.asp

 

You do not need database just to upload and store file in the server, but most of the time we want to store the file information in our database, so we can later manipulate or list them easily on the pages. Therefore, we are going to create a table in our database, and then we will upload files and store the information in the database table.

Database Table

As discussed above, let’s create a table called records with 5 columns in database as shown below, or you can just copy and run following SQL query in your PhpMyAdmin page, it should automatically create the table for you.

CREATE TABLE IF NOT EXISTS `records` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(60) NOT NULL,
`file_title` varchar(60) NOT NULL,
`file_size` int(11) NOT NULL,
`uploaded_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Creating Upload Form Page

Upload form page contains a regular HTML form, file name field, file input field and the upload button. It is pointed to “uploader.php”, we need to send our POST variables to this PHP page to do the rest of the task, storing file and inserting records in the database.

 

 

<div id=”theForm”>
<div id=”output”></div>
<form action=”uploader.php” id=”FileUploader” enctype=”multipart/form-data” method=”post” >
<label>Title
<span class=”small”>Title of the File</span>
</label>
<input type=”text” name=”mName” id=”mName” />
<label>File
<span class=”small”>Choose a File</span>
</label>
<input type=”file” name=”mFile” id=”mFile” />
<button type=”submit” class=”red-button” id=”uploadButton”>Upload (1MB)</button>
<div class=”spacer”></div>
</form>
</div>

jQuery

Next we need little bit of jQuery to make our form completely Ajax. We will wrap in jQuery $(document).ready method, $(document).ready only gets triggered when the document is fully loaded, so its always a good idea to put our jQuery codes inside this method.

Here’s how jQuery code below works: When the user clicks on submit button, the button gets disabled after the first click, and then we display the loading image, then the form gets submitted to uploader.php using ajaxSubmit (Note, I am using jQuery Form Plugin, and ajaxSubmit is an easy way of sending form data via Ajax, when the plugin is used). If everything goes smoothly, we should receive message from the PHP page, which will be displayed in DIV element called #output, and then we can reset the Form and enable submit button.

 

$(document).ready(function()
{
$(‘#FileUploader’).on(‘submit’, function(e)
{
$(‘#uploadButton’).attr(‘disabled’, ”); // disable upload button
//show uploading message
$(“#output”).html(‘<div style=”padding:10px”><img src=”images/ajax-loader.gif” alt=”Please Wait”/> <span>Uploading…</span></div>’);
$(this).ajaxSubmit({
target: ‘#output’,
success:  afterSuccess //call function after success
});
});
});

function afterSuccess()
{
$(‘#FileUploader’).resetForm();  // reset form
$(‘#uploadButton’).removeAttr(‘disabled’); //enable submit button
}

Combing jQuery and HTML form

I have combined our HTML form and jQuery code in a page as shown below. We should now have a rough looking Ajax upload page. The jQuery goes to <HEAD> part, and the Form goes to <BODY> of the page. I don’t want to go though the whole style part right now, but you can checkout the downloadable file at the bottom which also includes a CSS file.

 

<html>
<head>
<title>File Upload with PHP</title>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js”></script>
<script type=”text/javascript” src=”js/jquery.form.js”></script>
<script>
$(document).ready(function()
{
$(‘#FileUploader’).on(‘submit’, function(e)
{
e.preventDefault();
$(‘#uploadButton’).attr(‘disabled’, ”); // disable upload button
//show uploading message
$(“#output”).html(‘<div style=”padding:10px”><img src=”images/ajax-loader.gif” alt=”Please Wait”/> <span>Uploading…</span></div>’);
$(this).ajaxSubmit({
target: ‘#output’,
success:  afterSuccess //call function after success
});
});
});

function afterSuccess()
{
$(‘#FileUploader’).resetForm();  // reset form
$(‘#uploadButton’).removeAttr(‘disabled’); //enable submit button
}
</script>

</head>
<body>
<div id=”theForm”>
<div id=”output”></div>
<form action=”uploader.php” id=”FileUploader” enctype=”multipart/form-data” method=”post” >
<label>Title
<span class=”small”>Title of the File</span>
</label>
<input type=”text” name=”mName” id=”mName” />

<label>File
<span class=”small”>Choose a File</span>
</label>
<input type=”file” name=”mFile” id=”mFile” />
<button type=”submit” class=”red-button” id=”uploadButton”>Upload (1MB)</button>
<div class=”spacer”></div>
</form>
</div>
</body>
</html>

Uploader PHP page

In previous article, the Form data was posted to PHP page, and every-time the PHP page was reloaded in order to return the success/failure messages, but here the PHP page runs in background, only responding to the Ajax request made by user, user uploading the file won’t even see or interact with the PHP page directly.

Config

Let’s start with configuration variables we need to continue with processing PHP page. The $UploadDirectory variable is where you will be storing the user uploaded files, and then the MySQL username, password, hostname and database information we need to make database queries. Then we check the upload folder and try to create one if it doesn’t exist.

 

$UploadDirectory    = ‘uploads/’; //Upload Directory, ends with slash & make sure folder exist

// replace with your mysql database details

$MySql_username     = “xxx”; //mysql username
$MySql_password     = “xxx”; //mysql password
$MySql_hostname     = “localhost”; //hostname
$MySql_databasename = ‘xxx’; //databasename

if (!@file_exists($UploadDirectory)) {
//destination folder does not exist
die(“Make sure Upload directory exist!”);
}

POST Variables

It’s always a good practice to check empty POST data, before we continue and then run into silly errors. The syntax below checks whether the data is coming form a HTML Form or not, only then it moves to next step.

 

if($_POST)
{
// do our form data processing
}
Next we check for empty fields, if everything is OK, we need to get POST variables and prepare the type, size and random name for the file we are going to store. Once we have the file type, we can compare the file with our allowed file type list, if it’s not in the list we can just exit the script outputting the error.
if($_POST)
{
if(!isset($_POST[‘mName’]) || strlen($_POST[‘mName’])<1)
{
//required variables are empty
die(“Title is empty!”);
}

if(!isset($_FILES[‘mFile’]))
{
//required variables are empty
die(“File is empty!”);
}

$FileName           = strtolower($_FILES[‘mFile’][‘name’]); //uploaded file name
$FileTitle          = mysql_real_escape_string($_POST[‘mName’]); // file title
$ImageExt           = substr($FileName, strrpos($FileName, ‘.’)); //file extension
$FileType           = $_FILES[‘mFile’][‘type’]; //file type
$FileSize           = $_FILES[‘mFile’][“size”]; //file size
$RandNumber         = rand(0, 9999999999); //Random number to make each filename unique.
$uploaded_date      = date(“Y-m-d H:i:s”);

switch(strtolower($FileType))
{
//allowed file types

case ‘audio/wav’: //wav file
case ‘audio/x-wav’: //wav file

case ‘audio/x-mp3’: //mp3 file
case ‘audio/x-mpeg-3’: //mp3 file
case ‘audio/mpeg3’: //mp3 file
case ‘audio/mpeg’: //mp3 file
case ‘image/png’: //png file
case ‘image/gif’: //gif file
case ‘image/jpeg’: //jpeg file
case ‘application/pdf’: //PDF file
case ‘application/msword’: //ms word file
case ‘application/vnd.ms-excel’: //ms excel file
case ‘application/x-zip-compressed’: //zip file
case ‘text/plain’: //text file
case ‘text/html’: //html file
break;
default:
die(‘Unsupported File!’); //output error
}

}
//File Title will be used as new File name
$NewFileName = preg_replace(array(‘/s/’, ‘/.[.]+/’, ‘/[^w_.-]/’), array(‘_’, ‘.’, ”), strtolower($FileTitle));
$NewFileName = $NewFileName.’_’.$RandNumber.$ImageExt;

Storing File

Once we are done with checking and preparing, we can now safely move the uploaded file to new location. PHP move_uploaded_file moves an uploaded file to a new location, we just need to specify the filename and the destination path. When we know the file is successfully moved to new location, we can proceed with database queries as shown in syntax below. As you can see the MySQL INSERT statement just inserts the file information into the database table we created earlier in this article.

 

if(move_uploaded_file($_FILES[‘mFile’][“tmp_name”], $UploadDirectory . $NewFileName ))
{
//connect & insert file record in database
$dbconn = mysql_connect($MySql_hostname, $MySql_username, $MySql_password)or die(“Unable to connect to MySQL”);
mysql_select_db($MySql_databasename,$dbconn);
@mysql_query(“INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES (‘$NewFileName’, ‘$FileTitle’,$FileSize,’$uploaded_date’)”);
mysql_close($dbconn);
die(‘Success! File Uploaded.’);

}else{
die(‘error uploading File!’);
}

Complete PHP page

Here’s the complete PHP code which does the server side task, you need to place this file along with upload Form page we created earlier. Just point your Ajax form to this file and it should work without any trouble.

I have tried to make this tutorial very simple, you can download the sample files from bottom of this page and continue with testing. If you have any suggestions to improve this tutorial, please go ahead and leave your valuable comments, good luck!

 

<?php
$UploadDirectory    = ‘uploads/’; //Upload Directory, ends with slash & make sure folder exist

// replace with your mysql database details

$MySql_username     = “xxx”; //mysql username
$MySql_password     = “xxx”; //mysql password
$MySql_hostname     = “localhost”; //hostname
$MySql_databasename = ‘xxx’; //databasename

if (!@file_exists($UploadDirectory)) {
//destination folder does not exist
die(“Make sure Upload directory exist!”);
}

if($_POST)
{
if(!isset($_POST[‘mName’]) || strlen($_POST[‘mName’])<1)
{
//required variables are empty
die(“Title is empty!”);
}

if(!isset($_FILES[‘mFile’]))
{
//required variables are empty
die(“File is empty!”);
}

if($_FILES[‘mFile’][‘error’])
{
//File upload error encountered
die(upload_errors($_FILES[‘mFile’][‘error’]));
}

$FileName           = strtolower($_FILES[‘mFile’][‘name’]); //uploaded file name
$FileTitle          = mysql_real_escape_string($_POST[‘mName’]); // file title
$ImageExt           = substr($FileName, strrpos($FileName, ‘.’)); //file extension
$FileType           = $_FILES[‘mFile’][‘type’]; //file type
$FileSize           = $_FILES[‘mFile’][“size”]; //file size
$RandNumber         = rand(0, 9999999999); //Random number to make each filename unique.
$uploaded_date      = date(“Y-m-d H:i:s”);

switch(strtolower($FileType))
{
//allowed file types
case ‘image/png’: //png file
case ‘image/gif’: //gif file
case ‘image/jpeg’: //jpeg file
case ‘application/pdf’: //PDF file
case ‘application/msword’: //ms word file
case ‘application/vnd.ms-excel’: //ms excel file
case ‘application/x-zip-compressed’: //zip file
case ‘text/plain’: //text file
case ‘text/html’: //html file
break;
default:
die(‘Unsupported File!’); //output error
}

//File Title will be used as new File name
$NewFileName = preg_replace(array(‘/s/’, ‘/.[.]+/’, ‘/[^w_.-]/’), array(‘_’, ‘.’, ”), strtolower($FileTitle));
$NewFileName = $NewFileName.’_’.$RandNumber.$ImageExt;
//Rename and save uploded file to destination folder.
if(move_uploaded_file($_FILES[‘mFile’][“tmp_name”], $UploadDirectory . $NewFileName ))
{
//connect & insert file record in database
$dbconn = mysql_connect($MySql_hostname, $MySql_username, $MySql_password)or die(“Unable to connect to MySQL”);
mysql_select_db($MySql_databasename,$dbconn);
@mysql_query(“INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES (‘$NewFileName’, ‘$FileTitle’,$FileSize,’$uploaded_date’)”);
mysql_close($dbconn);

die(‘Success! File Uploaded.’);

}else{
die(‘error uploading File!’);
}
}

//function outputs upload error messages, http://www.php.net/manual/en/features.file-upload.errors.php#90522
function upload_errors($err_code) {
switch ($err_code) {
case UPLOAD_ERR_INI_SIZE:
return ‘The uploaded file exceeds the upload_max_filesize directive in php.ini’;
case UPLOAD_ERR_FORM_SIZE:
return ‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form’;
case UPLOAD_ERR_PARTIAL:
return ‘The uploaded file was only partially uploaded’;
case UPLOAD_ERR_NO_FILE:
return ‘No file was uploaded’;
case UPLOAD_ERR_NO_TMP_DIR:
return ‘Missing a temporary folder’;
case UPLOAD_ERR_CANT_WRITE:
return ‘Failed to write file to disk’;
case UPLOAD_ERR_EXTENSION:
return ‘File upload stopped by extension’;
default:
return ‘Unknown upload error’;
}
}
?>

Use This Link for sample code download ….
 
Leave a comment

Posted by on October 4, 2013 in PHP

 

Tags: , , , ,