Saturday, 13 January 2018

How to authenticate a user and create session in PHP ?

User authentication is very essential part of any web application. There may be many kind of user authentication are available in web technology, but form based user authentication is very common and secure.

Now here I am telling about form based user authentication in PHP and session creation. Here I pre- assume that you all are aware of database, and pre-requisite is a user table with user data. it may be like this -



Now I also assume that you know that how to create login form and perform a action on it. But again I am giving screen shot of login page code and its output.



output looks looks like -


Above is database design and form design.

Now come to the PHP programming, how would you authenticate the user and create a session for him?

Here is the full code to authenticate user and create his session.

<?php
session_start();

// Connect to server and select databse.

  $host="localhost";// Host name
  $username="root";// Mysql username
  $password="aarvindd";// Mysql password
  $db_name="e-cert";// Database name
  $con=mysqli_connect("$host", "$username", "$password")or die("cannot connect");
  mysqli_select_db($con,"$db_name")or die(mysqli_error());

// To protect MySQL injection(<a href="http://us.php.net/mysql_real_escape_string">more detail about MySQL injection</a>)

   $myusername = mysqli_real_escape_string($con,$myusername);
  $mypassword = mysqli_real_escape_string($con,$mypassword);

if (isset($_POST['Submit'])) {
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
  $result=mysqli_query($con,$sql);
  
// Mysql_num_row is counting table row
  $count=mysqli_num_rows($result);
    
  // If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// create session
 $_SESSION['user'] =$myusername;
//redirect user to his page
  header("location:adminhome.php");
}

  else {
  header("location:index.php?ll=Invalid Credentials, please try again.");
  }
  }
  
  ?>



Thursday, 11 January 2018

> Manifest merger failed: uses-sdkminSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support.apcompat-v7:26.0.0-alpha1] Android Studio

This kind of error you get when you select lower SDK version and you are using library which required higher version. This is the very basic error which occurs when you start a new project.

When you select very low minimum SDK requirement on "target android device window" of Android Studio, such kind of error occurs. You may resolve this in two ways -

1. Since these problem occurs during the start a new project, so you can restart a new project with some higher minimum SDK. See the screen shot -





2. But if you don't want to restart a new project and you want to resolve it in existing project, then open the build.gradle(Module app) file of your project and find the following value-

minSdkVersion 9

then change it to -

minSdkVersion 14

And then sync the project. screen shot is below-




Resolve java.lang.StringIndexOutOfBoundsException while getting substring in Java

Getting substring in Java is very easy. But when we don't  know the size of string or string size is variable, then it becomes difficult.

When I was working a project and I had to get the substring of 10 char long to display on page and this string was coming from database and I didn't know the length of this string and some times this string was less than 10 character.

So it was obvious to get the exception like "java.lang.StringIndexOutOfBoundsException: String index out of range: 10"

Then I started to search the solution for this. After a long search I could not find the simple one line solution to fix this. Every or many solution was based on to first find the null and then get the substring.

But I found the one line solution on stackoverflow by a user linqu.

Solution is given below :-

Suppose I have a string arvind and I want to get a substring of 10 character

class SubStr
{
public static void main(String ar[])
{
String s="arvind";
System.out.println(s.substring(0,10));
}
}

then it will give error like -


So one line solution is -

System.out.println(s.substring(0,Math.min(10, s.length())));





Thursday, 4 January 2018

Create dropdown menu in navigation bar in HTML and CSS

Creating navigation bar on web page which looks like drop down menu on mouse over is an essential part of web development. It can be developed by using CSS and HTML.

Here is the example code of this :-



Following CSS has used  for style and design, You may change the colour and font according to you. 

nav {
  background-color:;
  height:30px;
}

nav ul {
  font-family: Arial, Verdana;
  font-size: 15px;
  margin: 0;
  padding: 0;
  list-style: none;
}

nav ul li {
  display: block;
  position: relative;
  float: left;
}

nav li ul {
  display: none;
}

nav ul li a {
  display: block;
  text-decoration: none;
  padding: 7px 15px 3px 15px;
  background:;
  color: ; 
  margin-left: 1px;
  white-space: nowrap;
  height:20px; /* Width and height of top-level nav items */
  width:auto;
  text-align:center;
 }

nav ul li a:hover {
  background:#FBEFEF;
}

nav li:hover ul {
  display: block;
  position: absolute;
  height:20px;
}

nav li:hover li {
  float: none;
  font-size: 11px;
}

nav li:hover a {
  background:#E0F8F7 ;
  height:20px; /* Height of lower-level nav items is shorter than main level */
}

nav li:hover li a:hover {
  background: #95A9B1;
}

nav ul li ul li a {
    text-align:left; /* Top-level items are centered, but nested list items are left-aligned */
}

