Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

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

Jquery Ajax File Upload Example in Php

In current world while making website or an application, the file uploading is one of the important requirement through front end or back end(Admin panel). Jquery and Ajax moved web development to the next level. Today no one want to upload files through traditional fashion or wait till page get reloaded completely after upload.
So here we will show you how to create your Jquery Ajax file upload application in php so that you don’t need to wait for page reload.
Jquery Ajax File Upload in Php
Jquery Ajax File Upload in Php
Here is the Download link for “Jquery Ajax File Upload in Php Tutorial”.



Creating Jquery Ajax file upload in php require 2 step procedure.

Step 1:- You need to create “index.html” file which contain code of front end to upload your files.
<html>
<head> <title>jQuery Ajax File Upload Example in PHP – Demo</title> <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js”></script> <script src=”http://malsup.github.com/jquery.form.js”></script> <link rel=”stylesheet” type=”text/css” href=”style.css” /> <script> $(document).ready(function() { var options = { target: ‘#message’, beforeSubmit: function() { $(“#progress”).show(); $(“#bar”).width(’0%’); $(“#message”).html(“”); $(“#percent”).html(“0%”); if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$(‘#ajaxUpload’).val()) //check empty input filed { $(“#message”).html(“<font color=’red’>Please select the file to upload!!!</font>”); return false; } var fileSize = $(‘#ajaxUpload’)[0].files[0].size; //get file size var fileType = $(‘#ajaxUpload’)[0].files[0].type; // get file type //allow file types switch(fileType) { case ‘image/png’: case ‘image/gif’: case ‘image/jpeg’: case ‘image/pjpeg’: case ‘text/plain’: case ‘text/html’: case ‘application/x-zip-compressed’: case ‘application/pdf’: case ‘application/msword’: case ‘application/vnd.ms-excel’: case ‘video/mp4′: break; default: $(“#message”).html(“<font color=’red’><b>”+fileType+”</b> Unsupported file type!</font>”); return false } //Allowed file size is less than 5 MB (1048576) if(fileSize>5242880) { $(“#message”).html(“<font color=’red’><b>Too big file!</b> <br />File should be less than 5 MB.</font>”); return false; } $(“#message”).html(“”); } else { //Output error to older unsupported browsers that doesn’t support HTML5 File API $(“#message”).html(“Please upgrade your browser, because your current browser lacks some new features we need!”); return false; } }, uploadProgress: function(event, position, total, percentComplete) { $(“#bar”).width(percentComplete+’%’); $(“#percent”).html(percentComplete+’%’); }, success: function() { $(“#bar”).width(’100%’); $(“#percent”).html(’100%’); }, complete: function(response) { $(“#message”).html(“<font color=’green’>”+response.responseText+”</font>”); }, error: function() { $(“#message”).html(“<font color=’red’> ERROR: unable to upload files</font>”); }, resetForm: true }; $(‘#jqueryAjaxForm’).submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); </script> </head> <body> <div class=”main-wrapper”> <form id=”jqueryAjaxForm” name=”jqueryAjaxForm” action=”upload.php” method=”post” enctype=”multipart/form-data”> <h1 class=”page_header”>Jquery Ajax File Upload Example</h1> <input type=”file” size=”60″ name=”ajaxUpload” id=”ajaxUpload”> <input type=”submit” value=”Upload” id=”submit-btn”> </form> <div id=”progress”> <div id=”bar”></div> <div id=”percent”>0%</div > </div> <div id=”message” class=”msg”></div> </div> <br/> </body> </html>
Step 2:- In this step create a “upload.php” file which contain codes to move your file from temporary directory to specified directory.
<?php

    //In below line we are specifying the path/name of folder where uploaded image get stored.

    $output_dir = “uploads/”;

    if (isset($_FILES["ajaxUpload"])) {

        if ($_FILES["ajaxUpload"]["error"] > 0) {

            echo “Error Occured: ” . $_FILES["file"]["error"] . “<br>”;

        } else {

    //Below we are moving uploaded file from temporary directory to specified directory.

            move_uploaded_file($_FILES["ajaxUpload"]["tmp_name"], $output_dir . $_FILES["ajaxUpload"]["name"]);

            echo $_FILES["ajaxUpload"]["name"].” Successfully Uploaded.”;

        }

    }

