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.

 

Requirements

 

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>
    <button>Upload</button>
    <div>Upload files</div>
    
</form>

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.

<script>
/*global $ */
$(function () {
    $('#file_upload').fileUploadUI({
        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>' +
                    '</button></td></tr>');
        },
        buildDownloadRow: function (file) {
            return $('<tr><td>' + file.name + '</td></tr>');
        }
});
);
</script>

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 () {
                 handler.removeNode(handler.uploadRow);
             }, 10000);
             return;
         }
         
         
        
         callBack();
 }

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 () {
               handler.removeNode(handler.uploadRow);
           }, 10000);
           return;
 }

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.

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

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

image

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.

image

 

Conclusion

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.

 

Requirements

 

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.

image

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.

image

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

image

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:

image

Until you find these lines:

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

Those are the defaults. Change those to:

public $Host          = 'ssl://smtp.gmail.com';
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.

include('../../phpmailer/class.phpmailer.php');

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();  
$mail->IsSMTP();

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 = "blablabla@gmail.com"; 
$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 = "replyemail@gmail.com"; 

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

$email="recipient@gmail.com"; 

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:

$mail->AddAddress($email,$name);

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:

$mail->AddAttachment("embarassingmoments.jpg");

Then specify if the email is html.

$mail->IsHTML(true);

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:

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
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.

image

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

image

Next, restart all services.

image

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.

image

 

Conclusion

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!

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.

 

mysql_real_escape_string()

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)

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

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)

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

 

PDO’s

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("

mysql:host=localhost;

dbname=testdb",

"root",

"yourmysqlpassword");

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

 

Conclusion

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.

How to install Kohana

 

In this guide, I will show you how you can install Kohana.

 

Requirements

  • Kohana version 3.1.1.1

 

Installation

  1. Download Kohana.
  2. Create a folder on your www directory if you’re using Wamp and htdocs if you’re on Xampp.
  3. Name the folder to anything you like as long as it is easy to remember.
  4. Extract the contents of the .zip file that you downloaded earlier into the folder that you have just created.
  5. The inside of that folder should now look like this:image
  6. Open up the folder so that you will have the same screen as the screenshot above. Then open up the application folder. Then open bootstrap.php using any text editor.
  7. There are many things which you have to edit here. First is the time zone. If you’re also from the Philippines then you can use the same time zone as mine. Just use the find and replace function of the text editor to find where is this specific line of code.
date_default_timezone_set('Asia/Manila');

Next thing, specify the folder where Kohana is installed. This will depend on the folder name you have a while ago. But mine is named kohana, and it is directly after the www directory or the root directory of the web accessible folder. So it will look like this:

Kohana::init(array(
    'base_url'   => '/kohana',
));

That’s it, you should now see this screen when you try to access the url below on your browser. Of course, the kohana here will not be the same as yours if you have named yours differently.

image

You might as well enable or disable some php extensions in your wamp tray icon if you want to pass all the optional tests as well.

image

As you can see, I failed one optional test but its okay since its just optional.

 

Conclusion
That’s how you install Kohana framework. Stay tuned. Thanks!

Simple php inventory system

This is the third part of the six part series about creating a php online store.

Here’s a summary of the

Just in case, I haven’t included the download link on the database that were going to use. Here it is. Download that and import it into any database that you have created. Using phpmyadmin.

 

 

Item Creation

This would be the form that will be used by the admin to create new products.

Go ahead and type the codes below. Or just copy and paste it into your text editor:

<form action="regprodact.php"  id="info" method="post">
   <h3>Product Registration</h3>
 
 
      <label for="prodname">Product Name:</label>
      <input type="text" id="prodname" name="prodname" class="validate[required]">
 
 
      <label for="description">Description:</label>
      <input type="text" id="description" name="description" class="validate[required]">
 
 
      <label for="reorder">Reorder Qty:</label>
      <input type="text" id="reorder" name="reorder" class="validate[required,custom[onlyNumber]]">
      
 
    
      <label for="bprice">Cost price:</label>
      <input type="text" id="pprice" name="pprice" value="" class="validate[required,custom[onlyNumber]]" value="">
 
      <label for="sprice">Unit price:</label>
      <input type="text" id="sprice" name="sprice" value="" class="validate[required,custom[onlyNumber]]" value="">
  
   
      <label for="category">Category:</label>
      <input type="text" id="category" name="category"/>
 
