Showing posts with label Web developement. Show all posts
Showing posts with label Web developement. Show all posts

Thursday, October 11, 2012

Image editing and saving using canvas in HTML5 with PHP

This document will demonstrate use of canvas for editing image and also we can get as download.
Index.html


Script.js


Save.php


Download.php

Tuesday, June 19, 2012

Difference between API and Web Service

Basically, a webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.

You could very well have an API and the main method of interacting with that API is via a webservice.

The technical definitions (courtesy of Wikipedia) are:

API

    An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.

To know more

Webservice

    A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"

To know more

Thursday, June 7, 2012

Export HTML to .CSV in PHP

This script will help you to export HTML content to *.CSV. PHP is one of most powerfull scripting language in Open source. This script was build through PHP script.

We split across three files to achieve this functionality.
  1. CSS file [To make desgin of HTML table].
  2. PHP file which will list out the DB data from Mysql to PHP.
  3. Another PHP file. Which will help you generate *.CSV file.
style.css



table.php



export.php



Thursday, May 31, 2012

Can't connect to local MySQL server through socket

In mysql we might get this problem while fresh installation of mysql.

"Can't connect to local MySQL server through socket"

The below line can help to over come a problem.

Step:1
sudo mkdir /var/run/mysqld/

Step:2
sudo ln -s /opt/lampp/var/mysql/mysql.sock /var/run/mysqld/mysqld.sock


I think this will help you overcome the problem of mysql sock layer.

Monday, May 14, 2012

Import .CSV file in PHP

This code will help you to import the .CSV file data into Database. This code was build in PHP. It is generic class which can use into different purpose.

Db.php
$con = mysql_connect("hostname","username","password");
mysql_select_db("dbname",$con);

Import.php
include('db.php');
class ImportComponent
{
    