?>
Thats it. No need to do any extra stuff now and your Jquery Ajax file upload application is ready to use.

Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Simple jQuery Ajax Comment System in Php

Simple jQuery Ajax Comment System in Php
Simple jQuery Ajax Comment System in Php
It looks very annoying when we submit comment and wait till the whole page gets load to check our comments added successfully. But what if don’t want to refresh/reload the page after submitting our comments? Here the solution is jQuery Ajax comment box. 
In this tutorial of PHP Tutorials for Beginners I will show you how to create Comment box without refreshing page with jQuery Ajax and Php. We will use jQuery Ajax for comment system so that the page will not refresh while adding or updating comment.

Please follow step by step to create jQuery Ajax Comment box with Php. 

Step 1:- First step is to create a table in you database. We have create as "comments" table in our example.

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `post_id` int(5) NOT NULL,
  `name` varchar(20) NOT NULL,
  `email` varchar(10) NOT NULL,
  `comment` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
Step 2:- Next step is to create our config.php file which will contain your database connection code.
<?php $database = “practice”; // the name of the database. $server = “localhost”; // server to connect to. $db_user = “root”; // mysql username to access the database with. $db_pass = “”; // mysql password to access the database with. $table = “comments”; // the table that this script will set up and use. $link = mysql_connect($server, $db_user, $db_pass); mysql_select_db($database, $link); ?>
Step 3:- Now the next step is to create an index.php page which contain your Front end Comment box code.
<script type=”text/javascript” src=”jquery.js”></script>
<script type=”text/javascript” src=”common.js”></script>
<link rel=”stylesheet” type=”text/css” href=”style.css” />
<?php
/* Including database connection file. */
include(‘config.php’);
session_start();
/*
  The below SESSION is very important step.
  Here we have stored post id into session,
  which is used while inserting and fetchig data from database.
  I have used static id ie “1″. So please replace this with your POST ID.
 */
$_SESSION['postid'] = 1;
?>

<!–
The below “Write Your Comment” link will use to show Ajax Comment Box on clicking on it.
–>
<h3 class=”comment form-signin”><a href=”#” onclick = “show_comment_box();”>Write Your Comments</a></h3>

<!–
The below div will show the Ajax Comment Box.
Initially I have made Ajax Comment Box hidden.
If you want to show it on page load it self then remove the style=”display: none;” line from it.
–>
<div class=”comment_box container login form-signin” style=”display: none;”>
     <div>
        <div>
            <input type=”text” class = “name” value=”Enter your name” name=”” onblur=”if(this.value == ”){this.value =’Enter your name’}” onfocus=”if(this.value == ‘Enter your name’) {this.value=”}” />
        </div>
        <div>
            <input type=”text” class = “email” value=”Enter your email” name=”” onblur=”if(this.value == ”){this.value =’Enter your email’}” onfocus=”if(this.value == ‘Enter your email’) {this.value=”}” />
        </div>
        <textarea onblur=”if(this.value == ”){this.value =’Enter your comment’}” onfocus=”if(this.value == ‘Enter your comment’) {this.value=”}”  class = “user_comment”  rows=”5″ cols=”60″ name=””>Enter your comment</textarea>
    </div>
    <span><a onclick=”submit_review()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Submit</a></span> |
    <span><a onclick=”cancel()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Cancel</a></span>
    <input type=”hidden” id=”post_id” value=”<?php echo $_SESSION['postid']; ?>” />
</div>

<!–
The below div will show the successful message after comment is added into database.
–>
<div class=”message”></div>