<input type="submit" value="create"/>
</form>

It’s a good practice not to make the value of the submit button into something like ‘submit’. Because that doesn’t give the user any idea on what he is doing. Most of the time you have to make use of an action word or a verb in the value of the submit button.

Next thing that you have to do is to create a new php file and name it to regprodact.php or whatever form action you have included in the item creation form. What this will do is to insert the data that is inputted by the user into the database.

<?php include('conn.php'); ?>
 
<?php 
 
$prod=$_POST['prodname'];
$desc=$_POST['description'];
$category=$_POST['category'];
 
$reorder=$_POST['reorder'];
 
$cost_price=$_POST['pprice'];
$unit_price=$_POST['sprice'];
 

/* format the text*/
$f_prod=ucwords(strtolower($prod));
$f_desc=ucwords(strtolower($desc));
$f_category=ucwords(strtolower($category));
 
$inserts=mysql_query("INSERT INTO prod_table(PRODUCT, P_DESC, CATEGORY, REORDER_LVL, B_PRICE, S_PRICE") VALUES('$f_prod','$f_desc','$f_category', '$reorder', '$cost_price', '$unit_price')");
 
if(!$inserts){
    echo mysql_error();
}
?>

 

Item list

This will be used by the user to (surprise!) list all the items that matches the query that he is going to type in the textbox:

<form action="listprod.php" method="post">
<label for="items">Item name:</label>
<input type="text" name="items"/>
<input type="submit" value="list">
</form>

Create a new php file again, and name it to listprod.php. This is the php file that would produce the results from the user query.

<?php include('conn.php'); ?>
<?php
$item=$_POST['items'];
$list=mysql_query("SELECT * FROM prod_table WHERE PRODUCT LIKE '$item%'");
 
if(mysql_num_rows($list)==0){
 
}else{
 
?>
<table border="1">
<tr>
<th>ITEM ID</th>
<th>DESCRIPTION</th>
<th>CATEGORY</th>
<th>QTY AVAILABLE</th>
<th>REORDER LEVEL</th>
<th>COST PRICE</th>
<th>UNIT PRICE</th>
</tr>
 
<?php
while($row=mysql_fetch_assoc($list)){
?>
 
<tr>
<td><?php echo $row['PID']; ?></td>
<td><?php echo $row['PRODUCT']; ?></td>
<td><?php echo $row['P_DESC']; ?></td>
<td><?php echo $row['CATEGORY']; ?></td>
<td><?php echo $row['QTYHAND']; ?></td>
<td><?php echo $row['REORDER_LVL']; ?></td>
<td><?php echo $row['B_PRICE']; ?></td>
<td><?php echo $row['S_PRICE']; ?></td>
</tr>
</table>
<?php
}
 
}
?>

 

Updating Items

This will be used by the user to update the items that are already stored in the database. You can integrate it with the list item module so that the user can search the items that he is going to update. But of course, I’ll leave that to you so that you’ll also have something to do.

Create a new php file again and name it to updateform.php. This would be use by the user to edit the existing item data that is stored on the database. I’ll leave it as a challenge on how you can connect this module with the list module.

The following are the codes for updateform.php:

<?php include('conn.php'); ?>
<?php 
 
$item_id=$_GET['item_id']; 
 
$listupdate=mysql_query("SELECT * FROM prod_table WHERE PID='$item_id'"); 
 
 
 
/*You'll have to do the rest here*/
 
?>

