Wednesday, 2 November 2016

Form with rounded Border

Hi All,

See this code to put rounded border to forms.

---------------------------------------------------------------------
<html>
<head>
<style>
fieldset {
  -moz-border-radius:5px;
  border-radius: 5px;
  -webkit-border-radius: 5px; //edit :D
 
}
</style>
</head>
<body>
<fieldset  style="width:250px">
<form action=HUPModify.php method=post>
<pre>
New Reference Number <input name=nrefno>
Total References     <input name=tref>
<input type=submit value="Change file">
</pre>
</form>
</fieldset>
</body>
</html>

---------------------------------------------------------------------

Sunday, 30 October 2016

Hi All,

If you want to find the difference between two dates (Eg. current date and another date) use this simple code

<?php

$current = time(); // Current date and time
$testdate= strtotime("2016-10-20");
$daydiff = $current - $testdate;
echo floor($daydiff / (60 * 60 * 24));

?>

Using this code you can find the fine by calculating day difference between current date and book issue date.

Saturday, 11 June 2016

Execute a Java program from PHP

Dear friends,

In data mining works we usually used to call java class files. Sometimes from PHP.

Try this code to invoke a Java program or some other jar executables from your PHP

Sample 1.

<?php

exec("java Apriori hup.dat 0.4 > hupa.txt");

?>

The above code will run Apriory.class with hup.dat as input file and the output will be saved in hupa.txt which can be further processed by PHP data mining program.

Sample 2.

<?php

exec("java -jar LDA/jar/jLDADMM.jar -model LDA -corpus LDA/test/corpus.txt -name testLDA -ntopics 5 -twords 5 > huplda.txt");

?>

The above code will run a jar file for LDA topic modeling algorithm stored in LDA/jar/ folder in www directory of LAMP or WAMP or XAMPP with lot of switches and output can be redirected to huplda.txt file.

Show Time difference in milliseconds using PHP

Dear Friends,
We might have come across showing results by google with search time. The same can be implemented in our program as well.

<?php

$currentTime = microtime(true);


// Write some code which consume your CPU time
//...
// Find time difference in milliseconds

$timediff= round(microtime(true) - $currentTime,3)*1000;
echo "<h4>in ". $timediff. " Milli seconds </h4><br>";

?>

Friday, 27 May 2016

Make a copy of a template file and Change a word by another word in the whole file using PHP

Dear Friends
While dealing with template file, it is too common to make copies of that file and replace one word by another word.

In the code attached below one file is created dynamically based on table name and then a local copy of template file is created in the name of table in a folder HUP. Then a word HHHUUUPPP will be replaced with the name of table. Once the entire file is replaced then a fresh copy the new file will be taken and old file will be deleted.

//Code starts here.

<?php

$table=$_POST['tablename'];
$viewfile1='HUP/view'.$table.'1.php';
$viewfile='HUP/view'.$table.'.php';
copy('HUPViewtable.php',$viewfile1);

$myfilemain=fopen($viewfile, "w") or die("Unable to open file!"); //Open table structure file for
$myfiletemp = fopen($viewfile1, "r") or die("Unable to open file!"); //Open table structure file for
while(!feof($myfiletemp)) // Reading the table structure file
{
  $line= fgets($myfiletemp) ;
  $rtext=str_replace("HHHUUUPPP",$table,$line);
  fwrite($myfilemain,$rtext);
}
fclose($myfilemain);
fclose($myfiletemp);
unlink($viewfile1);
?>

Delete all files from a folder using PHP

Dear friends,
In some cases we will be forced to clear the contents of some server folders. Use the code given below.

//Code starts here

<?php

$files = glob('HUP/*'); // get all file names
foreach($files as $file)
{ // iterate through the files in the folder
  if(is_file($file))
    unlink($file); // delete file
}
?>

Create Zip file out of your Folder using PHP

Dear Friends,
Use this code to generate and download zip files. NB: no echo statements should be there in your code. If so should comment it.