/* END NAV MENU */

Now here is the HTML code to create navigation bar.

<nav>
    <ul>
      <li><a href="adminhome.php">Home</a></li>
      <li><a href="">Event &dtrif; </a>
        <ul>
            <li><a href="stregister.php">New Registration</a></li>
     <li><a href="viewreg.php">View Registration</a></li>
            <li><a href="">Update Registration</a></li>
            <li><a href="">Delete Registration</a></li>
<li><a href="searchreg.php">Search Registration</a></li>
<li><a href="addevent.php">Add Event</a></li>
<li><a href="">Edit Event</a></li>
<li><a href="">Delete Event</a></li>
<li><a href="">Search Event</a></li>
        </ul>
      </li>
 
  <li><a href="/services">Project &dtrif; </a>
        <ul>
<li><a href="proj_reg.php">New Registration (Project)</a></li>
             
        </ul>
      </li> 
      <li><a href="/products">E-Certificate &dtrif; </a>
        <ul>
            <li><a href="get-cert1.php">Generate e-certificate</a></li>
<li><a href="get-cert-proj.php">Generate e-certificate (Project)</a></li>
            <li><a href="">View e-certificate</a></li>
<li><a href="checkstatus.php">Check Status</a></li>
        </ul>
      </li>
      <li><a href="/services">Reports &dtrif; </a>
        <ul>
            <li><a href="report-dept.php">Department-wise</a></li>
<li><a href="">Event-wise</a></li>
<li><a href="">Year-wise</a></li>
<li><a href="">Course-wise</a></li>
<li><a href="">Sem.-wise</a></li>
<li><a href="">All</a></li>
         
        </ul>
      </li>         
 
<li><a href="/services">Data &dtrif; </a>
        <ul>
            <li><a href="uploadexcel.php">Upload Data From Excel Sheet</a></li>
<li><a href="">Delete Data</a></li>
<li><a href="">View Data</a></li>
<li><a href="">Search Data</a></li>
       
        </ul>
      </li>         
      <li><a href="/contact">Profile &dtrif; </a>
        <ul>
            <li><a href="/email">Reports</a></li>
         
        </ul>
      </li>
   <li><a href="/contact">Site Map</a>
        <ul>
                   
        </ul>
      </li>
    <li><a href="/contact">FAQ</a>
        <ul>
                 
        </ul>
      </li>
    </ul>
</nav>

Wednesday, 3 January 2018

How to take screen shot of a system and save it to database in Java ?

To view any user's desktop in network or any organisation, there are many paid or may be free software is available. But if you want to develop your own software, you can develop into Java.

Here is the example code in which I have used MYSQL database to save screen shot. This example will save new image to database of given system and if image already exists of given system then it will update the table.

If you are familiar with database connectivity in JAVA, you know that we require database driver- i.e. also known as mysql_connector.jar file to make database connectivity.

You can download this jar file from here.


import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.imageio.ImageIO;

public class TakeShot {
    
    public void shot()
    {
      try {

//To capture image
            Robot robot = new Robot();
// put the desired filename and file extension
            String format = "png";
            String fileName = "fscshot." + format;
  // get the screen size and image of screen           
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
            ImageIO.write(screenFullImage, format, new File(fileName));
 //Save file to disk          
            File file=new File("fscshot.png");
            FileInputStream fis=new FileInputStream(file);
  //         
            System.out.println("A full screenshot saved!");
 //get ip address  of system
            InetAddress IP=InetAddress.getLocalHost();
            String ipadd=IP.getHostAddress();
System.out.println("IP of my system is := "+ipadd);
//Database connectivity
            PreparedStatement ps=null;
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost/lenser","root","");
            Statement stm=con.createStatement();
// check image is already saved in database then update image

            String sql="select ip from scshot where ip='"+ipadd+"'";
            ResultSet rs=stm.executeQuery(sql);
            if(rs.next())
            {
String ipp=rs.getString("ip");
System.out.println(ipp);
if(ipp.equals(ipadd)==true)
{
System.out.println("ipfound");
                                         ps=con.prepareStatement("update scshot set shot=? where ip='"+ipadd+"'"); 
                                       // ps.setString(1,ipadd);
                                        ps.setBinaryStream(1,fis,(int)file.length());
                                        ps.executeUpdate();
}
}
//if there is no image exist of IP address the insert new image
else
{
System.out.println("ipnotfound");
        ps=con.prepareStatement("insert into scshot (ip,shot) values(?,?)"); 
ps.setString(1,ipadd);
ps.setBinaryStream(2,fis,(int)file.length());
ps.executeUpdate();
}

            rs.close();
            ps.close();
            fis.close();
            con.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    
}

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...