Multiple Files Upload with PHP

In this tutorial we will make a multiple file Upload system with PHP. The system will automatically create directory if not previously created for storing uploaded files. This multiple file Upload system can be used to upload images, PDF's, Doc's or any file types.
You can also see a tutorial on Single File Upload and Jquery Ajax File Upload.

THE HTML

This is a simple HTML form containing interface for multiple file Upload system.
<html>
    <head>
        <title>Multiple Files Upload with PHP</title>
    </head>
    <body>
        <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
            <tr>
            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
                <td>
                    <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                        <tr>
                            <td><strong>Multiple Files Upload with PHP</strong></td>
                        </tr>
                        <tr>
                            <td>Select file 
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td align="center"><input type="submit" name="Submit" value="Upload" /></td>
                        </tr>
                    </table>
                </td>
            </form>
        </tr>
    </table>
</body>
</html>
Make sure to make add enctype="multipart/form-data ,type="file" and most importantly name="userfile[]" to enable multi files selection possible.

PHP

Moving on to the PHP codes. we can get started with isset($_POST['Submit']), in this we are checking if the upload button is clicked or not. If upload button is clicked then we can move further for validating and uploading files. $_FILES[' '] will contain the information of each file, but when more that one file are selected it will have the details of each file enclosed inside another array.
To access them we will be using foreach loop.
foreach($_FILES['userfile']['tmp_name'] as $key => $tmp_name ){ $file_name = $key.$_FILES['userfile']['name'][$key]; $file_size =$_FILES['userfile']['size'][$key]; $file_tmp =$_FILES['userfile']['tmp_name'][$key]; $file_type=$_FILES['userfile']['type'][$key]; }
Now we will check the size of uploaded files. If the size of any file is equal to 0 means file is not selected for upload and we through an error.
if($file_size == 0){ $errors='There is something error in your files.'; }

MOVING THE FILES

File uploaded will be allocated space in the temporary location as mentioned in the php.ini. It is necessary to move the file from the temporary location to another in order to use it again. You can get the file moved to another location using move_uploaded_file(), here we will move it to an "Upload" folder, make sure the directory exists, since move_uploaded_file() cannot create a directory. So it recommended to verify for existence of directory.
$upload_dir="upload"; move_uploaded_file($file_tmp,$upload_dir."/".$file_name);
If you plan to create a directory on the go, then you can use mkdir(DIR NAME,PERMISION)
if($file_size == 0){ $errors='There is something error in your files.'; }

FULL CODE FOR MILTIPLE FILES UPLOAD WITH PHP

You can use the following codes to upload files of any size & type.
<?php
if(isset($_POST['Submit'])){
 foreach($_FILES['userfile']['tmp_name'] as $key => $tmp_name ){
  $file_name = $key.$_FILES['userfile']['name'][$key];
  $file_size =$_FILES['userfile']['size'][$key];
  $file_tmp =$_FILES['userfile']['tmp_name'][$key];
  $file_type=$_FILES['userfile']['type'][$key]; 
   
   if($file_size == 0){
    $errors='There is something error in your files.';
   }
   $upload_dir="upload";
   if(empty($errors)==true){
    if(is_dir($upload_dir)==false){
     mkdir("$upload_dir", 0700);  // Create directory if it does not exist
    } 
     move_uploaded_file($file_tmp, $upload_dir."/".$file_name);
   }
  }
 if(empty($errors)){
  echo "Your files uploaded successfully!!!";
 }else{
   print_r($errors);
 }
}
?>
<html>
    <head>
        <title>Multiple Files Upload with PHP</title>
    </head>
    <body>
        <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
            <tr>
            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
                <td>
                    <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                        <tr>
                            <td><strong>Multiple Files Upload with PHP</strong></td>
                        </tr>
                        <tr>
                            <td>Select file 
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="userfile[]" type="file" id="userfile[]" size="50" /></td>
                        </tr>
                        <tr>
                            <td align="center"><input type="submit" name="Submit" value="Upload" /></td>
                        </tr>
                    </table>
                </td>
            </form>
        </tr>
    </table>
</body>
</html>
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Single Files Upload with PHP

In this tutorial we will make simple php file upload system with a verification for file extension and size, thus making it a secure way to upload files.
You can use this for Uploading image's ,PDF's, Doc any file types make sure you change the necessary parts in the script.
You can also see a tutorial on Multiple file upload with PHP and Jquery Ajax File Upload.

THE HTML

This is a simple HTML form containing interface for php file Upload system.
<html>
    <head>
        <title>Single Files Upload with PHP</title>
    </head>
    <body>
        <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
            <tr>
            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
                <td>
                    <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                        <tr>
                            <td><strong>Single Files Upload with PHP</strong></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="file" type="file" size="50" /></td>
                        </tr>
                        <tr>
                            <td align="center"><input type="submit" name="Submit" value="Upload" /></td>
                        </tr>
                    </table>
                </td>
            </form>
        </tr>
    </table>