//Code starts below


<?php

$file_names=array();

$dir="HUP/";
if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            $file_names = array();
            while (false !== ($file = readdir($handle))) {
                if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $file_names[] = $file;
            }
            closedir($handle);
            if (is_array($file_names)) sort($file_names);
          
        }
    }

$error = "";      //error holder
$file_path="HUP/";
//echo "entered 1";
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
//echo "entered 2";
    if(count($file_names) > 0)
    {  
    //echo "entered 3";
        // 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/>";
            //echo $error;
        }
        foreach($file_names as $file){ 

            $zip->addFile($file_path.$file);            // Adding files into zip
        }
        $zip->close(); 
        //echo $zip_name;
        if(file_exists($zip_name))
       {
        //echo "entered 4";
            // 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/>";
}
?> 

PHP code to prevent upload of invalid image with hack script

Hi All,

Always use this code for image upload to prevent images with vulnerable scripts.

<?php

$newIm = @imagecreatefromjpeg($_FILES["image"]["tmp_name"]);
if (!$newIm) {
    // gd could not create an image from the source
    // most likely, the file was not a valid jpeg image
    header('location:userhome.php?msg=error'); // Code to direct to your home page showing error

}
else     // code to upload file
       move_uploaded_file($_FILES["image"]["tmp_name"], $target_file) or die('Error'.mysql_error());


?>

Wednesday, 25 May 2016

Process Regular Expressions in Strings

A common problem which we encounter during string processing
In the program a sentence is given which contains actual text enclosed in parenthesis. In that case to extract only those text, we can go for the below given code. The same would be of great use in pdf text extraction.

<?php

       $text="1212(HI)fjsdlf(how)sldfjs(are)sldfjslf(you)";
        preg_match_all('#\((.*?)\)#', $text, $match);      
       print_r ($match);
       
            $key=key($match);
            $val=$match[$key];
               if ($val<> ' ')
            {
                   echo $key ." = ".  $val ." <br> ";
           
                    for ($i1 = 0; $i1 <  count($val); $i1++)
                    { echo "entered";
                        $key1=key($val);
                        $val1=$val[$key1];
                        if ($val1<> ' ')
                        {
                            echo "--". $key1 ." = ".  $val1 ." <br> ";
                           
                        }
                        next($val);
                    }
             
             }
            
?>

Thursday, 3 March 2016

Generate one combo box on click of another combo box using Ajax

Dear Friends,

Here I have exemplified a shop with car brands and models. When you select Brand from one combo only those models matching the brands will be displayed in the other combo box.

SQL Database and Tables required

--
-- Database: `carcare`
--

