Showing posts with label MySQL. Show all posts

Wednesday, January 25, 2017

Ajax jQuery File Upload with Codeigniter using BlueImp with image preview

Hello friends, are you looking for ajax based jquery file upload using codeiginter. Then here is tutorial for you. In this tutorial we will discuss about File Uploading using PHP Codeigniter and Jquery with ajax. Blueimp file upload gives you a best option for file uploading. I found this script very useful for my projects and I would like to share this information with you. Blueimp is a free open source code.

Why Blueimp?

Blueimp is a file upload widget which can be used for multiple file uploads with validations and is highly secured. It also supports cross domain, chunked and resumable file uploads. It can be used for image, audio, video etc., It has a progress bar shown for each image and supports drag and drop. It works with any server side platform such as Google App Engine, PHP, Python, Ruby on Rails, Java etc., However in this tutorial we are going to discuss about PHP and Codeigniter.

Demo


Blueimp with codeigniter

As we already discussed that Blueimp supports PHP, so we can use with Codeigniter too. Blueimp wiki says that you can easily integrate this script with Codeigniter but when I tried to work with it I found it very hard to do. I made it simpler and will share it with you.

How to integrate Blueimp with Codeigniter?

Open constants.php file in config folder and add the below given code in it. You can add it at the bottom of the code in constants.php

// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

Now create a new php file using any text editor and add the following code to it.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Upload extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url', 'file'));
    }}
 public function do_upload() {
        $upload_path_url = base_url() . 'files/';
//you should create a folder uploads in the root directory of your codeigniter
        $config['upload_path'] = FCPATH . 'files/';
  //to allow only image files of below type
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
  //max size to upload else return error message. change it to more if you want to allow large files
        $config['max_size'] = '50000';

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload()) {
           

            //Load the list of existing files in the upload directory
            $existingFiles = get_dir_file_info($config['upload_path']);
            $foundFiles = array();
            $f=0;
            foreach ($existingFiles as $fileName => $info) {
              if($fileName!='thumbnails'){//Skip over thumbnails directory
                //set the data for the json array   
                $foundFiles[$f]['name'] = $fileName;
                $foundFiles[$f]['size'] = $info['size'];
                $foundFiles[$f]['url'] = $upload_path_url . $fileName;
                $foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbnails/' . $fileName;
                $foundFiles[$f]['deleteUrl'] = base_url() . 'upload/deleteImage/' . $fileName;
                $foundFiles[$f]['deleteType'] = 'DELETE';
                $foundFiles[$f]['error'] = null;

                $f++;
              }
            }
            $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array('files' => $foundFiles)));
        } else {
            $data = $this->upload->data();
            
            // to re-size for thumbnail images un-comment and set path here and in json array
            $config = array();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $data['full_path'];
            $config['create_thumb'] = TRUE;
            $config['new_image'] = $data['file_path'] . 'thumbnails/';
            $config['maintain_ratio'] = TRUE;
            $config['thumb_marker'] = '';
            $config['width'] = 300;
            $config['height'] = 100;
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();


            //set the data for the json array
            $info = new StdClass;
            $info->name = $data['file_name'];
            $info->size = $data['file_size'] * 1024;
            $info->type = $data['file_type'];
            $info->url = $upload_path_url . $data['file_name'];
            // I set this to original file since I did not create thumbnails.  change to thumbnail directory if you do = $upload_path_url .'/thumbnails' .$data['file_name']
            $info->thumbnailUrl = $upload_path_url . 'thumbnails/' . $data['file_name'];
            $info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['file_name'];
            $info->deleteType = 'DELETE';
            $info->error = null;

            $files[] = $info;
            //this is why we put this in the constants to pass only json data
            if (IS_AJAX) {
                echo json_encode(array("files" => $files));
                //this has to be the only data returned or you will get an error.
                //if you don't give this a json array it will give you a Empty file upload result error
                //it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
                // so that this will still work if javascript is not enabled
            } else {
                $file_data['upload_data'] = $this->upload->data();
                $this->load->view('upload/upload_success', $file_data);
            }
        }
    }
 public function deleteImage($file) {//gets the job done but you might want to add error checking and security
        $success = unlink(FCPATH . 'files/' . $file);
        $success = unlink(FCPATH . 'files/thumbnails/' . $file);
        //info to see if it is doing what it is supposed to
    $info = new StdClass;
        $info->sucess = $success;
        $info->path = base_url() . 'files/' . $file;
        $info->file = is_file(FCPATH . 'files/' . $file);

        if (IS_AJAX) {
            //I don't think it matters if this is set but good for error checking in the console/firebug
            echo json_encode(array($info));
        }
    }