</body>
</html>
Make sure to make add enctype="multipart/form-data" to form and type="file" for the input.

PHP

We will use isset($_FILES[]) to make sure some file is selected and then we will proceed for the upload.
$_FILES[' '] is an array with the file information. $_FILES[] contain temporary name, size, type, name and error information of uploaded file in an array.

$_FILES description

This is the output when sunset.jpg was uploaded. The  [name] => sunset.jpg is the name of the file. [type] => image/jpeg  is the type of the file,  [tmp_name] => C:\wamp\tmp\php26CPE.tmp  tmp_name is the temporary location where the file is uploaded , in what ever server you are running on, We will use move function to move the file to our desired location later. [error] => 0 Its the error variable, we are not using that in this tutorial, [size] => 21654 and the last one is the size of the file, we will use it to make sure that the files above the a certain limit is not uploaded.
if(isset($_FILES['file'])){
    $file_name = $_FILES['file']['name'];
    $file_size =$_FILES['file']['size'];
    $file_tmp =$_FILES['file']['tmp_name'];
    $file_type=$_FILES['file']['type'];
}
Now to get started with verification.
$extensions = array("jpeg","jpg","png"); 
In in example we are uploading an image so we need to allow the image extensions. You can add the appropriate extensions that you need.
To get the extension we will use the name as it will have the extension, to extract it we will use PHP explode() & use end(). There won't be any problem even if the file name has a dot in it.
$file_ext=explode('.',$_FILES['file']['name']) ;
$file_ext=end($file_ext);
Extensions can also be in UPPER case or LOWER case to overcome the problem we will get them converted into lower case or upper case as you mentioned in the $extensions array.
$file_ext=strtolower(end(explode('.',$_FILES['file']['name']))); 
With in_array() you can get it checked extension is present in allowed extension
if(in_array($file_ext,$extensions ) === false){
 $errors[]="extension not allowed";
} 
We will make an array to store errors and check if the error is empty or not to confirm the upload or echo out the error at the end. To check for size we can use $file_size to check but, make sure that the size is in bytes.
if($file_size > 2097152){
 $errors[]='File size must be less than 2 MB';
}
Now we have done with the verification part. Now lets move the uploaded file to another folder to user that file in future and display a confirmation message.
To move the file from the tmp_name to another location we will be using move_uploaded_file(), here we will move it to  images directory, make sure the directory exist, as move_uploaded_file() cannot create a directory.
if(empty($errors)==true){
    move_uploaded_file($file_tmp,"upload/".$file_name);
    echo "Your file uploaded successfully!!!";
}else{
 print_r($errors[]);
}

PHP SINGLE FILE UPLOAD WITH PHP


Now let's take a look at the full code once again.
<?php
if(isset($_FILES['file'])){
    $errors= array();
    $file_name = $_FILES['file']['name'];
    $file_size =$_FILES['file']['size'];
    $file_tmp =$_FILES['file']['tmp_name'];
    $file_type=$_FILES['file']['type'];
    $file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
    $extensions = array("jpeg","jpg","png");
    if(in_array($file_ext,$extensions )=== false){
     $errors[]="Extension not allowed, please choose a JPEG or PNG file.";
    }
    if($file_size > 2097152){
    $errors[]='File size must be less than 2 MB';
    }
    if(empty($errors)==true){
        move_uploaded_file($file_tmp,"upload/".$file_name);
        echo "Your file uploaded successfully!!!";
    }else{
        print_r($errors);
    }
}
?>
<html>
    <head>
        <title>Single Files Upload with PHP</title>
    </head>
    <body>
        <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
            <tr>
            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
                <td>
                    <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                        <tr>
                            <td><strong>Single Files Upload with PHP</strong></td>
                        </tr>
                        <tr>
                            <td>Select file
                                <input name="file" type="file" size="50" /></td>
                        </tr>
                        <tr>
                            <td align="center"><input type="submit" name="Submit" value="Upload" /></td>
                        </tr>
                    </table>
                </td>
            </form>
        </tr>
    </table>
</body>
</html>
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Creating a Dependent Dropdown List with PHP, jQuery and Ajax

There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. Scenarios like this can be populating a Country’s State dropdown based on the value of the Country selected, populating product sub-categories based on the parent category. In this example, we will be creating a dropdown list for category/subcategory for a product in an eCommerce website.
Dependent Dropdown List with PHP, jQuery and Ajax
Dependent Dropdown List with PHP, jQuery and Ajax

Create a database called dependent_list. We will Create 2 tables: categories and subcategories with the following queries:
CREATE TABLE IF NOT EXISTS `categories` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `category_name` VARCHAR(100) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB;
 
