Wednesday, 19 November 2014

Using Regular Expressions with PHP

PHP provides rich support for regular expression. Regular expressions or RegEx can be used for pattern matching, replacing a particular part of string or to extract some part of string.

RegEx are string of characters that defines a particular patter and has its own rules.
There are two types of RegEx :
  • POSIX Regular Expressions
  • PERL Style Regular Expressions

We will see only POSIX style RegEx in this tutorial.

What is a Regular Expression

RegEx is a string of character. For example, a is a regex, \"([^\"]+)\" is also a regex and so is [0-9]+([a-z]).* In the first sight it looks very weird but as we go along the tutorial it will become easy for you to understand these patterns.

Matching with literals

Literals matches exact characters they specify.For example, "/abc/" is a regular expression. It will match strings which has string "abc" as a sub string, like abcdef, xyzabc, xyabcef etc. The forward slashes at the begin and end are called delimiters. They mark the start and end of pattern. They should be same and can not be backslash or any alphanumeric character that is you can use /,|,: etc.

Matching start and end

Consider the pattern "/abc/". As we saw it will match "abcdef", "xyzabcdef". Suppose we want that "abc" should only come at the beginning, that is we dont want to match "xyzabcdef". We can use ^ for the purpose. Anything that comes after ^ should come in the beginning of the subject string. Thus "/^abc/" will only match "abcdef" not "xyzabcdef".
Just like ^, $ matched end on the string. So "/abc$/" will match neither "abcdef" nor "xyzabcdef", but it will match "defabc".
Some particular examples :
"/^$/" will match empty string
"/^abc$/" will match only "abc", i.e. none of "abcdef", "xyzzbcdef", "defabc" is matched, only "abc" gets matched.

Giving Range with brackets

Brackets [] can be used in a regex to specify a range. For example, [0-9] matches single digit from 0 to 9. Consider [a-z] which matched any lower case alphabets. Consider the pattern, "/^[a-z][a-z][0-9][0-9]/" it will match any string starting with a small case alphabet and followed by a small alphabet and two digits. So it will match "aa10", "xy44"; but not "12fv","ddrt", "1123". The ^ character when used at starting of pattern it will indicate start of the subject string. But inside the [] it has a special purpose of negation. For example "/^[^0-9]/" will match any string that DOES NOT start with a number. Here first ^ marks the beginning of the string while the second one inside the brackets gives negation.

Giving choices

Suppose we want to match a pattern where first character is either a digit or a alphabet and followed by two digits. From above examples a simple solution would be to first check "/^[a-z][0-9][0-9]/" and if it does not match we check for "/^[0-9][0-9][0-9]/". But this is not a good solution as you have to write case for each choice that is possible. For example consider date-month-year pattern, where date can 0 followed by a digit or 1 followed by a digit or 2 followed by digit or 3 followed by either 1 or 0; month can be 0 followed by a digit or 1 followed by 0 or 1 or 2; year is any two digits. If we use above method and write code it will be really cumbersome to write and prone to error. Fortunately RegEx provides | symbol for making choice. Consider our first example, if want a alphabet OR digit followed by two digits, our patter would be "/^[a-z]|[0-9][0-9][0-9]/". | serves as OR in patters. Remember | needs patterns on both side. Also pattern "/a|bc/" will match (a OR b) and then c; not a OR (b and then c). We can use parenthesis for easy reading like: "/(a|b)c/".

Using Quantifiers

Quantifiers are used to match long repeating string of pattens. For example, assume that we want to match a string containing only numbers. It is not possible to do directly using any of above features. For such kind of situations Quantifiers are provided.
They are +,*,?, {},^,$. We have already seen ^ and $. Here is a short explanation of rest.

Quantifier Use
* Matched zero or more occurrence of preceding pattern.
+ Matched one or more occurrence of preceding pattern.
? Matched zero or one occurrence of preceding pattern.
{min,max} Matched occurrence of preceding pattern min to max times.
{min,} Matched occurrence of preceding pattern atleast min times.


Here are some examples:
Quantifier Use
a* Matches empty string,a,aa,aaa,aaa...
a+ Matches a,aa,aaa,aaa...
Can be thought as aa*
a? Matches empty string or a.
{2,5} Matched occurrence of preceding pattern min to max times.
{min,} Matched occurrence of preceding pattern at least min times.


Escaping

Sometimes you want to match symbols like '[', or ' / ' in the string with the string, which are actually a part of the pattern syntax. Thus, it is necessary to distinguish weather we want to use a particular symbol as an literal or as a part of RegEx. "\" (without quotes) is used for this. So if you want to match / you would actually use \/. It called escape sequence. Same goes for other symbols like, \[, \" etc.

Remembering with parenthesis

Suppose you want to extract an IP address from a line of text. IP addresses are like, 127.0.0.1, 192.168.2.6. They are 4 numbers separated by dots and say we want all four numbers separately. From what we have learned its hard to do this. However with parenthesis at our help this becomes really easy. Pattern "/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/" will match the IP address. Now if you want to extract some part of matched string from pattern, you can parenthesis that part and the use references to it. Thus, "/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/" can be used to remember four numbers of IP address that can be accessed later. We will see, how to reference them when we will see PHP functions that uses RegEx. Also note that I have escaped the . because it has a special meaning as we will see next.

The Dot

There is a special symbol "." which is used for matching any one character. You can use if you don't know actual characters in the patter but you know the text, pattern or symbols bounding the required pattern. With the use of above quantifier . is really helpful in many cases. For example suppose you want to find the text in a line between two hash symbols. You don't know what text is, what its length is, it could be empty as well. We use . is situations like this. So for above scenario, "/#(.*)#/" will match #AnyText# and using parenthesis we can extract the text between hashes.

You can practice regular expressions on following site.
regex101.com

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

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