Saturday, June 7, 2014

How to send activation link to email on user registration in PHP (Email verification)

During user registration in order to verify the email address of the user, a confirmation email is sent to the provided email address with activation link and when user clicks the link provided in the mail, his account gets activated. If you are looking for such PHP code. Then read this tutorial carefully.

This is a basic code to implement email verification using PHP and MySQL. In this code I have shown how to get a link to user email. The link actually contains an id which is stored in the database for each user. Here we use PHP mail() function to send an email to the user after registration.
You may also read:

PHP contact form using mail function using JQuery toggle. 

Beautiful contact form in PHP. 

Here is the MySQL query to create users table with five columns id, name, email, password and status. We are using the first column "id" in activation link and status contains whether the user has been activated or not.
Dump the below sql code into your MySql database.
CREATE TABLE IF NOT EXISTS `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(70) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '0',
   PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Follow the below given steps.
Step 1. Look How to connect MySql database using PHP and copy the full PHP code from the block and save the file as db.php.

Step 2. Copy the below code and save it as register.php
<form action="" method="post" >
    <label>Name</label>
    <input type="text" name="name" >
    <label>Email</label>
    <input type="text" name="email">
    <label>Password</label>
    <input type="password" name="pwd" id="pwd">
    <input type="submit" name="submit" value="Register">
</form>
<?php
        require_once("db.php");
          if(isset($_POST['submit']))
          {
              $email = $_POST['remail'];
              $check = mysql_query("SELECT email FROM users where email='$email'");
              $num_rows = mysql_num_rows($check);
              if($num_rows > 0)
              {
                  echo "<script>alert('Email Already in Use. Please Choose another Email')</script>";
              }
              else
              {
                  $name = $_POST['name'];
                  $email = $_POST['email'];
                  $pwd = $_POST['pwd'];
                                   
                  $insert = mysql_query("INSERT INTO users(name,email,password) VALUES('$name','$email','$pwd')");
                $id = mysql_insert_id($conn);    //gets the last inserted id       
                $message = "<html>
                <head></head>
                <body>
                <p>Hello ".$name.",</p>
                <p>Your content here</p>
                <p><a href=\"http://DOMAIN-NAME/activate.php?actid=".$id."\">http://DOMAIN-NAME/activate.php?actid=".$id."</a></p>
                </body>
                </html>";
                $from = "your-mail-id"; //Ex: name@domain.com
                $headers ='Reply-To: '. $from . "\r\n" ;
                $headers.='From: '.$from. "\r\n";
                $headers .='X-Mailer: PHP/' . phpversion();
                   $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                  mail($email, "Activate your account", $message, $headers);
                                   
              }
          }
?>

Step 3. Copy the below code and save it as activate.php
  <?php
            require_once("db.php");
              $activationid = $_GET['actid'];
              $check = mysql_query("SELECT status FROM users where id='$actid'",$api->db);
              $num_rows = mysql_num_rows($check);
            if($num_rows > 0)
              {
                $row = mysql_fetch_array($check);
                $status = $row['status'];
                $query = mysql_query("UPDATE users SET status = 1 where id = $actid",$api->db) or die(mysql_error());
              }
            else { echo "<script>alert(Activation link is not valid.')</script>"; }
      ?>
how to implement email verification system using PHP.
How to send activation link to email PHP
Email verification using PHP
Email verification script
User registration email check verify validate with PHP

Friday, March 7, 2014

PHP simple login script

Hi dear friends, we have discussed about deleting a file using PHP script in our previous tutorial. In this tutorial I am going to explain you about login script using PHP. Login is used in applications where a user needs to be authenticated to access an application. This tutorial will give you the basic login form. I have used MySql to connect to the database where the login details are stored.

I have three PHP files where the first file contains the login form, the second contains the process for login form and the third file is the one where you will be redirected after login is successful.

Now let us see these files and let me explain them in detail. Please follow these carefully.

login.php

As I said there are three files. Login.php is the first file that contains login form. Let us see the code for it.

login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="te-IN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login</title>
</head>
<body>

<?php  if(@$_REQUEST['msg']=='fail')
 {
 echo"<div style='color:red;'>User name or password invalid.</div>";
 }


?>
<style>
.login_field
{
border:2px solid rgb(168, 168, 168);
border-radius:8px;
box-shadow:1px 0px 9px rgb(110, 110, 110);
color:rgb(153, 153, 153);
font-size:14px;
height:20px;
padding:4px;
}
</style>
<h1>Login</h1>

<form action="login_a.php" method="post" style="clear:both;">
<table>
<tr><td>Email</td><td><input type="text" name="email" id="email" class="login_field"></td>
</tr></br>

<tr><td>Password</td><td><input type="password" name="pwd" id="pwd" class="login_field"></td>
</tr></br>

<tr>
<td><input type="submit" name="login" value="login" onClick="return validate()"></td>
</tr>
</table>
</form>
</body>
</html>
In the above code we have HTML form which is used to fill the email and password. It contains input fields of text and submit button. In the <form> tag you can see action.  It tells the form to perform an action. We have to supply a file name on which the action has to be performed.

Next you can see method  It tells the form whether to POST or GET. There are three form methods POST, GET and REQUEST. Method will send the form values to the file which performs an action.

Name attributes inside input tags are used to get the values in the text boxes.

$_REQUEST['msg']=='fail'  checks whether the get method has the value fail for msg and if it is true then it prints "User name or password invalid". The request method will be executed when the username or password is wrong.

Copy the above code and save it as login.php

Now lets have a look on the second file which performs the action for login.

login_a.php

<?php
session_start();
include "db.php";

 if(isset($_REQUEST['login']))
 {

 $email = $_POST['email'];
 $password = $_POST['pwd'];
 $check = mysql_query("select * from user where email='$email' and password= BINARY '$password'")or die(mysql_error());
 $ret = mysql_fetch_array($check);
 $count = mysql_num_rows($check);

 if($count==1)
{
$_SESSION['id']=$ret['id'];

header('location:index.php');
exit();

}
else
{
header('location:login.php?msg=fail');
exit();
}
 }

?>
The above code session_start(); is a function that starts a session for the login.
include "db.php"; will import the database file. For database connection file please read How to connect mysql database using PHP, copy the code from there and save it as db.php

isset($_REQUEST['login']) checks whether the form has the name login in the submit button. If yes it will fetch the values from the text boxes of the form.

 $check = mysql_query("select * from user where email='$email' and password= BINARY '$password'")or die(mysql_error()); //checks the email and password whether matching or not. and die(mysql_error()) returns a value if it finds any error in the syntax.

$ret = mysql_fetch_array($check); This line fetches the array from the database.

Here is the logic $count = mysql_num_rows($check); counts for the number of rows in the database matching for the current email and password.

We have unique email or usernames for login. So  if($count==1) checks whether the count is equals to 1.

If yes then it creates a session and redirects you to the next page else you will be taken back to the login page with an error message we discussed above.

Copy and save the second block of code as login_a.php

The next and last page after login is index.php

index.php

<?php
session_start();
 $id = $_SESSION['id'];
 if(empty($_SESSION['id']))
 {
 header('location:login.php');
 exit;
 }

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
<link href="css/gallery.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="css/style.css" />

</head>
Welcome
</body>
</html>
As discussed above session_start(); starts a session for this page.

$id = $_SESSION['id']; // session stores id in it.

if(empty($_SESSION['id'])) checks if session expired. If yes the page will be redirected to login.php

Save this code as index.php

The sql for the login script is given below.

CREATE TABLE IF NOT EXISTS `user` (
 

`id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
 