CREATE TABLE IF NOT EXISTS `subcategories` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `categoryID` INT(11) NOT NULL,
  `subcategory_name` VARCHAR(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Some data has been inserted into both tables as shown in database. categoryID is a foreign key in subcategories table i.e 1 category has multiple subcategories.
Create a project folder called ‘dependent_list’ in your site root folder. Create a config.php file to store the database connection and add the following code:
<?php
 
mysql_connect('localhost', 'root', '');
mysql_select_db('dependent_dropdown_list');
 
?>
Next Create an index.php file in the project folder and add the following code:
<?php 
include('config.php'); 
$query_parent = mysql_query("SELECT * FROM categories") or die("Query failed: ".mysql_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#parent_cat").change(function() {
  $.ajax({
    type: "GET",
    url: "loadsubcat.php",
    data: {id:$(this).val()}
    }).done(function( data ) {
    $("#sub_cat").html(data);
    
    });
    });
});
</script>
</head>

<body>
<form method="get">
 <label for="category">Parent Category</label>
    <select name="parent_cat" id="parent_cat">
 <option value="">Select Category</option>
        <?php while($row = mysql_fetch_array($query_parent)): ?>
        <option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
        <?php endwhile; ?>
    </select>
    <br/><br/>
  
    <label>Sub Category</label>
    <select name="sub_cat" id="sub_cat">
 <option value="">Select Parent Category</option>
 </select>
</form>
</body>
</html>

On line 3, we queried our categories table to get all categories. We then populate the parent_cat dropdownlist with the categories on lines 33-37. Whenever the dropdown value for category is changed, a jquery changed event is triggered for the category dropdown list on line 10. On lines 10-18,it sends the id value of the selected category through jquery Ajax to a php script called loadsubcat.php which then queries the subcategories table for subcategories that belongs to the parent category id value using $_GET[] super global . The values returned is now appended to the sub_cat dropdown list. We also added an animated loading gif for user experience, it is displayed when the a value is selected for the parent category and removed using a jquery “slideUp” method after the subcategory has been populated.
Lastly, create a loadsubcat.php file in the project folder and add the following code.
<?php 
include('config.php');
 
$parent_cat = $_GET['parent_cat'];
 
$query = mysql_query("SELECT * FROM subcategories WHERE categoryID = {$parent_cat}");
while($row = mysql_fetch_array($query)) {
 echo "<option value='$row[id]'>$row[subcategory_name]</option>";
}
 
?>
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Dynamically Shortened Text With "Show More" Link Using JQuery

Dynamically Shortened Text With "Show More" Link Using JQuery
 "Show More" Link Using JQuery
In this tutorial we will show you how to create jquery show more text or less text functionality for your web page or web application. If the text is larger than few characters, the extra words are hide and a show more link is presented to user. This way you can keep long text out of the view to user and stop the cluttering of page. Also interested users can click on more link and see the full content.




Here is a simple tutorial to achieve this using jQuery / JavaScript.

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed or not.
<div class="comment more">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum laoreet, nunc eget laoreet sagittis,
quam ligula sodales orci, congue imperdiet eros tortor ac lectus.
Duis eget nisl orci. Aliquam mattis purus non mauris
blandit id luctus felis convallis.
Integer varius egestas vestibulum.
Nullam a dolor arcu, ac tempor elit. Donec.
</div>
<div class="comment more">
Duis nisl nibh, egestas at fermentum at, viverra et purus.
Maecenas lobortis odio id sapien facilisis elementum.
Curabitur et magna justo, et gravida augue.
Sed tristique pellentesque arcu quis tempor.
</div>

 The CSS

Below is the CSS code for our example. Note the class “.morecontent span” is hidden. The extra text from the content is wrapped in this span and is hidden at time of page loading.
a {
color: #0254EB
}
a:visited {
color: #0254EB
}
a.morelink {
text-decoration:none;
outline: none;
}
.morecontent span {
display: none;
}
.comment {
width: 400px;
background-color: #f0f0f0;
margin: 10px;
}

 The Javascript

Below is the Javascript code which iterate through each DIV tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”.
You can change the behaviour by changing following js variables.
  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: The text shown in less link. Default is “less”. You can change to “<<"
$(document).ready(function() {
var showChar = 100;
var ellipsestext = "...";
var moretext = "more";
var lesstext = "less";
$('.more').each(function() {
var content = $(this).html();

if(content.length > showChar) {

var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);

var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

$(this).html(html);
}

});

$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
 Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Send Email using Mail() Function In PHP

In this tutorial of php we will see how mail() function in php works.
The mail() function in php allow you to send email to anyone directly from code. It return TRUE if mail is properly sent otherwise FALSE.
Example:-
<?php
$to = “info@phptutorials.co.in”;
$subject = “Php tutorial for mail function”;
$body = “PHP code for Beginners.(Body of your message)”;
$headers = ‘From: <abc@xyz.com>’ . “rn”;
$headers .= ‘MIME-Version: 1.0′ . “n”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1′ . “rn”;
mail($to,$subject,$body,$headers);
?>
Hope this php tutorial is useful for you. Keep following Php Point for more help.
Continue Reading