Friday, 28 February 2014

Submitting and Securing the form data with Javascript

Whenever you create a form in HTML, you use "action" attribute of the <form> to submit your form. Now if you are not using SSL, then the data that you are sending is not encrypted and not secure.
You can use javascript to encrypt the data and also submit the form. <form> contains a attribute or event "onsubmit" which is fired when user clicks on the submit button. We can use this event and submit form using javascript.

Here is a little demo of what you can do.

First create a simple form.
<form action="process.php" method="post" onsubmit="return submitForm(this.form)"> <input type="text" name="uname" id="uname"> <br> <input type="password" name="pass" id="pass"> <br> <input type="submit" value="Submit"> </form>
Now consider that want to send the username and password after encrypting it.
One way to do this is when user clicks the submit button, we change the values of the fields with the encrypted values.
The other way is to create form in javascript and values to it and then submit that form to server side.
Here is a little JS that does the same thing.
<script> //Dummy Encrypt function, returns the given data as it is. function Encrypt(data) { return data; } function submitForm(form) { //create a form element var f = document.createElement("form"); //set post and action attributes f.setAttribute('method',"post"); f.setAttribute('action',"process.php"); //Create a new element of type input var uname = document.createElement("input"); //Set its type uname.setAttribute('type',"text"); //give it a name uname.setAttribute('name',"uname"); //Encrypt can be any function that you define to //encrypt the given data uname.value = Encrypt(form.uname.value); //create one more to store password var pass = document.createElement("input"); pass.setAttribute('type',"password"); pass.setAttribute('name',"pass"); pass.value = Encrypt(form.pass.value); //add both to form f.appendChild(uname); f.appendChild(pass); //submit the form f.submit(); return false; } </script>
Here it we create a new form element, add child elements to it and submit is. The advantage here is you can choose your own encryption logic based on your needs and send the data securely to the server.
Ads :
Buy Kodak, Canon, Panasonic Cameras on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Thursday, 20 June 2013

How to upload file to server in android using FTP

In my previous post I have discussed how we can upload file using HTTP-POST method.
It is a good method, but if you have a large file and server is not configured for upload of that size it will fail.
So, we can use another protocol made for transferring files between two machines, FTP. As android app is build using java we can use Apache Commons Net library which provides classes for using FTP service.
You can download it here, and then dd commons-net-3.2 file to your android project. Here is the code to connect to FTP server.
FTPClient client = new FTPClient(); client.connect(FTPSERVER, PORT); client.login(USERNAME, PASSWORD);
Here we instantiate an object of FTPClient class which is used for communication with server.
  • FTPSERVER is address of your ftpp server where you want to upload file
  • PORT is the post used to connect to server, mostly 21
Once you have logged in successfully, you can change current working directory on server, upload file receive file etc.
connect method throws SocketException, IOException and login method throws IOException so you should surround them in try/catch block.
Once you have logged in you can use printWorkingDirectory() method to get the current working directory. It returns path of directory as String.
changeWorkingDirectory(String dir) method is used to change the working directory.

So once you are at your target directory you can upload files. You can upload then as Binary or Text(ASCII) files.
client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
Or
client.setFileType(FTP.ASCII_FILE_TYPE, FTP.ASCII_FILE_TYPE); client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
Mostly it is better to transfer files in binary mode. To upload a file use
client.storeFile(String REMOTE_FILE_NAME, FileInputStream SROUCE);
It will read data from give FileInputStream and save it on server with the name given as first parameter.

NOTE :
This methods use network so make sure not use them on main thread or UI thread. Either use them in a service or in AsyncTask.
Also don't forget to add android.permission.INTERNET permission in manifest file.
Ads :
Buy Kodak, Canon, Panasonic Cameras on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Monday, 17 June 2013

Pointers In C

Pointers are very useful while programming in C and they are easy to learn.
We start discussion with what are pointers and why they are used.