`email` varchar(30) NOT NULL,
  `password` varchar(15) NOT NULL,
 

PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

AUTO_INCREMENT=2 ;

--
-- Dumping data for table `user`
--

INSERT INTO

`user` (`id`, `name`, `email`, `password`) VALUES
(1, '', 'admin@admin.com',

'pass');

Run the sql query in phpmyadmin and set the requires database configuration by copying the db.php from here and login to the application using admin@admin.com as email and pass as password.

Thank you very much. Please feel free to ask your queries below.

Note: Spamming comments will be removed.

Friday, February 21, 2014

How to connect mysql database using PHP

 We have seen how to fetch youtube videos using simple javascript in our previous tutorial. Today's tutorial is about connecting our database using PHP. Since PHP is a dynamic scripting language and it uses mysql database in the back end to store the data. That means the php file has to be configured to connect the database. This can be done very easily with a simple php code. This tutorial will help you to connect to the database. The database connection needs four parameters to be passed into two functions. mysql_connect() and mysql_select_db() are the two functions to connect to the database.

mysql_connect() function requires three parameters and this function is used to connect to the database. and mysql_select_db() function is used to select the database.

Here is the simple code that you can simply copy and use to connect your database with php.

<?php
$dbhost                            = "localhost"; //host name (usually localhost)
$dbuser                            = "root"; //your database(mysql) user name
$dbpass                            = "database_password"; //your database (mysql) password
$dbname                            = "database_name"; //database name
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
mysql_select_db($dbname) or die ("Error selecting the database");
?>
Now replace root with your database username database_password with your database password  database_name with your database username. That's it, you are done.