<!–
The below div will show the list of all comments for that perticular post.
–>
<div class=”comment_list form-signin”>
     <h3>User’s Comment on this Article:-</h3>
         <?php
         $query = “SELECT * FROM comments where post_id = ”.$_SESSION['postid'];
         $result = mysql_query($query);
         while ($res = mysql_fetch_array($result)) {
             ?>
        <label style=”font-size:18″>Name:-<?php echo $res['name']; ?></label>
        <label>Comment:-<?php echo $res['comment']; ?></label><br>
<?php } ?>
</div>
Step 4:- Now the next step is to make "common.js" page which we have included in index.php. This file contain all the functions and ajax request which are called while commenting.
function show_comment_box(){
        $(“.comment_box”).show();
    }

    function submit_review(){
        /*
        In below code we have first stored the values of post id,name,email and comment in some varialbles.
         */
        var id = $(‘#post_id’).val();
        var name = $(‘.name’).val();
        var email = $(‘.email’).val();
        var comment = $(‘.user_comment’).val();
        /*
        In below code we checking if user have entered all feilds or not?
         */
        if(comment != “Enter your comment” && name != “Enter your name” && email != “Enter your email”){
            $(‘body’).css(‘cursor’, ‘progress’);
          /*
            In below code we are passing the data to external url which contain the code to add our inputs into database.
           */
            $.ajax({
                type: “POST”,
                url: “http://localhost/ajax_comment_box/add_comment.php”,
                data: { pid:id,user_name:name, user_email:email, user_comment:comment}
            }).done(function( result ) {
                setTimeout( function(){
                    if(result == “”){
                        $(“.message”).html(“Your comment is added successfully.”);
                        $(‘.comment_list’).fadeOut([30]).load(‘http://localhost/ajax_comment_box/reload_comment.php’).fadeIn([10]);
                        $(“.name”).val(‘Enter your name’);
                        $(“.email”).val(‘Enter your email’);
                        $(“.user_comment”).val(‘Enter your comment’);
                        $(“.comment_box”).hide();
                        $(‘body’).css(‘cursor’, ‘auto’);
                    }
                }, 2000);
            });
        }else{
            alert(“Please fill all the field!!!”);
        }
    }

    function cancel(){
        $(“.comment_box”).hide();
        $(“.name”).val(‘Enter your name’);
        $(“.email”).val(‘Enter your email’);
        $(“.user_comment”).val(‘Enter your comment’);
    }
Step 5:- This is the second last step while creating jQuery Ajax Comment Box. In this step we will create file called "add_comment.php". This file will be called when ajax request is made after submitting comment and it will insert the data into database.
<?php
    include(‘config.php’);
    $post_id = $_POST['pid'];
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $comment = $_POST['user_comment'];
    $query = “INSERT INTO comments(post_id, name, email, comment) VALUES(‘$post_id ’,’$name ’,’$email ’,’$comment’)”;
    mysql_query($query) or die (“MySQL Error.”);
?>
Step 6:- This is the last step of jQuery Ajax Comment Box. In this step we will create file called "reload_comment.php". After successful data insertion we need to update the comment list, so "reload_comment.php" will be called at that time and it will update the comments without refreshing the page.
<?php
    session_start();
    include(“config.php”);
    $query = “SELECT * FROM comments where post_id=”.$_SESSION['postid'];
    $result = mysql_query($query);
    while($res=mysql_fetch_array($result)){ ?>
    <div style=”font-size:18″>Name:-<?php echo $res['name']; ?></div>
    <div>Comment:-<?php echo $res['comment']; ?></div><br>
<?php } ?>
Hope this php tutorial is useful for you. Keep following Php Point for more examples.
Continue Reading

Checking USER AGENT of Client in Php

In this tutorial for PHP Point - A Tutorial for Beginners we will show you the example of checking user agent in PHP.
The first question will be WHAT IS USER AGENT?
It is a software that is acting on behalf of user. Let’s take browser Example, when you are using your browser for surfing at that time it’s your USER AGENT. If you are working on Google Chrome then your USER AGENT will be “CHROME”, if you are using Mozilla Firefox then your user agent will be “Mozilla”. The USER AGENT values of particular request not only contain browser details but also it include your platform details.

Suppose you are making some project and at particular situation you want some code to be run only on Mozilla Firebox. In that situation you need to add following code in your page.
Example:-
if(strpos($_SERVER['HTTP_USER_AGENT'],’Firefox’))
{
 //Your Firefox code
}
This code will fetch the USER AGENT details of user and our “strpos” function will check whether “Firefox” is present or not in that code. If it return true then your code for Mozilla Firefox browser will be executed.

Similarly you can also check the platform of user.
Example:-
if(strpos($_SERVER['HTTP_USER_AGENT'],’iPhone’))
{
 //Your iPhone code
}

Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Download & save a remote image on your server using PHP

In this tutorial of Php Tutorials for Beginners we will show you how to download and save images from remote server to your server.
To download and save images from remote server to your server we need 2 php file functions.

1 - file_get_contents()
This function is the used to read the contents of a file into a string.
Syntax:-
file_get_contents("URL")
Here URL is path of file to read.

2 - file_put_contents()
This function is the used to writes a string to a file.
Syntax:-
file_put_contents(file,data,mode,context)
Here file and data are required fields.

Example:-
$image = file_get_contents('http://www.any_url.com/image.jpg');
file_put_contents('/images/new_image_name.jpg', $image); //save the image on your server
Hope this php tutorial is useful for you. Keep following Php Point for more Codes.
Continue Reading

Multiple Checkbox Select/Deselect using jQuery

In this tutorial of PHP Point - A Tutorial for Beginners we will show you the implementation of multiple select and deselect checkbox functionality with the use of jquery. Here if we check top checkbox then all the checkbox below it get automatically selected and vice versa.
Multiple Checkbox Select/Deselect using jQuery
Multiple Checkbox Select/Deselect using jQuery
Here is the sample code to implement "Checkbox Select/Deselect Functionality with Jquery".
<HTML>
    <HEAD>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <TITLE>Multiple Checkbox Select/Deselect - Example</TITLE>
        <SCRIPT language="javascript">
            $( document ).ready(function() {
                $("#checkall").click(function () {
                    $('.option').attr('checked', this.checked);
                });
                $(".option").click(function(){
                    if($(".option").length == $(".option:checked").length) {
                        $("#checkall").attr("checked", "checked");
                    } else {
                        $("#checkall").removeAttr("checked");
                    }
                });
            });
        </SCRIPT>
    </HEAD>
    <BODY>
        <div class="main-wrapper">
            <H2 class="page_header">Multiple Checkbox Select/Deselect</H2>
            <table width="100%" class="table">
                <tr>
                    <th><input type="checkbox" id="checkall"/></th>
                    <th>Topics</th>
                </tr>
                <tr>
                    <td align="center"><input type="checkbox" class="option" name="login" value="1"/></td>
                    <td><a href="http://phptutorialforbeginners.com/2012/10/php-simple-login-form-php-tutorial-for.html">Php Login Form</a></td>
                </tr>
                <tr>
                    <td align="center"><input type="checkbox" class="option" name="ajax" value="2"/></td>
                    <td><a href="http://phptutorialforbeginners.com/2013/01/jquery-ajax-tutorial-and-example-of.html">Jquery Ajax Example</a></td>
                </tr>
                <tr>
                    <td align="center"><input type="checkbox" class="option" name="download" value="3"/></td>
                    <td><a href="http://phptutorialforbeginners.com/2013/04/file-download-script-in-php-php.html">File Download Script</a></td>
                </tr>
                <tr>
                    <td align="center"><input type="checkbox" class="option" name="upload" value="4"/></td>
                    <td><a href="http://phptutorialforbeginners.com/2014/02/jquery-ajax-file-upload-example-in-php.html">Ajax File Upload</a></td>
                </tr>
            </table>
        </div>
    </BODY>
</HTML>
Hope this php tutorial is useful for you. Keep following  Php Point for more Codes.
Continue Reading

Creating ZIP File with PHP

Creating ZIP File with PHP
PHP is great platform and provide many features. It provide list of classes which make our job easy. Among the list of classes it has class which provides extension to make zip of files. This extension enables you to transparently read or write ZIP compressed archives and the files inside them. This feature helps you while downloading multiple files in Zip compressed archives.

In this tutorial we will show you how to create and download files or multiple files in Zip compressed archives with Php. Below are the steps for "Creating ZIP File with PHP".

Step 1:- Create an index.php page with HTML code that contains list of files with input type checkbox name files[]. 
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css" />
        <title>Download As Zip</title>
    </head>
    
    <body>
        <div class="main-wrapper">
            <center><h1 class="page_header">Create and Download Zip</h1></center>
            <form name="creat_zip" method="post">
                <?php if (!empty($error)) { ?>
                    <p class="error"><?php echo $error; ?></p>
                <?php } ?>
                <table class="table">
                    <tr>
                        <td><b>Select Files</b></td>
                        <td><b>File Type</b></td>
                        <td><b>File Name</b></td>
                    </tr>
                    
                    <tr>
                        <td align="center"><input type="checkbox" name="files[]" value="Chrysanthemum.jpg" /></td>
                        <td align="center"><img src="files/image.png" title="Image" /></td>
                        <td>Chrysanthemum.jpg</td>
                    </tr>

                    <tr>
                        <td align="center"><input type="checkbox" name="files[]" value="Desert.jpg" /></td>
                        <td align="center"><img src="files/image.png" title="Image" /></td>
                        <td>Desert.jpg</td>
                    </tr>

                    <tr>
                        <td align="center"><input type="checkbox" name="files[]" value="Hydrangeas.jpg" /></td>
                        <td align="center"><img src="files/image.png" title="Image" /></td>
                        <td>Hydrangeas.jpg</td>
                    </tr>

                    <tr>
                        <td colspan="3" align="center">
                            <input type="submit" name="download_zip" value="Download as ZIP" id="submit-btn" />
                            <input type="reset" name="reset" value="Reset" id="reset-btn"/>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
</html>
Step 2:- Add PHP code in above fiel to covert the selected files into ZIP file format.
<?php
$error = ""; //error holder
if (isset($_POST['download_zip'])) {
    $post = $_POST;
    $file_folder = "files/"; // folder to load files
    if (extension_loaded('zip')) {// Checking ZIP extension is available
        if (isset($post['files']) and count($post['files']) > 0) {// Checking files are selected
            $zip = new ZipArchive(); // Load zip library
            $zip_name = time() . ".zip"; // Zip name
            if ($zip->open($zip_name, ZIPARCHIVE::CREATE) !== TRUE) {// Opening zip file to load files
                $error .= "* Sorry ZIP creation failed at this time<br/>";
            }
            foreach ($post['files'] as $file) {
                $zip->addFile($file_folder . $file); // Adding files into zip
            }
            $zip->close();
            if (file_exists($zip_name)) {
// push to download the zip
                header('Content-type: application/zip');
                header('Content-Disposition: attachment; filename="' . $zip_name . '"');
                readfile($zip_name);
// remove zip file is exists in temp path
                unlink($zip_name);
            }
        }else
            $error .= "Please select file to zip <br/>";
    }else
        $error .= "You dont have ZIP extension<br/>";
}
?>
Hope this php tutorial is useful for you. Keep following PHP Point for more Codes.
Continue Reading

Database Connection in Php

After knowing the basic structure of php, next step is how to connect to the mysql database. To perform basic queries from within MySQL is very easy.This tutorial of Php Point will show you mysql database connection in php.
The first thing to do is connect to the database. To connect to mysql database we use function mysql_connect().

Syntax of mysql_connect():-
mysql_connect(hostname, username, password);

Here "hostname" is name of your host(like 'localhost'), "username" is username of your host(For localhost it is 'roo') and "password" is password of your host site(Default is '').
Example:-
<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
    $conn = mysql_connect($hostname, $username, $password) or die("Unable to connect");
    echo "Connected to MySQL";
?>
After successfull connection you should see "Connected to MySQL" when you run this script. If you can't connect to the server, make sure your password, username and hostname are correct.
Now we have created connection object, next step is to select a database to work with. To select database we use function mysql_select_db() with connection object.
Example:-
<?php
    //selecting a database with name phptutorials.
    $database = mysql_select_db("phptutorials", $conn) or die("Could not select phptutorials");
?>
Now database is selected, let's try and run some queries. The function used to perform queries is named - mysql_query(). The function returns a resource that contains the results of the query, called the result set. To examine the result we're going to use the mysql_fetch_array function, which returns the results row by row.
Example:-
<?php
    $result = mysql_query("SELECT id, name, address FROM students");
    while ($row = mysql_fetch_array($result)) {
        echo "ID:" . $row{'id'} . " Name:" . $row{'name'} . " Address:" . $row{'year'} . "<br>";
    }
?>
//Finally, we close the connection.
<?php
    mysql_close($conn);
?>
Here is the full code:
<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";

    //connection to the database
    $conn = mysql_connect($hostname, $username, $password) or die("Unable to connect");
    echo "Connected to MySQL";

    //select database phptutorials
    $database = mysql_select_db("phptutorials", $conn) or die("Could not select phptutorials");

    //execute the SQL query and return records
    $result = mysql_query("SELECT id, name, address FROM students");

    //fetch tha data from the database
    while ($row = mysql_fetch_array($result)) {
        echo "ID:" . $row{'id'} . " Name:" . $row{'name'} . " Address:" . $row{'year'} . "<br>";
    }
    //close the connection
    mysql_close($conn);
?>
Continue Reading

PHP Login Form or PHP Login System

Php Login form
PHP Login Form or Login Script in PHP!!!
If you know how to create website in php and you started creating any php web site that allow user or admin to login then first thing comes in your mind is to create php login script or login form in php that allow user or admin to get login. For login the user must have their respective username and password which he enters in to login form page. To make his successful login we verified his username and password with MySQL database table which contain the username and password for all.

In this tutorial of php point we will show you step by step creation of your first php login form or php script for login. Basically we create one simple login form in html and connect this code with MySQL database and php script.

You can also use the JavaScript validation or jquery validation for your login php form.

Logic:-
1 – First we make signup or registration form to create username and password for login.
In Signup process we check if entered username is already existing in our database then we prompt error message else allow him to create an account.

2 - Now the Second step is creating your Login Page.
If user is registered then allow him to login into home page else prompt error message.

3 - If User is registered user i.e. username password exists in database then before redirecting him into home page we save his username in SESSION.
We use this SESSION variable in our home page to check whether user is logged in or not? If it is session variable is set then allow him to access the content of home page else redirect to login page.

4 - Last step is adding logout button. When user click on logout button we will unset or clear the session variable and redirect him to login page.
Files:-
1 - signup.php (Used for signup or registration process)
2 - login.php (Used for user login)
3 - home.php (User home page after login)
4 - logout.php (Used for logout purpose)
5 - config.php (Contain database connection code)
6 - style.php (For styling the pages)

Step 1:- Create a table "users" with the code below:

User Table for php login form



CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(10) NOT NULL,
  `lastname` varchar(20) NOT NULL,
  `username` varchar(16) DEFAULT NULL,
  `password` char(50) DEFAULT NULL,
  `email` varchar(20) NOT NULL,
  `is_active` int(1) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
Step 2:- Create a config.php file and put below code in it.
<?php
    $database = "mydata";  // the name of the database.
    $server = "localhost";  // server to connect to.
    $db_user = "root";  // mysql username to access the database with.
    $db_pass = "";  // mysql password to access the database with.
    $table = "users";    // the table that this script will set up and use.
    $link = mysql_connect($server, $db_user, $db_pass);
    mysql_select_db($database, $link);
?>
Step 3:- Create "signup.php" file and add below code in it.
User Sign up page
Sign Up Form
<?php
include("config.php"); //including config.php in our file
//
// Now checking user name and password is entered or not.
if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['email'])) {

    $first_name = mysql_real_escape_string($_POST['firstname']);
    $last_name = mysql_real_escape_string($_POST['lastname']);
    $username = mysql_real_escape_string(stripslashes($_POST['username']));
    $password = mysql_real_escape_string(stripslashes(md5($_POST['password'])));
    $mail = mysql_real_escape_string($_POST['email']);
    $check = "SELECT * from users where username = '" . $user . "'";
    $qry = mysql_query($check);
    $num_rows = mysql_num_rows($qry);

    if ($num_rows > 0) {  // Here we are checking if username is already exist or not.
        echo "The username you have entered is already exist. Please try another username.";
        echo '<a href="signup.php">Try Again</a>';
        exit;
    }

// Now inserting record in database.
    $query = "INSERT INTO users (firstname,lastname,username,password,email,is_active) VALUES ('" . $first_name . "','" . $last_name . "','" . $username . "','" . $password . "','" . $mail . "','1');";
    mysql_query($query);
    echo "Thank You for Registration.";
    echo '<a href="login.php">Click Here</a> to login you account.';
    exit;
}
?>
<html>
    <head>
        <title>Registration Page | Simple login form</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
        <div id="containt" align="center">
            <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-signup">
                <div id="header"><h2 class="sansserif">Create an account</h2></div>
                <table>
                    <tr>
                        <td>Select Your Firstname:</td>
                        <td> <input type="text" name="firstname" size="20" placeholder="First name"><span class="required">*</span></td>
                    </tr>
                    
                    <tr>
                        <td>Select Your Lastname:</td>
                        <td> <input type="text" name="lastname" size="20" placeholder="Last name"><span class="required">*</span></td>
                    </tr>

                    <tr>
                        <td>Select Your Username:</td>
                        <td> <input type="text" name="username" size="20" placeholder="User name"><span class="required">*</span></td>
                    </tr>

                    <tr>
                        <td>Select Your Password:</td>
                        <td><input type="password" name="password" size="20" placeholder="Password"><span class="required">*</span></td>
                    </tr>

                    <tr>
                        <td>Select Your Email:</td>
                        <td> <input type="text" name="email" size="20" placeholder="Email"><span class="required">*</span></td>
                    </tr>

                    <tr>
                        <td><input type="submit" value="Sign Up" class="btn btn-large btn-primary"></td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