When you create a variable in C, some memory is allocated for it from primary memory (RAM) and we can refer to that memory location by the name of the variable.
For example consider int var; . Now a memory location will be allocated to 'var' and we will refer to that location using variable name var.
Now assume that the memory is addressed using sequential numbers, and var is allocated at location 1000. which means if we do var = 10; value 10 will be stored at memory location 1000 and 1001 as int is of 2 bytes.

1000 -> 0000 1010 (10)
1001 -> 0000 0000 (00)

Thus we can say that a variable is a memory location allocated during execution and its value is value stored in corrosponding location.
We can obtain address of any variable using '&' operator, so in our example &var will be 1000.


Now different type of variables store different type of values like integer digit, floating point data, character data etc. The vary same way pointer are also variables and they store the address of other variables.
They are declared same way normal variable but with an extra * before their name.
For example int *ptr; . This statement will declare a variable of int* type which means it is a pointer and it will contain the address of int variable.


There are two ways of assigning a value (address of a variable) to the pointer.
  1. At declaration time :
    int *ptr = &var;
    Here ptr is declared as a pointer to int and address of var is stored in ptr.
  2. After declaration :
    int *ptr; ptr = &var;
    Here we first declare the pointer and then assign the value.


Note that we can not assign value to the pointer directly like ptr = 1000; or int *ptr = 1000; . Only assignment through & operator or malloc/calloc/reaclloc is allowed with exception being 0 and null i.e. ptr = 0; or ptr = null is allowed. Also note that pointer is also a variable and its value is also stored at some memory location.
Consider following figure.
Here we can see that var is allocated memory location 1000 and its value is 1234 and ptr is allocated memory location 2000 and its value is 1000 which is address of var. Thus value of ptr and &var is same as &var gives address of var and so does ptr.
Now if we want to access any variable pointer by a pointer we use dereference operator or indirection operator which is * in C. So writing *ptr will yield the same value as the var.
Thus we can use pointer to access the address of a variable and also the value. Also note that a int* type pointer can only point to a int variable but a void* pointer also called generic poiner can point to variable of any datatype.

Pointer To Pointer:

A pointer can be used to store address of a variable like int, float, char, it can also point to another pointer i.e. store address of another pointer, such pointers are called pointer to pointer.
Pointer to pointer can be declared using data-type **ptrptr; Consider following fragment of the code.
int i=18; int *ptr = &i; int **ptrptr = &p;

Here ptrptr is a pointer to an int pointer ptr and ptr is a pointer to an int. Following figure illustrates the above scenario.

As we can see here we can also use ptrtpr to get value stored in i.


The * operator is evaluated as following. Suppose we have ***x then it is evaluated as *(*(*x)). So we can evaluate it as first get the value stored as address x say y, so expression becomes *(*y). Now again get the value stored at address y say z, so expression is now *z which is value stored at address z.

For our case **ptrptr means get the value stored at address 2000 which is 1000 and then get the value stored at 1000 which is 18.


Summary :
A variable is a memory location with a name given to it and it declared like data-type i;
A pointer variable is declared as data-type *ptr; and it points to a variable declared with same data-type.
A pointer can be assigned value using & operator.
Value of a variable pointed by a pointer is retrieved using * operator.
A Pointer to pointer is a pointer that points to a pointer that is it stores the address of a pointer.
Ads :
Buy Sony, Canon, JVC Cameras on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Sunday, 19 May 2013

Starting file download with Javascript