Please don't hesitate to ask your queries. Thank you

Wednesday, February 12, 2014

Create simple pagination with PHP and MySQL


Hi friends, todays tutorial is about creating a simple pagination using PHP and MySQL. I am going to explain you about creating a page with PREVIOUS and NEXT links at the bottom of your page with numberings.

Before looking at the code let's discuss about pagination concept. Pagination let's you create links that contains the data which is the continuation of the current item. Whenever there is large amount of data then it looks hard to load the entire data into a single page. Hence, we use the concept of pagination to allow the content to be split into parts and show only some part of the content per each page. This will give your website viewers a great experience and also has an advantage of speed loading of data, inorder to avoid the inconvenience.


You may also like:

Beautiful contact form for websites 

Add Google plus follower widget to blogger 

Stylish sticky menu bar with social icons for footer 

 Make money with facebook 

Add contact form to your blogger blog free 

Get more visitors to your site with SEO

Remove facebook graph search

Trick to find fake accounts on facebook

Get free mobile balance 100% working trick in India only

Speed loading like button for blogger

Delete facebook account permanently 100% working trick

Trick to use facebook on slow internet

How to get more page likes on facebook

How to delete google search history

8 Tricks to reduce load time of your website

3 ways to make money online without investment

5 idiotic ways to promote your blog


I said before that this code is based on PHP and MySQL, hence this code reads the data from the database tables and displays it on our page with pagination links. Since the data is being retrieved from the tables in the database we need to use sql connection mysql_connect() and then we need select database using mysql_select_db(). Let us see briefly how to connect to database using these two functions in PHP.

Code for Database connection:

<?php
$dbhostname               = "host name here"; //replace with your host name usually localhostname
$dbusername               = "database user name"; //replace with your database user name.
$dbpassword              = "database password"; //replace with your password
$dbname                     = "database name"; //replace with your database name

$conn = mysql_connect($dbhostname, $dbusername, $dbpassword) or die ("Database connection failed");
mysql_select_db($dbname) or die ("Database selection failed");
?>
The above code is used for datavase connection. Now let's see the code that is required to generate pagination links.

Code to generate pagination:

<?php
function create_pagination($current_page, $total_pages)
  {
    $create_page_links = '';
    // generates anchor tag for previous page if this is not first page
    if ($current_page > 1)
    {
      $create_page_links .= '<a href="current-page-name.php?page=' . ($current_page - 1) . '">PREV</a> ';
    }
    // generates page links with numbers till the loop ends
    for ($count = 1; $count <= $total_pages; $count++)
    {
      if ($current_page == $count)
      {
        $create_page_links .= ' ' . $count;
      }
      else
      {
         $create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . $count . '"> ' . $count . '</a>';
      }
    }

    // generates anchor tag link for next page if this is not last page
    if ($current_page < $total_pages) {
      $create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">NEXT</a>';
    }
    return $create_page_links;
  }

  // Calculate pagination
  $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
  $results_per_page =15;  // displays number of results per single page replace 15 with number of pages you may want
  $jump = (($current_page - 1) * $results_per_page); //3*2
 $query =  "select * FROM table_name order by id desc";//query to select from table
  $result = mysql_query($query1);

  $total = mysql_num_rows($result); //counts number of rows
  $total_pages = ceil($total / $results_per_page);

  $query =  $query . " LIMIT $jump, $results_per_page";
  $result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
//your code here to retrieve rows
}
?>
<!--creates links to display at bottom with previous, next and page numbers-->
                <div style="float:left; padding:20px">
                <?php
                if ($total_pages > 1)
                  {
                    echo create_pagination($current_page, $total_pages);
                  }
                ?>
                </div>
The above part of the code is to generate pagination links. I have clearly explained within the comments. So please look the code carefully and understand it. The above code is not included with database connection. Hence we can combine both the above codes together as shown below.

Pagination code with database connection:

<?php
$dbhostname               = "host name here"; //replace with your host name usually localhostname
$dbusername               = "database user name"; //replace with your database user name.
$dbpassword              = "database password"; //replace with your password
$dbname                     = "database name"; //replace with your database name

$conn = mysql_connect($dbhostname, $dbusername, $dbpassword) or die ("Database connection failed");
mysql_select_db($dbname) or die ("Database selection failed");
function create_pagination($current_page, $total_pages)
  {
    $create_page_links = '';
    // generates anchor tag for previous page if this is not first page
    if ($current_page > 1)
    {
      $create_page_links .= '<a href="current-page-name.php?page=' . ($current_page - 1) . '">PREV</a> ';
    }
    // generates page links with numbers till the loop ends
    for ($count = 1; $count <= $total_pages; $count++)
    {
      if ($current_page == $count)
      {
        $create_page_links .= ' ' . $count;
      }
      else
      {
         $create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . $count . '"> ' . $count . '</a>';
      }
    }

    // generates anchor tag link for next page if this is not last page
    if ($current_page < $total_pages) {
      $create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">NEXT</a>';
    }
    return $create_page_links;
  }

  // Calculate pagination
  $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
  $results_per_page =15// displays number of results per single page replace 15 with number of pages you may want
  $jump = (($current_page - 1) * $results_per_page); //3*2
 $query =  "select * FROM table_name order by id desc";//query to select from table
  $result = mysql_query($query1);

  $total = mysql_num_rows($result); //counts number of rows
  $total_pages = ceil($total / $results_per_page);

  $query =  $query . " LIMIT $jump, $results_per_page";
  $result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
//your code here to retrieve rows
}
?>
<!--creates links to display at bottom with previous, next and page numbers-->
                <div style="float:left; padding:20px">
                <?php
                if ($total_pages > 1)
                  {
                    echo create_pagination($current_page, $total_pages);
                  }
                ?>
                </div>
The above code is the final one.Copy the code and use it wherever you want.

Note: Now just make these changes before using the code.

host name here //replace with your host name usually localhostname

database user name //replace with your database user name.

database password//replace with your password

database name //replace with your database name

current-page-name.php  //Replace with the name of the page where this code is being used.

 $results_per_page =15  //change 15 to whatever the number results you may want to display ina single page
 
//your code here to retrieve rows //Code to fetch the rows from a database table

Thanks for reading this articles.
If you still have any queries then please don't hesitate to comment below.