    function array_remove_empty($arr){
 $narr = array();
 while(list($key, $val) = each($arr)){
     if (is_array($val)){
  $val = array_remove_empty($val);
  // does the result array contain anything?
  if (count($val)!=0){
      // yes :-)
      $narr[$key] = $val;
  }
     }
     else {
  if (trim($val) != ""){
      $narr[$key] = $val;
  }
     }
 }
 unset($arr);
 return $narr;
    }

   
    function import($file,$uid,$table){
 $row = 1;
 $status = "";
 if (($handle = fopen($file, "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     if($row == 1){
  foreach ($data as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  
  if(strpos($result,'"') == true){
      $splitdata = split('"',$result);
      $splitdata = str_ireplace("'",'',$splitdata);
  }
  else{
      $splitdata = split("'",$splitdata);
  $splitdata = str_ireplace('"','',$splitdata);
  $dataval = $this->array_remove_empty($splitdata);
  $result = "";
  foreach ($dataval as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  }
  $num = count($data);
  $row++;
  $valueresult = "";
  $datavalue = "";
  for ($c=0; $c < $num; $c++) {
     if($row > 2){
      $datavalue = $data[$c];
      $valueresult=$valueresult."'".$datavalue;
      $datavalueofsecrec = split('"',$valueresult);
      $datavalueofsecrec = str_ireplace("'",'',$datavalueofsecrec);
      $datavalueofsecrec = $this->array_remove_empty($datavalueofsecrec);
      $valueresult = "";
      foreach ($datavalueofsecrec as $finalval) {
   $valueresult=$valueresult."'".$finalval."',";
      }
      }
  }
  if($row > 2){     
      $query = "insert into $table($result) values($valueresult)";
      $status =  mysql_query($query);
  }
     }
 fclose($handle);
 }
 if($status)
 {
     return "Success";
 }
 else
 {
     echo "failed";
 }
    }
}

Form.php
include('import.php')
$obj = new Import();
 if($_FILES){
    $uploaddir = 'Directory path';
    $filename = $_FILES['file']['name'];
    $filesize = $_FILES['file']['size'];
    $tmpname_file = $_FILES['file']['tmp_name'];
    if($filesize > '1000000') {
    echo "Way too big!!";
    } else {
    move_uploaded_file($tmpname_file, "$uploaddir$filename");
         $status = $obj->import("$uploaddir$filename",$userid(Optional),$tablename);        
    }
 }

Friday, May 11, 2012

Query to know particular table status in MySql

In Mysql, we can execute several queries. Here, i am going to demonstrate about important query. This query will show you the properties belongs to particular table.

Query :         

SHOW TABLE STATUS LIKE TableName

The above query will return following coulmns,
  1. Name
  2. Engine
  3. Version
  4. Row_format
  5. Rows
  6. Avg_row_length
  7. Data_length
  8. Max_data_length
  9. Index_length
  10. Data_free
  11. Auto_increment
  12. Create_time
  13. Update_time
  14. Check_time
  15. Collation
  16. Checksum
  17. Create_option
  18. Comment
To get next "Auto Increament" id of table is most of realtime usage of this query. Also, They can know about engine name of the table.

Tuesday, January 31, 2012

Load different image on page refresh in PHP

In PHP, We can have multiple image can be show on page refresh. ALL the images should have same format.

Thursday, January 12, 2012

HTML Month Dropdownlist

This code in HTML dropdownlist for month. I has a month name on user view in the dropdown.Every month name bind with month numeric value.

Wednesday, January 11, 2012

Cross site scripting

Cross Site Scripting (CSS for short, but sometimes abbreviated as XSS) is one of the most common application level attacks that hackers use to sneak into web applications today. Cross site scripting is an attack on the privacy of clients of a particular web site which can lead to a total breach of security when customer details are stolen or manipulated. Unlike most attacks, which involve two parties – the attacker, and the web site, or the attacker and the victim client, the CSS attack involves three parties – the attacker, a client and the web site. The goal of the CSS attack is to steal the client cookies, or any other sensitive information, which can identify the client with the web site. With the token of the legitimate user at hand, the attacker can proceed to act as the user in his/her interaction with the site – specifically, impersonate the user. For example, in one audit conducted for a large company it was possible to peek at the user’s credit card number and private information using a CSS attack. This was achieved by running malicious Javascript code at the victim (client) browser, with the “access privileges” of the web site. These are the very limited Javascript privileges which generally do not let the script access anything but site related information. It should be stressed that although the vulnerability exists at the web site, at no time is the web site directly harmed. Yet this is enough for the script to collect the cookies and send them to the attacker. The result, the attacker gains the cookies and impersonates the victim.

Friday, January 6, 2012

Javascript: Remove duplicates from Array

There is now an array prototype function for removing duplicates. I suggest you use the prototype function instead of the functions below. It is the way it should have been done in the first place and is faster and moreover the most correct way to do it.
Array.prototype.unique = function () {
 var r = new Array();
 o:for(var i = 0, n = this.length; i < n; i++)
 {
  for(var x = 0, y = r.length; x < y; x++)
  {
   if(r[x]==this[i])
   {
    continue o;
   }
  }
  r[r.length] = this[i];
 }
 return r;
}
You can now utilize the unique function like this:
var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
var unique = arr.unique();
alert(unique);
The result will be [1,2,3,4,5,6,7,8,9].

The first one does what you’ll expect, it’ll regard the first encountered entry as the original and all subsequent entries as duplicates.
function unique(a)
{
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++)
   {
      for(var x = 0, y = r.length; x < y; x++)
      {
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}
If we pass the following array [1, 2, 3, 1, 4, 5] to the function the result will be [1, 2, 3, 4, 5]. The second variant returns different results. It will regard the last encountered duplicate as the original. This may be desirable in certain situations.
function unique(a)
{
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++) {
      for(var x = i + 1 ; x < n; x++)
      {
         if(a[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}
The output in this case will be [2, 3, 1, 4, 5]. You can easily adapt the function to make it a prototype function of an Array object. If people don’t know how to do it just ask, i’ll add it. Hope this helps someone out!

Thursday, January 5, 2012

Creating Dynamic PDF files using HTML and PHP


There always arise a need for converting content from one file format to another one. Some may need to convert some text into HTML and some may need to convert some HTML content to an image format. The main reason for the need to convert from one file format to another is because the target file format is best suited for targeted medium where the content need to be displayed. The targeted medium may be an email, a printed hard copy or a web browser. The text format is best suited for sending emails, as the possibility of the email contents getting corrupted in the transition is much lesser, when compared to the HTML formatted emails. PDF document or a word document would be the best choice for taking a printed hard copy and obviously HTML is best for showing contents in web browsers.

Here, we are going to study on converting HTML 2 PDF using PHP. This article is not going to explain on the main logic of how to convert a HTML file to PDF file. That would be a separate subject and it could not be covered in this short article. But we would be seeing how to use some free open source PHP scripts to accomplish this file conversion.

The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.

require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();


 To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:

$pdf=new FPDF('P','mm','A4');

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:

$pdf->SetFont('Arial','B',16);

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:

$pdf->Cell(40,10,'Hello World !',1);

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
There are lot more functions in FPDF and we cannot cover all those in this article.
To learn FPDF, please browse http://www.fpdf.org.

Tuesday, January 3, 2012

Autocompletion with Scriptaculous and Ajax


This tutorial supercedes my previous turtorial on autocompletion by adding further tips and tricks to make your autocompletion a much better experience for your site users The tutorial is structured in the following way:
  1. Introduction: What is autocompletion and why use it?
  2. How it works.
  3. Getting scriptaculous and building the form.
  4. Building the autocomplete server.
  5. Passing back an id to our form.

1. What is autocompletion and why use it?

I predict that most people will want to skip this section and get straight to the action, so I will keep it brief. Autocompletion is a means of helping your users when filling in forms. The most common application of autocomplete is found in your web browser’s address bar; as you type the bar makes suggestions of URLs based on previous pages visited. In our example we will query a database of musical artists and give our users suggestions as they type in an artist name field.

2. How it works.

As a user types in a specific input field on a form, on each key up event, we use JavaScript to call a script in the background using Ajax (XMLHttpRequest) features built into the Scriptaculous library. Our form will pass the currently typed text to this script and the script will return a list of suggestions which will be dynamically placed in our page. The important thing is that our user can select one of these items by mouse-click or key-stroke to populate the form field instantly.

3. Getting scriptaculous and building the form.

This implementation of autocomplete requires 3 components:
  1. The Scriptculous libraries;
  2. An HTML form with a single field;
  3. An autocomplete server script
I use PHP as my language of choice for the autocomplete server script, but I have tried to keep this tutorial abstract enough to allow you to use your language of choice. The server script is the only thing that changes for different server-side scripting languages. Download the latest version of the Scriptaculous JavaScript Libraries and include them in the head of a new HTML document as below.

Don’t forget to change the paths to match your directory structure:

<script type="text/javascript" src="lib/prototype.js"></script>
<script type="text/javascript" src="src/scriptaculous.js"></script>


Now add a form to your HTML page’s body. In this form we are going to add a field that will take our search term (with both id and name attributes as “searchterm”) and an empty div with an id of “hint”. This empty div acts as a holder for our hints when they are generated. You should have some HTML looking like this:

<input type="text" name="searchterm" id="searchterm" />
<div id="hint"></div>


All we need now is to initiate a new call to Scriptaculous’ built in Ajax.Autocomplete method below our HTML code for the autocompleter – like this:

<script type="text/javascript">
new Ajax.Autocompleter(”searchterm”,”hint”,”server.php”);
</script>


The Ajax.Autocompleter takes 3 arguments: The element supplying the search string, the element to show suggestions in and the server script that will generate our suggestions. With that in place we can write the server script.

4. Building the autocomplete server.

The following server is written in PHP connecting to a MySQL database but you can your language of choice and even a flat text file or XML file for the suggestion database. My database table, “Artists”, is simple – it comprises a unique id field and an artist “name”.
As the Autocompleter sends the value of a form field as a POST variable, we can use this in our server script’s query againstthe database. All we need to do is output an unordered list for the autocompleter. Scriptaculous does the leg work of inserting the latest list into our hint box everytime the user makes a keystroke. Here is my server code in PHP

<?
// don't forget your database connection here.
echo "<ul>";
$sql = "SELECT * FROM artists WHERE name LIKE '%" . $_POST['searchterm'] . "%'";
$rs = mysql_query($sql);
while($data = mysql_fetch_assoc($rs)) {
echo "<li id=\"" . $data['id'] . "\">" . $data['name'] . "</li>";
}
echo "</ul>";
?>


Note that I have given each list item an id that is the same as that of the record. We will use this shortly for a more advanced technique. But for now we have all we need for a basic autocompleter.

5. Passing back an id to our form

Once a user has selected an item from the autocompleter, the string is entered into the textfield. Often, for the sake of efficiency and accuracy it is better to deal with the id of the item than the string name when it is passed on to the next page. To do this we can use some extra functionality of Ajax.Autocompleter along with some JavaScript that will pass the id to a hidden field in our form.

The first thing we need to add to our form is a hidden field with an id that we can reference:

<input type="hidden" id="artist_id" name="artist_id" />

Now we can use an extra piece of functionality built into Ajax.Autocompleter that allows us to pick up the id that we included in our list item from the server script. This is an extra option on our autocompleter call:

new Ajax.Autocompleter(”searchterm”,”hint”,”server.php”, {afterUpdateElement : getSelectedId});

We are telling our autocompleter to run a function called getSelectedId when an item is selected. All we need to do now is write this function to get the id and inject it into our hidden field. Insert the function below the

function getSelectedId(text, li) {
$('searchterm').value=li.id;
}


And that’s all there is to it. Of course you can be as clever as you want with your autocomplete server script. Try using the LIMIT clause in your SQL to make it run faster. Make your queries more advanced to bring back more specific results. And don’t forget the fun you can have with CSS on your hint div and the list of suggestions that it displays. If you have any implementations of autocompletion using this tutorial, please post them in the comments here.

How to get the javascript objects in html body tag

____________________________________________

index.jsp
____________________________________________

<html>
<head>
<script>
function jsAdd()
{

var temp=document.getElementById("count");
var values=temp.value;
alert(""+values);

var parent = document.getElementById("family");
div = document.createElement("div");
var tbl=div.appendChild(document.createElement("table"));
var tb=tbl.appendChild(document.createElement("tbody"));
var tr=tb.appendChild(document.createElement("tr"));
var td=tr.appendChild(document.createElement("td"));
parent.appendChild(div);

var oSelect=document.createElement("select");

var option1 = document.createElement("option");
var t = document.createTextNode("Parent");
option1.setAttribute("value","Parents");
option1.appendChild(t);
oSelect.appendChild(option1);

var option2 = document.createElement("option");
var t = document.createTextNode("Spose");
option2.setAttribute("value","Spose");
option2.appendChild(t);
oSelect.appendChild(option2);

var option3 = document.createElement("option");
var t = document.createTextNode("Chaild");
option3.setAttribute("value", "Chaild");
option3.appendChild(t);
oSelect.appendChild(option3);

var option4 = document.createElement("option");
var t = document.createTextNode("Other");
option4.setAttribute("value", "Other");
option4.appendChild(t);
oSelect.appendChild(option4);
oSelect.name="rel"+values;
var fname=document.createElement("input");
fname.type="text";
fname.value="Enter name";
fname.name="name"+values;
var age=document.createElement("input");
age.type="text";
age.value="Enter Age";
age.name="age"+values;
td.appendChild(oSelect);
td.appendChild(fname);
td.appendChild(age);

temp.value=parseInt(values)+1;
}

function count()
{
document.getElementById("count").value=0;
}

</script>
</head>
<body onload="count()">
<form action="./submit.jsp" method="post">
<input type="hidden" value="0" id="count" name="count">
<div name="family" id="family">
</div>
<input type="button" value="add" onCLick="jsAdd()">
<BR><br><input type="submit">
</form>
</body>
</html>

______________________________________________

Submit.jsp
______________________________________________

<html>
<head>
</head>
<body >
<table>
<tr><td>Relation Ship</td><td>NAME</td><td>Age</td></tr>

<%
int count=Integer.parseInt(""+request.getParameter("count"));
for(int i=0; i<count;i++){%>
<tr><td><%=request.getParameter("rel"+i)%></td><td><%=request.getParameter("name"+i)%></td>
<td><%=request.getParameter("age"+i)%></td></tr>
<% } %>
</table>
</body>

</html>

Wednesday, October 12, 2011

Creating an Image Watermark

Well, this is my last javascript post for a bit, seeing as this is just an offshoot of my last post Javascript: Dynamically Altering CSS Properties. In this post, we’ll go over creating a simple Javascript watermark for a textbox using an image. If you are curious how to create a watermark with just text, read my other post on how to create a textbox text watermark. A textbox watermark can help encourage its use and reduce confusion for your users. I typically employ a watermark for textboxes that exist outside of a form (they only gather one piece of needed information such as a zip code as opposed to an entire address).
So either in an external Javascript file (which is called the same way as an external CSS file), or in the head of your HTML inside a <script> tag, include the following javascript.
The Javascript:
function hideWatermark(theID)
{
    var element = document.getElementById(theID);
    element.style.backgroundImage = 'none';
    element.style.backgroundColor = 'white';
}
function showWatermark(theID)
{
    var element = document.getElementById(theID);
    if (element.value.length == 0)
        element.style.backgroundImage = 'url(\'IMAGE_LOCATION_HERE\')';
    else
        element.style.backgroundColor = 'white';
}
On focus (when the user clicks on the textbox) the hideWatermark function is called. The javascript takes in a string of the textbox ID. It then sets the background image to none, and the background color to white. On blur (when the user clicks away from the textbox, putting focus on any other element), the showWatermark function is called. This javascript also takes in the same ID. It then checks to see if the content of the textbox is empty, if it is, it puts the background image of the watermark back in. If it is not empty, then it keeps the background color as white.
Here is the HTML that goes with the JS:
And the CSS:
.gatherZip{
   background: white url('IMAGE_LOCATION_HERE') no-repeat center center;
}
The image you create can say or imply whatever you want. As an estimate, try to keep the image no more than about 15 pixels high or it won’t fit in standard sized textboxes. And that’s it. A beautiful textbox watermark just for you and your users! Comments? Questions?