Ever wondered how many sites triggers download after a given timeinterval or by pressing a button or clicking a link.
In this tutorial I'm going to show you how to various methods initiate downloads from your website.
  1. Simple Old Method :

    This is the simpleset method to start download, just create a <a> and point it to your file location.
     
    <a href="file.ext" > Click Here <a> To Download
    
  2. Javascript based download

    We can use a simple javascript to start file download. We will use window.location method to initiate the download.
    HTML code :
     
    <input type="button" value="Download" onClick="download('file.ext')" >
    

    JavaScript Code:
     
    <script>
    function download(file)
    {
     window.location=file;
    }
    </script>
    
  3. Download using javascript and Iframe

    <iframe id="frame" style="display:none"></iframe>
    <a href="javascript:download('file.ext')">download</a>
    
    <script type="text/javascript">
    function download(path) 
    {
        var ifrm = document.getElementById("frame");
        ifrm.src = path;
    }
    </script>
    
  4. Download using Javascript, Iframe and PHP

    Create a Link :
    <iframe id="frame" style="display:none"></iframe>
    <a href="javascript:download('file.ext')">download</a>
    
    Javascript:
    <script type="text/javascript">
    function download(path) 
    {
        var ifrm = document.getElementById(frame);
        ifrm.src = "download.php?path="+path;
    }
    </script>
    
    Code for download.php file :
    <?php 
       header("Content-Type: application/octet-stream");
       header("Content-Disposition: attachment; filename=".$_GET['path']);
       readfile($_GET['path']);
    ?>
    
  5. Javascript based download with timer

    Above method can be used to start a javascript based timer and at the end of timer download will start.
    Simply put the code in file and it will start the timer.
    After time is up we can either display link or directly start download.
    You can use all of above method with the timer with few changes. HTML code:
     
    <div id="counter-text"> Please Wait For <span id="counter">  </span> Seconds. 
    </div>
    <a href="javascript:download('file.ext')" style="display:none" id="link"> 
    Click To Download </a>
    
    JavaScript Code:
     
    <script>
    time = 5;
    document.getElementById("counter").innerHTML = time;
    timer = setInterval("count()",1000);
    
    function count()
    {
     if(time == 1)
     {
      //Cleare Timer and remove counter from page
      clearInterval(timer);
      document.getElementById("counter-text").style.display="none";
      //If you want to display link
      document.getElementById("link").style.display="block";
      //Or directly start download
      //download('file.ext');
     }
     else
     {
      time--;
      document.getElementById("counter").innerHTML = time;
     }
    }
    function download(file)
    {
     window.location=file;
    }
    </script>
    
Ads :
Buy Apple Iphone 5, iphone 4S On www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Related Posts :

Friday, 17 May 2013

PHP MySQLI Tutorial

What is MySQLI :

The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP programming language to provide an interface with MySQL databases.
MySQLi is an improved version of the older PHP MySQL driver, offering various benefits.
The developers of the PHP programming language recommend using MySQLi when dealing with MySQL server versions 4.1.3 and newer (takes advantage of new functionality).

Why Mysqli :

The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which are:
  • An object-oriented interface
  • Support for prepared statements
  • Support for multiple statements
  • Support for transactions
  • Enhanced debugging support
  • Embedded server support

MySQLi Vs MySQL

MySQLi MySQL
PHP version introduced 5.0 Prior to 3.0
Included with PHP 5.x yes Yes
MySQL development status Active development Maintenance only
Recommended by MySQL for new projects Yes - preferred option No
API supports Charsets Yes No
API supports server-side Prepared Statements Yes No
API supports Stored Procedures Yes No
API supports Multiple Statements Yes No
Supports all MySQL 4.1+ functionality Yes No


Here is a simple code that implements mysqli

<?php


 //CONNECT TO THE DATABASE
 $DB_HOST = 'HOST';
 $DB_USER = 'USERNAME';
 $DB_PASS = 'PASSWORD';
 $DB_NAME = "mysqlitest";

 $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
 
 
 if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
 }

 //CREATE TABLE
 $q = "CREATE TABLE user (id int AUTO_INCREMENT PRIMARY KEY, 
     name varchar(30))";
 $mysqli->query($q);
 
 //INSERT FEW VALUES
 $q = "INSERT INTO user VALUES (NULL, 'abc')";
 $mysqli->query($q);
 $q = "INSERT INTO user VALUES (NULL, 'bcd')";
 $mysqli->query($q);
 $q = "INSERT INTO user VALUES (NULL, 'xyz')";
 $mysqli->query($q);
 
 
 //SELECT A USER
 $q = "SELECT * FROM user WHERE id=3";
 $result = $mysqli->query($q) or die($mysqli->error.__LINE__);

 // GOING THROUGH THE DATA
 if($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
   echo $row['name']; 
  }
 }
 else {
  echo 'NO RESULTS'; 
 }
 // CLOSE CONNECTION
 mysqli_close($mysqli);