Again, I’ll be leaving you with some challenge. The codes that are supposed to be placed after the comment is similar to the codes used for listing item data. The only difference is that it will only return 1 record. And were going to make use of textbox instead of a table. Remember that a text box should be inside a form tag, and the form tag should have 2 attributes: action and method.

 

Now, you have to create another php file and name it to whatever form action you have indicated in updateform.php. Here are the codes:

<?php
/*Something is missing in this part, I wonder what it is? */
 
$pid=$_POST['prodid'];
$prod=$_POST['prodname'];
$desc=$_POST['description'];
$category=$_POST['category'];
 
 
$qtyonhand=$_POST['qtyonhand'];
$pprice=$_POST['pprice'];
$sprice=$_POST['sprice'];
$reorder=$_POST['reorder'];
 
/* format the text*/
$f_prod=ucwords(strtolower($prod));
$f_desc=ucwords(strtolower($desc));
$f_category=ucwords(strtolower($category));
 
$update_item=mysql_query("UPDATE prod_table SET PRODUCT='$f_prod', P_DESC='$f_desc', CATEGORY='$f_category' , QTYHAND='$qtyonhand', B_PRICE='$pprice', S_PRICE='$sprice', REORDER_LVL='$reorder' WHERE PID='$pid'");
 
if(!$update_item){
    echo mysql_error();
}
 
?>

 

Deleting Items

The last module that were going to create in this tutorial.  I’m getting lazy now, so here’s the query. Remember to do some housekeeping. This is not the full code:

DELETE FROM prod_table WHERE PID='$pid'

Changed my mind. This module should also be connected to the list item module. The most common that people do is to add a delete icon on the table that has the items listed on it. And put a link on that icon to whatever the name of the php file which performs the delete query. Add something like this to your list module:

<a href="delprod.php?itemid=<?php echo $row['PID']; ?>">

<img src="deleteicon.png"></img></a>

Common sense tells us that this link would yield a GET method. So here’s the more complete code on delprod.php or whatever you call it on the link that you have created:

<?php
$item_id=$_GET['itemid'];
 
$deletes=mysql_query("DELETE FROM prod_table WHERE PID='$item_id'");
 
/*do some housekeeping here*/
?>

You might have notice that the parameter for the GET method should be the same as the variable that you have declared on your url. In this case it is ‘itemid’. Always remember that since the code won’t work if they are not the same.

 

Conclusion

That’s it for the inventory tutorial. Next time I’m going to tell you about the cart. The meat of this six part tutorial series.

Building an online store in php

In this series I’m going to show you how you can create an online store in php. Something like e-bay, or Amazon. But remember I’m just going to show you the basics of creating an online store. Were not actually going to create the next e-bay or amazon.

 

Things I won’t include

  • Pay-pal integration – I myself have no idea how to integrate pay-pal or any other third party that the clients will use to pay the items that they’re going to buy from the sites.
  • Customized products displayed for clients – We will not be tackling how to display custom products on every client page. If that’s not clear to you, I’m referring to product suggestions. For example, Customer A. Always buys blank dvd’s from the online store. I will not tackle how display the dvd’s on the client page. Something like a shortcut so that the client won’t search for the product everytime he buys from the store. Again, I won’t show you how to do that. But you can do a research and do it your self.
  • Hosting –  I absolutely won’t include this. Since I myself, don’t know how to apply for paid-hosting. And I don’t have a pay-pal account.

 

Modules were going to create

  • Login system – This would be used by the clients, employees, administrators to login to the system. Privileges for those users will be different from each other. There are limits to what they can do with the system.
  • Inventory- This is would be used by the administrator to determine what products need to be reordered, what products are out of quantity, etc. This also includes managing the product records, updating, deleting, and creating new products.
  • Cart – This will be used by clients to interact with the system. This is the module that they’re going to  use to buy items that are added by the administrator.
  • Purchasing-  This will be used by the administrator to add quantity to products that are below the reorder level.
  • Reports- Will be used by the administrator to gain an insight about what products are sold regularly. And what products are not sold.

On the next part of this series, I’ll discuss about the login system.