</html>
Step 4:- Create "login.php" file with following code.
Php Login form
Login Page
<?php
if (isset($_POST) && !empty($_POST)) {
    session_start();
    include("config.php"); //including config.php in our file
    $username = mysql_real_escape_string(stripslashes($_POST['username'])); //Storing username in $username variable.
    $password = mysql_real_escape_string(stripslashes(md5($_POST['password']))); //Storing password in $password variable.
    $match = "select id from $table where username = '" . $username . "' and password = '" . $password . "';";
    $qry = mysql_query($match);
    $num_rows = mysql_num_rows($qry);

    if ($num_rows <= 0) {
        echo "Sorry, there is no username $username with the specified password.";
        echo "Try again";
        exit;
    } else {
        $_SESSION['user'] = $_POST["username"];
        header("location:home.php");    // It is the page where you want to redirect user after login.
    }
} else {
    ?>
    <html>
        <head>
            <title>Login</title>
            <link rel="stylesheet" type="text/css" href="style.css" />
        </head>
        <body>
            <div class="container login">
                <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" class="form-signin" id = "login_form" >
                    <h2 class="form-signin-heading">Admin/Employee Login</h2>
                    <input type="text" name="username" size="20" placeholder="Username">
                    <input type="password" name="password" size="20" placeholder="Password"></br>
                    <input type="submit" value="Log In" class="btn btn-large btn-primary">
                    <a href="signup.php">Sign Up</a>
                </form>
            </div>
        </body>
    </html>
    <?php
}
?>
Step 5:- Create "home.php" file with following code.
<?php
    session_start();

    if (isset($_SESSION['user']) && !empty($_SESSION['user'])) {
        echo "You are Welcome " . $_SESSION['user'];
?>
        <a href = "logout.php">Logout</a>
<?php
    } else {
        header("location:login.php");
    }
?>
Step 6:- Create "logout.php" file with following code.
<?php
    session_start();
    session_destroy();
    header("location:login.php");
?>
Now your PHP login form is ready to use.

Hope this php tutorial is useful for you. Keep following Php Point for more help.
Continue Reading