?>

Ads :
Buy iPad Tablet eBook Reader on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Wednesday, 15 May 2013

How to upload file to server in android


If you are building an app that requires files to be uploaded on server you will need to follow this method. By using this method,  you will be able to upload a file from your SD Card.

We will be using httpmime-4.2.5.jar for this tutorial. You can download it from here. Extract the zip file and you will find jar file under lib folder.


  1. Create a new android project in Eclipse, and add the jar file to lib folder.
  2. Add android.permission.INTERNET and android.permission.WRITE_EXTERNAL_STORAGE in your manifest file.
  3. Use the following code :
 String address;
 MultipartEntity entity;
 File f;
 FileBody fb;
 entity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);
 address = Environment.getExternalStorageDirectory()
    + "/temp.dat";
 f = new File(address);
 fb = new FileBody(f, "application/octect-stream");
 entity.addPart("file", fb);
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("Your URL Here");
 
 httppost.setEntity(entity);
 HttpResponse response = httpclient.execute(httppost);
 BufferedReader bufferedReader = new BufferedReader(
  new InputStreamReader(
   response.getEntity().getContent()));
 StringBuffer stringBuffer = new StringBuffer("");
 String line = "";
 String LineSeparator = System.getProperty("line.separator");
 while ((line = bufferedReader.readLine()) != null) {
  stringBuffer.append(line + LineSeparator);
 }
 bufferedReader.close();
 return stringBuffer.toString();
 } catch (ClientProtocolException e) {
  return e.toString();
 } catch (IOException e) {
  return e.toString();
 } 
Here we use MultipartEntity from the http library to add file for uploading.
f = new File(address);
fb = new FileBody(f, "application/octect-stream");
entity.addPart("file", fb);
We select the file given by address and then we get filebody using the FileBody Class and then add it to the entity.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Your URL Here");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
We create a new HttpClient and a HttpPost object, set entity and execute the reuqest.
Now android does not allow us to use network operations under the main thread, either we have to create a new thread or we use AsyncTask. You can Find the full source code here or download it here .
You can also use FTP library to uplaod the file which is better than this approach as described here.
Ads :
Buy Hard Drive, RAM, CD, DVD, USB on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

Tuesday, 4 December 2012

Some useful shortcut keys for windows

We often use the mouse to do many things on our pc or laptop. Using mouse is easy but some time slow in accessing some functions. So, we have some shortcut key for many functions that windows provides.
Here is the list :
ctrl + w Closes the current window
ctrl + e
ctrl + f
Reach to the search box (Windows 7)
ctrl + r Refresh
ctrl + n Opens new copy of same window
alt + p Toggle show file preview
alt + d Direct access to address bar
alt + tab Switch windows
alt + space Open command menu
window key + up arrow Maximizes window
window key + down arrow If window is maximized, restores it
else minimizes it
window key + left arrow Move window to left
window key + right arrow Move window to right
window key + e Opens explorer
window key + d Shows desktop
window key + f Open new search window
window key + l Switch user
window key + f Open new search window
window key + x Opens windows mobility center
window key + b reach to notification area
(right side on taskbar)
window key + m minimize current window
window key + tab Switch windows
ctrl + shift + esc Open task manager
ctrl + esc / Window key Open start menu
ctrl + shift + n New folder
windows + number key Open nth item from task bar
(Window+1 will open 1st item)

Ads :
Buy Laptops and netbooks : HP, DELL, SONY, ASUS on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my