CREATE TABLE IF NOT EXISTS `brand` (
  `bid` varchar(5) NOT NULL,
  `bname` varchar(20) NOT NULL,
  PRIMARY KEY (`bid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `model` (
  `bid` varchar(5) NOT NULL,
  `mid` varchar(5) NOT NULL,
  `mname` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Make sure you have data in brand and model tables

1.  database.php

<?php
$cn=mysql_connect("localhost","root","") or die("Could not Connect My Sql");
mysql_select_db("carcare",$cn)  or die("Could connect to Database");
?>


2. servicereq.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Car Service</title>


<script>
function loadDoc() {
//alert('HUP');
     var key=document.frmsearch.brand.value;
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             document.getElementById("a1").innerHTML = xhttp.responseText;
        }
  };
  xhttp.open("GET", "selectmodel.php?key="+key, true);
  xhttp.send();
}

</script>

</head>

<body>
<table>
<form name=frmsearch  method=post>
<tr><td>Select Brand</td><td><select name="brand" onChange="loadDoc()"><option>select</option>

<?php
include("database.php");

 $qr="select * from brand";
 $data=mysql_query($qr,$cn);
 while($row=mysql_fetch_array($data))
 {
         echo"<option value='$row[bid]'>".$row[bname]."</option>";
 }
 ?>
 </select>
 </td>
 </tr>

 <tr><td>Select Model</td><td><div id=a1></div></td></tr>
 </table>
</body>
</html>


3. selectmodel.php


<select name="model">

 <?php
 $bid=$_GET['key'];
 include("database.php");
 $qr="select * from model where bid like  '%$bid%'";
 $data=mysql_query($qr,$cn);
 while($row=mysql_fetch_array($data))
 {
         echo"<option>".$row[mname]."</option>";
 }
 ?>
 </select>


Upload a file with unique name and save file details in table

Dear Friends,

Here using this files you can upload a file to a folder called "uploads" and can be retrieved for viewing.

In Step 1 you design the form as given below. Make sure enctype="multipart/form-data" is written in the form tag.

Step1. uploadform.html

<html>
<body>

<form name="frm" action="upload.php"  method=post enctype="multipart/form-data" >
<input type="file" name="fileupload" size="70"/>

<input name="upbtn" type="submit" value="Upload files" />
</form>


</body>
</html>





Step 2.  upload.php
Here in the second step the file is uploaded and also file details are stored in the table.
Here whatever be the filename we append the dynamically generated id in front of the file and save in the folder so that in future duplicate filenames can be eliminated.

<?php
$target_dir = "uploads/";
$fname=basename($_FILES["fileupload"]["name"]);

$uploadOk = 1;
$imageFileType = pathinfo($fname,PATHINFO_EXTENSION);
session_start(); // Starting session so that used id can be retrieved for storing in the table.

//Here we retrieve the previously stored id from the table, so that adding one to that id give you the new fileid.
 
$sql="select max(aid) as maid from assignment ";
$aid=0;
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$data=mysql_query($sql,$con) or die(mysql_error());
while($row=mysql_fetch_array($data))
{
    $aid=$row['maid']+1;   
}

$userid=$_SESSION["user"];
$dates="2016-3-3"; // Date can be taken from system
$filename=$aid.$fname;
//if the filename is "record.doc" and aid is 123 then the filename will be uploaded as 123record.doc
$target_file = $target_dir . $filename;

$sql="insert into assignment values('$aid','$userid','$dates','12','$filename')"; // Table fields can be set by user

$data=mysql_query($sql,$con)  or die(mysql_error());
// Allow certain file formats
if($imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "pdf" )
    alert("Only doc or pdf files");
else
       move_uploaded_file($_FILES["fileupload"]["tmp_name"], $target_file);

?>
<html>
<body bgcolor="#33CCFF">
Succesfully inserted
</body>
</html>

Monday, 15 February 2016

Text box validation on Key press

Dear All,
It is always mandatory to validate textbox in the keypress event. Please see the code

file name : validatetext.php


<html>
<head>
<!--
Coded by Prof. Sajeev Jaladharan
Date : 27.11.2015
email: sajeevjal@gmail.com
-->
<title>SNIT MCA Online Registration</title>

<script>
function checkname()
{

   
    /*if(!isNaN(name))
    {
        alert('Enter characters only');
        document.reg.Name.value='';
        document.reg.Name.focus();
    }
    */
        name=document.reg.Name.value;
   
    var letters = /^[A-Za-z]+$/; 
   if(name.match(letters)) 
     { 
      return true; 
     } 
   else 
     { 
     alert("No numbers or blank space please");
     document.reg.Name.value='';
        document.reg.Name.focus();
     return false; 
     } 
}



</script>
</head>
<body background="img.jpg" >
<table border=0 width=63% align="center" bgcolor="#EFFBFC">
<tr><td>

<form name="reg" class="wufoo topLabel page" method="post" action="saveadmission.php" onSubmit="return checkname()">
  <table style="border-color:#669999;border-style:dashed ;" align="center" cellpadding="2" cellspacing="2" width="85%">
    <tbody>
    <tr>
      <td>Name </td>
      <td><input id="Name" name="Name" style="width:150px" size="20" tabindex="2" type="text" onKeyUp="javascript:checkname()"></td></tr>
  
      <td colspan="2"><strong><blockquote class="style1"><span>For Communication Purpose</span></blockquote></strong></td></tr>
    <tr>
    
 
      <td colspan="2"><div align="center">
        <input name="Save" id="Save" value="Save Data" type="submit" tabindex="21">
        <label>
        <input name="Reset" value="Clear Form" type="reset">
        </label>
      </div></td></tr>
  </tbody></table>
  <div class="info" align="center">
</div>
</form>
</td></tr></table>
</body>
</html>

Thursday, 14 January 2016

Search using Ajax

Hi All,
Searching using Ajax is very important when we need to show the result in the same page without refreshing it.
It is composed of 2 steps

Step 1: Design the search page with Ajax function. Save this file as searchform.php

<html>
<head>
<script>
function loadDoc() {
//alert('HUP');
     var key=document.frmsearch.sname.value;
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             document.getElementById("demo").innerHTML = xhttp.responseText;
        }
  };
  xhttp.open("GET", "searchstud.php?key="+key, true);
  xhttp.send();
}
</script>


</head>
<body >
<form name=frmsearch  method=post>
<center>Name <input type=text name=sname onkeyup="loadDoc()"><input type=button value='Search Student'onclick="loadDoc()">
</center>
</form>
<div id="demo" align=center><h2>Search Result</h2></div>
</body>
</html>

Step2. PHP code to search in the database based on the Name field in Student table. Save this file as searchstud.php

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("SNIT",$con);
$sname=$_GET['key'];

$sql="Select * from student where name like '%$sname%'";



$data=mysql_query($sql,$con);
echo "<table border=1 align=center width=50%>";
echo "<tr><th>Name</th><th>Roll No</th><th>Marks</th></tr>";
while($row=mysql_fetch_array($data))
{
$name=$row['name'];
$rollno=$row['rollno'];
$marks=$row['marks'];

echo "<tr><td>$name</td><td>$rollno</td><td>$marks</td></tr>";

}

mysql_close($con);

?>

Working of this program

Here when we type in the textbox the 'onkeyup' event of textbox triggers the Ajax function 'loadDoc' which in turn make an http connection with the searching php program 'searchstud.php'.
The result generated by the php program will be send back to the searchform.php and updated in the area specified by the <div> tag in the same page. 










Wednesday, 13 January 2016

Searching using Form

Hi All,

Searching is most important in any student project.

This requires 5 important steps. [You can skip step 1,2 and 3 if you already have Database, table and data ]

1. Create Database - SNIT

Query : CREATE DATABASE SNIT

2. Create Table - student

Query : CREATE TABLE student(name TEXT(20),rollno int(3),marks int(3))

3. Insert few records in the table

Query : INSERT INTO `SNIT`.`student` (`name`, `rollno`, `marks`) VALUES ('Raju', '18', '90'), ('Babu', '9', '81')

4. Design Search form - save it as searchform.html

<html>
<body>
<form name=frmsearch action=searchstud.php method=post>
Name <input type=text name=sname><input type=submit value='Search Student'>
</form>
</body>
</html>

5. Write PHP program to search and display records. - save it as searchstud.php

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("SNIT",$con);
$sname=$_POST['sname'];
$sql="Select * from student where name like '%$sname%'";

echo $sql;

$data=mysql_query($sql,$con);
echo "<table border=1 align=center width=50%>";
echo "<tr><th>Name</th><th>Roll No</th><th>Marks</th></tr>";
while($row=mysql_fetch_array($data))
{
$name=$row['name'];
$rollno=$row['rollno'];
$marks=$row['marks'];

echo "<tr><td>$name</td><td>$rollno</td><td>$marks</td></tr>";

}

mysql_close($con);

?>

NB: Also try the same code with other table containing more fields

All the best.