Multiple file upload using jquery and php

In this tutorial I’m going to show you how you can handle multiple file uploads using php and jquery.




I’m assuming that you already know the basics of php and jquery. I’ll try to make this tutorial as short as possible. But you can also check out the documentation of the blueImp jquery file upload if you are pretty confident in your skills.

First, you need to include the css files for the file upload plugin. Remember to change the code inside the href attribute to match your folder structure.

<link rel="stylesheet" href="../jqui.css" id="theme">
<link rel="stylesheet" href="../jquery.fileupload-ui.css">

Then the html form that will be used to upload files. Remember that this can be used to upload multiple files to the webserver.

<form id="file_upload" action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" multiple>
    <div>Upload files</div>

Then just after the form. Insert a table tag. This will be used later on to display the selected files.

<table id="files"></table>

Next, include the scripts you downloaded earlier.

<script src="../jq.js"></script>
<script src="../jqui.js"></script>
<script src="../jquery.fileupload.js"></script>
<script src="../jquery.fileupload-ui.js"></script>

Then insert another script tag. This script will communicate with ‘upload.php’. And you can also define here  some rules regarding filesize , filetype and other restrictions in uploading a file.

/*global $ */
$(function () {
        uploadTable: $('#files'),
        downloadTable: $('#files'),
        buildUploadRow: function (files, index) {
            return $('<tr><td>' + files[index].name + '</td>' +
                    '<td class="file_upload_progress"><div></div></td>' +
                    '<td class="file_upload_cancel">' +
                    '<button class="ui-state-default ui-corner-all" title="Cancel">' +
                    '<span class="ui-icon ui-icon-cancel">Cancel</span>' +
        buildDownloadRow: function (file) {
            return $('<tr><td>' + + '</td></tr>');

That’s pretty much what you need if you don’t need to restrict the user from uploading a 200TB file. Or a javascript file that will mess up your whole system.

If however you want to limit the user from doing that. Then include the function below. Under the beforeSend event. The code below will limit the file size to 1Mb or 1 Million Bytes? Yeah, that’s a question mark since I’m not sure if 1Mb is really equal to 1 Million Bytes.

 function (event, files, index, xhr, handler, callBack) {
         if (files[index].size > 1000000) {
             handler.uploadRow.find('.file_upload_progress').html('FILE TOO BIG!');
             setTimeout(function () {
             }, 10000);

If you’re not satisfied with just limiting the file size. And you want the user to be able to upload only specific file types. Like for example, images:

var regexp = /.(png)|(jpg)|(gif)$/i;
       if (!regexp.test(files[index].name)) {
           handler.uploadRow.find('.file_upload_progress').html('ONLY IMAGES ALLOWED!');
           setTimeout(function () {
           }, 10000);

Lastly, the php script that will do the transfer from the clients computer to a folder inside the webservers web accessible directory. Here’s a short story on how this works: First the user will click on the upload button. Then selects multiple files. Blue Imp Jquery File Uploader will handle all the processes needed to forward the file information (temporary file path, filename, file size, file type) to the php script that you defined. In this case ‘upload.php’. As you can see from the code below. We don’t even have to create an array for all the files that are selected since its already done by Blue Imp. As you can see, the selected files will be uploaded to a folder named ‘img’. We used the ‘move_uploaded_file’ function because the file is not being materialized directly to the folder where we want it to reside. After every upload, it first resides on a ‘tmp’ or temporary folder in your webserver. In wamp the temporary folder is in: ’ C:wamptmp’ . You might notice that all the files in that folder have .tmp file extension and that the filename is mainly composed of unusual characters. That is why we need to issue this ‘$_FILES[“file”][“name”]’ as a parameter to get the original filename.

$file = $_FILES['file'];
echo '{"name":"'.$file['name'].'","type":"'.$file['type'].'","size":"'.$file['size'].'"}';
$transform=explode('.', $tempath);
$truefile=explode('.', $_FILES["file"]["name"]);
$filenamepath=$transform[0]. ".". $truefile[1];
      "img/" . $_FILES["file"]["name"]);

This is what it will look like. If you haven’t customized it.


Notice that it didn’t actually upload the txt file, and the mkv file which is 70Mb in size. But one thing that has caught my attention is the txt file which I changed the file extension to png. It actually uploaded it. I wonder if its really possible to detect the real extension of a file noting that the extension was only edited.




That is all with this tutorial. I hope you learned something. And please share this site using the buttons below if this tutorial has helped you.

Use gmail to send email in php

This time I’m going to show you how you can send emails in php using gmail smtp server.




First you have to download phpMailer from the link that I gave above. What I’m going to use in this tutorial is phpmailer for php version 5 and 6.


Just download the .zip file so that you won’t have any trouble extracting it. Especially if you are on windows.

Extract the file inside the wamp directory. Rename the extracted folder to phpmailer. So that it will be easier to remember.


To be consistent. After opening your phpmailer folder. It should contain most of these files:


Now, open up the class.phpmailer.php in a decent text editing tool like notepad++ or programmer’s notepad.

Press ctrl + h in your keyboard and search for $host or anything similar:


Until you find these lines:

public $Host          = 'localhost';
public $Port          = 25;

Those are the defaults. Change those to:

public $Host          = 'ssl://';
public $Port          = 465;

You can also change it to other hosts. But this tutorial is only for using gmail smtp. So just search it on your own if you want to use other smtp servers.


Next, create a new php file. This time, inside your project folder. Include those 2 files that you edited earlier. Remember to change the example below based on the actual location of your phpmailer folder.


Then create an object of the phpMailer class. And specify that it will be using SMTP or Simple Mail Transfer Protocol to send emails.

$mail = new PHPMailer();  

Also add this line to enable SMTP authentication. To authenticate that you are indeed a real human. And not a spammer bot.

$mail->SMTPAuth = true; 

Then add these lines. To specify which email address you are going to use as the sender email address:

$mail->Username = ""; 
$mail->Password = "mypasswordisthis"; 

I haven’t tested yet if you can use other  email addresses besides gmail. But you can certainly send emails to yahoo or hotmail account using this method.

Next, specify the email address where the recipient is going to reply:

$webmaster_email = ""; 

Then, the recipients email address. This can be yahoo, hotmail , or other email accounts as I have said a while ago.


Then, specify the name of the recipient together with the  email address that the recipient will see as the one who sent the mail.

$name="Master Buten"; 
$mail->From = $webmaster_email;

In the example above, we will send the email to master buten.

You can also specify your name after that:

$mail->FromName = "Master Kayosama";

Then we call the phpMailer function which uses the variables that we defined earlier as an argument:


Then call the other function that adds reply to information to the email that we are going to send:

$mail->AddReplyTo($webmaster_email, $mail->FromName);

You can also set the word wrap attribute to anything you want. Word wrap will allow you to format the body of your email in a nice way. If you specify it to be 50 then it creates a new line before or when 50 characters have been entered.

$mail->WordWrap = 50;

Then for adding attachments. You call the function addAttachment:


Then specify if the email is html.


Add the subject and the body of the email:

$mail->Subject = "Training"; $mail->Body = "I send you this email because

we will have a training inside Mt. Pinatubo on Mar 31, 2011";

You can also add an alternative body if you want. This is the one that the recipient is going to see if he switches to plain text format.

$mail->AltBody = "I send you this email because
 we will have a training inside Mt. Pinatubo on Mar 31, 2011";

Lastly, add these lines in order for you to determine if the mail is indeed sent or not:

echo "Mailer Error: " . $mail->ErrorInfo;
echo "Message has been sent";

Oops, were not ready to fire up that file yet. There’s one more thing to do.

Left click on the wamp tray icon. Select php-> php extensions.


Then you just have to ensure that php_openssl is checked. If not, then click it.


Next, restart all services.


Wait for the wamp tray icon to turn white before you do anything funny.

Fire up the php file that you have created. You should see something like the one below. If not, then review the instructions that I provided and see if you followed them well.




That’s an easy way to send email in php using gmail smtp. Please share this article if you like it. If you have questions or suggestions just throw them in the comments. Thanks for reading!

How to solve skype and wampserver conflicts

When you are programming in php. And you’re using wampserver. You might have notice that when you also have skype installed. The wamp icon in the notification area is color yellow. And it only means one thing. That some of the components cannot initialize properly. But this is only true if you have skype and wamp running at the same time.

There’s a conflict between the two since mysql(a component of wampserver) uses the same port with skype.

Here are the ways on how to solve this annoying problem:


Quit Skype



Pretty much self explanatory. Quit skype by right-clicking on the tray icon and select quit. Then restart wampserver by left-clicking its tray icon the select restart all services.


Uninstall Skype


If you’re not really using Skype. Then why not uninstall it.


Change MySql port


Left click wampserver tray icon. Select MySQL then click on my.ini. If this is the first time you do this. Then just select notepad to open the file.

Once you opened the file in notepad. You will see a bunch of text. Just look for the line which says:

   1: port=3306

And change it to:

   1: port=3309

Like the screenshot below:


Hit ctrl + s on your keyboard. Then perform the restart all services magic. If that doesn’t do the trick then select a random number then change the port number again.



You can also do the magic tricks above. If you’re experiencing other port conflicts on your other applications.

How to merge avi and srt files

In this tutorial, I’m going to show you how you can merge an avi file and an srt file. Most of the time, you won’t need to merge the two files in order to get  a video with subtitles on it. Because when the filename of the srt and avi are the same. Then the video player will automatically load up the subtitles while you play the video. Considering that the subtitle options are activated.

But what if you have a soft-coded or soft-sub video? Soft-sub means that the subtitles in the video are not totally embedded in the file. It means that if you convert the video file from its original format to the other. Then the subtitles will disappear.





First , you have to download all the requirements. I’ve already provided the links above.



Second, install the files that you have downloaded.

Here’s a set of screenshot for the installation of mkvtoolnix:

Click next.


Click next again.


Click install.


Here’s what you will see after the installation. Just click next.


Then finish.


Now, go to the installation folder:

   1: C:Program FilesMKVtoolnix

And paste the executable file of the mkv extract that you also downloaded.

The folder should contain these files:



And here’s how to install AVIrecomp.

Click on next.


Check the box. Then click on next.


Make sure that all the boxes are checked. Then click next.


Leave it to defaults. Click install.


Remember that this is a compound installer. And it calls on multiple installations. This time it will install avisynth. Just click on agree.


Type of installation is standard. Click next.



Here comes the next one.




And the installer for vobsub:



That’s it.


Extracting Subtitles

Third, we will need to extract the subtitle files from the video file. I’m assuming that the video file you have is in mkv format. So if you have another type of file then this tutorial is not for you.

Open the MKVextractGUI.exe. And click on the button which I highlighted


Select the mkv file and click on open.


Check the track with subtitles on it. Then click on the extract button.


An ass file will be added to the folder where your mkv file is. And by the way ass means advanced substation alpha.


Converting mkv to avi

Fourth, we need to convert the mkv file into avi. Because the software that were going to use for merging the subtitles with the video file can only read .avi

For this, you can make use of freemake. As the name implies it’s a free video converter which supports all video files that you could think of.

You can use the original mkv file for this. Just drag the mkv file on its interface. Then click on avi.


Just leave it to the defaults for now. And just click convert.





For the last part. Open up AVIrecomp. Click on the source and output tab. Click the open avi button.


And select the avi file which you got from the freemake conversion earlier.


Click on the save avi button. Don’t change the default filename. And just click on save.


The first tab will now look like this:


Now, click on the additions tab. On the subtitles panel. Check the box which says enable/disable. Then click on the load subtitles button.


Select the ass file. And click on open.


Lastly, click on the queue tab.  Click on add to queue. Then click on start, if you don’t have other files to tinker with. If you have other files then repeat the process again. Then click on start after all the files has been added into the queue.

Applying oop in php in mysql database manipulation

In this tutorial. I’m going to show you how you can make a class for manipulating mysql database in php.

Like you I’m still a beginner. But I want to keep track of what I have learned. That’s why I made this blog. The codes you will see here are not optimized and secured. This is only for the purpose of sharing what I know.

Let’s begin by creating a new class. If you’re not yet familiar with object oriented programming. Then you should learn java. I believe that java is good for beginners.

    class mysqlcon{

You can name the class whatever you want to name it. That class will contain all the functions and fields that will be used to manipulate mysql database.

To refresh your memories. Here’s how we connect to mysql database in a procedural way:

<?php //procedural $lname="Ancheta"; $uid="1"; $con=mysql_connect("localhost","root","1234"); $db=mysql_select_db("objordb",$con); $selects=mysql_query("SELECT * FROM testtable"); $inserts=mysql_query("INSERT INTO testtable(LNAME)

VALUES('$lname')"); $updates=mysql_query("UPDATE testtable

SET LNAME='$lname' WHERE UID='$uid'"); $deletes=mysql_query("DELETE FROM testtable WHERE UID='$uid'"); if(myql_num_rows()==0){//check if record exists echo "Does not exist!"; }else{ //if record exist while($row=mysql_fetch_assoc($selects)){//fetch all matches echo $row['LNAME']; } } ?>

It looks messy right?

We can avoid this and make our code more organized if we used the principles of object oriented programming. In the applications that were going to build.

The analogy here, is that we make a single class which will contain all the things that we need to manipulate our mysql database. A single repository for all the tools we need. So that things will be more organized. So that there’s no need to rewrite code.



First thing that we need to do after declaring a new class. Is to declare the member fields. Or variables that will be used throughout the whole class.

private $connection; //variable that will store the database configuration
private $database; //variable that will store the name of the database
public $query; //variable that will store the queries



Second, we declare the function that will open the database connection:

 function open_con(){
    $this->connection=mysql_connect("localhost", "root", "1234"); 
    $this->database=mysql_select_db("cms", $this->connection);

Nothing new here, we just encapsulated the built in php functions for manipulating mysql database.



Third, we declare a constructor. The constructor is the function which is called the moment you declare an object of the class where it belong.

In this case, we have to call the open_con() function on the constructor. So that we don’t have to call the open_con() function every time we want to connect.

function __construct(){

You can also call other functions in the constructor if you want.


Closing connection

If we have open, then we must also have close connection. This is not mandatory. Because oftentimes we don’t really close the connection.

function close_con(){

What I just did was to check if the connection variable has contents. If it contains anything then I call the mysql_close function and supplied the connection variable as the argument. Then lastly, I unset the connection variable. To make sure that it contains no information about the database. The next time anyone uses it.



Fifth, the query part. My codes here are not fully object oriented because I just reused what is available, and encapsulated them.

Here’s a function that will need a String argument. And after it has been called, considering that the correct argument has been supplied. In this case, a query string. Then it will return the query equivalent of that query string. Where it is no longer a string variable but a resource. Which can be used in other mysql functions.

function make_query($queryString){
        return mysql_query($queryString);

Here’s another example. A function which returns the number of rows that a query string has returned. As you can see this function makes use of the make_query() function to convert the query string into a resource. Then calls the mysql_num_rows function and supplied the query, as the argument. Then finally returned the value.

function num_rows($queryString){
        return mysql_num_rows($this->query);

Its similar to what you see in phpmyadmin when you execute a select query:


In the screenshot , the total number of rows returned is 8.


Here’s the last example, a function which performs a delete query:

function deletes($table, $field, $id){ $this->query=$this->make_query("DELETE FROM {$table}

WHERE {$field}={$id}"); }

Its pretty much the same as the previous examples. But we used an argument as part of the query.



This is the final part of this tutorial. Where we actually call the functions that we declared in our class.

First thing that we need to do is to create a new php file, and include the file that we created earlier:


Then we create an object of the class. Make sure that the name that you type after the ‘new’ keyword  matches the actual name of the class:

$con=new mysqlcon();

You can scroll to the top, to verify things.

And here’s how to call functions:

$rows = $mysqlcon->num_rows("SELECT * FROM users");
echo $rows;

This will echo out, 8. As we have seen earlier on the screenshot.

Here’s another which deletes the user with the ID of 5 from the users table:

$mysqlcon->deletes('users', 'ID', 5);

Note that the number 5 isn’t surrounded with quotes.




You have learned how to apply oop in php. This may not be the best tutorial but I hope you learned something.

How to know the name of the called function in php

I have just started migrating from procedural php to object oriented php. Since object oriented is easier to maintain and is more organized that procedural. First thing that I want to tackle about object oriented php is determining the name of the function that you are calling.

Here’s a sample class and a sample function. I assigned 1 parameter with the name $caller and assigned it to be equal to __FUNCTION__ which is a magic constant in php. Then I just echo back the variable $caller.

class sampleclass{
     function mysqlselectall($caller=__FUNCTION__){
        echo $caller. ": ";
        $this->mysqlFetchAssoc("SELECT * FROM testtable");       

So that every time you try to call that function mysqlselectall it will first echo its name then try to perform the actions that you supplied.



I can’t really think of how this would be useful. But maybe this can help in debugging purposes. Especially when you think that you are calling a certain function but its actually not the function that is being executed.

Escaping invalid characters in php

In this tutorial. I’m going to show you how you can escape all invalid characters in php. This will be useful when you are writing an application which connects and manipulates a database. For example, a mysql database wherein you perform insert, update, delete queries.


Why escape invalid characters?

Simple, since not every character that you can type using your keyboard can be valid when performing queries. As an example, try opening up phpmyadmin and perform the query below on the database of your choice:

SELECT * FROM table_name where field_name='dog's'

Note: substitute the table_name and field_name with the corresponding table name and field name that you are querying.

Next thing you will see is this nasty error:

#1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘s” at line 1

You can now imagine what will happen if you just did something like this in your code:

<?php include_once('connection.php'); $uname=$_POST['uname']; $pword=$_POST['pword']; mysql_query("INSERT INTO users(Username, Password)

VALUES('$uname','$pword')"); ?>

You’ll get the same nasty error. If the user inputs an invalid character in the form.

Here are some of the ways on how to avoid invalid characters from getting to your queries. These can also be used to avoid sql injections and other nasty attacks. But don’t take my word for it. Research on ways on how to avoid sql injections if you want to make your application more secured.



Use the built in php function to sanitize user input:

$userinfor=array($_POST['uname'], md5($_POST['pword'])); $newvalue=array(); foreach($userinfor as $key=>$value){ $newvalue[$key]=mysql_real_escape_string($value); } $uname=$newvalue[0]; $pword=$newvalue[1]; $db->query("INSERT INTO users(Username, Password)


Note: the code for executing the query is a bit different because I’m using a php class called ezsql. As the name implies, it’s a class used to easily manipulate database which uses the standard query language to manipulate their database.

If the code above didn’t work for you, then you can always do it like this:

$uname=mysql_real_escape_string($_POST['uname']); $pword==mysql_real_escape_string($_POST['pword']); $db->query("INSERT INTO users(Uname, Hpword)




You can also use pdo’s in php. Don’t ask me what’s the meaning of pdo. Because I can’t find anything on the internet what pdo means. So if you know what it means then please leave a comment.

To keep things short, I use pdo to automatically sanitize user input without having to write any functions that will handle it.

PDO is a built in class in php, so you don’t have to download anything if you already have php installed on your computer.

Begin by creating an object of the pdo class:

$pdo=new pdo("





As I have always said the defaults are:

  • localhost -this is your local computer. This is the default for the host.
  • testdb -the database that you want to manipulate.
  • root- the default user. You can leave it as it is.
  • yourpassword- yeah this is your mysql password. Most of the time this is blank.

Then here’s an example on how to insert records in the database using pdo:

$inserts=$dbh->prepare('INSERT INTO testtable(LNAME, FNAME)

VALUES(:fname, :lname)'); $inserts->bindParam(':fname', $fname); $inserts->bindParam(':lname', $lname); $fname=$_POST['fname']; $lname=$_POST['lname']; $inserts->execute();

There’s an extensive tutorial  on how to use pdo’s. You might want to read it if you want to learn more about pdo’s.

And an article on why you should be using pdo’s



What you have just red are some of the ways that you can sanitize user input to avoid any error when performing sql queries. Knowing and applying these things into your future projects will make the data in your database more reliable. And as you can see on the pdo example, it will also make your code cleaner as you implement classes in your application.