Wednesday, March 25, 2009

Create a web service with PHP

[W3C Definition: A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.] For more details visit http://www.w3.org/TR/ws-arch/

In PHP, the soap extension can be used to create soap based web services. http://php.net/soap

This article will shows you how to create a simple web service with PHP.

Soap Server

A simple server that receives a soap request and sends a response.The server takes a name from the client and returns a hello message.

Recommended IDE : Eclipse PDT [ http://www.eclipse.org/pdt ]

Listing 1: HelloServer.php


<?php

// Method

function sayHello($name){

return
"Hello $name";

}

// Create a SoapServer object using WSDL file.

// For the simplicity, our SoapServer is set to operate in non-WSDL mode. So we do not need a WSDL file

$server = new SoapServer(null, array('uri'=>'http://localhost/hello'));

// Add sayHello() function to the SoapServer using addFunction().

$server->addFunction("sayHello");

// To process the request, call handle() method of SoapServer.

$server->handle();

?>


Soap Client

Soap client allows you to communicate with server.

Listing 2: HelloClient.php


<?php

try {



// Create a soap client using SoapClient class

// Set the first parameter as null, because we are operating in non-WSDL mode.

// Pass array containing url and uri of the soap server as second parameter.



$client = new SoapClient(null, array(

'location' => "http://localhost/hello/HelloServer.php",

'uri' => "http://localhost/hello"));



// Read request parameter



$param = $_GET['name'];



// Invoke sayHello() method of the soap server (HelloServer)



$result = $client->sayHello($param);

print
$result; // Process the the result

}

catch(
SoapFault $ex) {

$ex->getMessage();

}



?>

HelloView

Create view for interacting with end-user

Listing 3: Helloview.php

<?php

print "<h3>Welcome to PHP Web Service</h3>";

print
"<form action='HelloClient.php' method='GET'/>";

print
"<input name='name' /><br/>";

print
"<input type='Submit' name='submit' value='GO'/>";

print
"</form>";

?>

locate Helloview.php with your web browser




Tuesday, March 24, 2009

Creating HTML link button

Simple html code to create link button


<input value="Click Me" type="button" onclick="window.location.href='http://codeglobe.blogspot.com'; " >

from, nexabion webhosting kerala cochin

Saturday, March 21, 2009

Read/write BLOB from/to MySQL in Java

This post shows you how to insert an image into MySQL database through Java

Step 1 : Open MySQL client
Step 2 : Execute the following query

CREATE TABLE IF NOT EXISTS `image` (
IMG blob,
IMG_ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`IMG_ID`)
)

Source code
-----------


import java.awt.event.ActionEvent;
import java.sql.*;
import java.awt.Graphics;

import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;



/**
*
* @author mustaq
*/
public class ImagePanel extends JPanel implements ActionListener {


JButton browse;
Connection con = null;

public ImagePanel() {
con = this.getConnection();
browse = new JButton("Browse");
browse.addActionListener(this);
this.add(browse);
}
public Connection getConnection() {
try {
// Creating connection to DB
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/image";
Connection c = DriverManager.getConnection(url,"root","");
return c;
}
catch(Exception ex) {
System.out.println(ex.getMessage());
return null;
}

}
public void imageWrite(File file) {
try {

FileInputStream io = new FileInputStream(file);
String query = "insert into image(IMG) values(?)";
java.sql.PreparedStatement stmt = con.prepareStatement(query);
stmt.setBinaryStream(1, (InputStream)io,(int)file.length());
stmt.executeUpdate();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
public BufferedImage getImageById(int id) {
String query = "select IMG from image where IMG_ID = ?";
BufferedImage buffimg = null;
try {
PreparedStatement stmt = con.prepareStatement(query);
stmt.setInt(1,id);
ResultSet result = stmt.executeQuery();
result.next();
InputStream img = result.getBinaryStream(1); // reading image as InputStream
buffimg= ImageIO.read(img); // decoding the inputstream as BufferedImage

}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
return buffimg;
}
@Override
public void paint(Graphics g) {

BufferedImage img = this.getImageById(5) ; // pass valid IMG_ID
if(img != null)
g.drawImage(img, 70, 20, this);

}
public static void main(String[] args) {
JFrame frame = new JFrame("ImagePanel Demo");
ImagePanel imgPanel = new ImagePanel();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(imgPanel);


}
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
File file = null;
if(returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile(); // path to image
this.imageWrite(file); // inserting image into database
JOptionPane.showMessageDialog(this, "Image inserted.", "ImageDemo", JOptionPane.PLAIN_MESSAGE);
this.repaint();

}
}

}

Javascript For Not Working Back Button in a WebPage

This is My first Post in Code Globe

/*
window.history.forward(1);
*/

Wednesday, March 18, 2009

SQL Server Date Time Formats using Query

We can format the sql server 'datetime' field into a specific date time format. SQL Server provides this functionality through an inbuilt function called CONVERT(). For Example you can get the date format in dd/mm/yy by using the following query.

Select Convert(Varchar(10),GetDate(),3) from your_table_name.

Look at the third integer parameter you are passing(i.e. 3), which does the formating part.

Following are the values and thier corresponding formats :

1----------------- mm/dd/yy
2-----------------yy.mm.dd
3-----------------dd/mm/yy
4-----------------dd.mm.yy
(And so on. Other format numbers range from 100-114, 120,121,126,130,131) .Try it n see the results yourself.....enjoy

Bulk inserting values from one table to another table

There may be situations when you need to copy records from one table to another on a specific condition. This is can be achieved by simply using the insert and select combination in your sql query. For example the following query copies the names of employees(emp table) who are managers(Manager table).

insert into Manager(name) select name from emp where designation ='mngr' .

NB:The number of fields you are selecting must be equal with the inserting fields.

The art of Decompilation

Decompilation


Decompilation is the reverse process of compilation i.e. creating high level language code from machine/assembly language code. At the basic level, it just requires to understand the machine/assembly code and rewrite it into a high level language, but things are not as simple as they seem, particularly when it comes to implementing a decompiler. Throughout this discussion, we will be using the C language for the high level language, and the 8086 assembly language for the low level language.

The ethics of decompilation

Is decompilation legal, and is it allowed?

There are many situations when decompilation can be used...

  1. To recover lost source code. You may have written a program for which you only have the executable now (or you got the exe of a program you wrote long back, from someone else!). If you want to have the source for such a program, you can use decompilation to recover it. In all rights, you are the owner of the program, so nobody is going to question you.
  2. Just as stated above, applications written long back for a legacy computer may not have the source code now, and you may need to port it to a new platform. Either you have to rewrite the application from the scratch, or use decompilation to understand the working of the application and write it again.
  3. Say you have code written in some language for which you cant find a compiler today! If you have the executable, just decompile it and rewrite the logic in the language of your choice today.
  4. To discover the internals of someone else's program (like what algorithm they have used...)

Usually all software are copyrighted by the authors. This means, copying or expressing the same idea in another program is prohibited. Hence if you are using decompilation to discover the internals of a program and if that particular part is breaching the copyright of the owner, you are liable for legal action. However, there are some permitted uses of decompilation, like the first three cases stated above. Also, decompilation of parts of software which do not come under the copyright laws (e.g. algorithms) is permitted. In any case, it is better to contact your legal advisor if you are doing any serious work with decompilation.

In all practical purposes, decompiling programs which were created by you can't be questioned! After all, you are the owner of all rights to the program. But be careful if you are trying it out on someone else's programs.

Is decompilation possible?

Let's take a look at a normal C compiler. When a C program is compiled, the first stage of the compiler will generate a very rudimentary assembly language output (or nearly equivalent to it), which is nothing but a line-by-line translation of the C source code. If any optimizations are chosen to be done, the next stages perform the code optimization to replace redundant instructions and improve the overall efficiency of the output program. This output is then linked with the standard libraries for any library function calls, and saved in the executable format of the platform.

void main()
{
int i, j, k;

i = 10;
j = 20;

k = i*j + 5;
}

 ;---- i = 10;
mov [bp+2], 10
;---- j = 20;
mov [bp+4], 20
;---- k = i*j + 5;
mov ax, [bp+2]
mov bx, [bp+4]
mul bx
add ax, 5
mov [bp+6], ax
Sample C code
Possible output of a compiler
(without optimizations)

If no optimizations are performed while the code is generated, it is very easy to understand what the output code does, and an equivalent C code can be written/generated automatically. Note that we can only generate "an equivalent C code", and not the "same C code" which was compiled to get this executable. In other words, it is always impossible to get the exact source code, but we can generate an equivalent program which will function in the same way.

However, things are a bit different if any compiler optimizations are used while building the original executable. It turns out to be more difficult to understand the flow of the program now, and the more rigorous the optimizations are, the worse are our chances to figure out what the code is doing exactly.

void main()
{
int i, j, k;

i = 10;
j = 20;

k = i*j + 5;
}

 ;---- i = 10;
mov si, 10
;---- j = 20;
mov di, 20
;---- k = i*j + 5;
mov ax, si
mov bx, di
mul bx
add ax, 5
mov [bp+6], ax

 ;---- k = i*j + 5;
mov ax, 10
mov bx, 20
mul bx
add ax, 5
mov [bp+6], ax
Sample C code
Possible output of a compiler
(using register variables)

Possible output of a compiler
(using code optimization)

One more factor which joins the opposition is that each compiler generates code in its own way. There are very few points where all compilers generate similar code. This means that we need to tailor the decompilation procedure for each compiler, so that if we know which compiler was used to generate this executable, we have a better chance of understanding the code.

For example, the simple "if" statement can be compiled in many ways, like the one given below.

  if (i>20)
{
j=30;
}
else
{
j=40;
}
j++;

    cmp [bp+2], 20
jle lab1

mov [bp+4], 30
jmp lab2
lab1:
mov [bp+4], 40
lab2:
inc [bp+4]

    cmp [bp+2], 20
jg lab1
jmp lab2
lab1:
mov [bp+4], 30
jmp lab3
lab2:
mov [bp+4], 40
lab3:
inc [bp+4]
Sample "if" statement
Possible output #1
Possible output #2

Some other factors which hinder the decompilation process are

1. Self modifying code
Code written for critical applications like games, where every machine cycle counts for the performance, sometimes self-modifying code is used. For example, if the same condition is used at many places in a critical loop, it is evaluated once and the code after that is modified to branch to the same location without evaluating the condition again. But with today's processor speeds, this technique is fast becoming antique!
2. User-defined datatypes
User defined data types, like "struct"s, "typedef"s, "union"s and bit-fields add more to the confusion of the decompiler. Though it is easy to use structures while writing the code, it is almost impossible to figure out if a variable is a part of a structure or is it a basic type on its own, by looking at the compiled output.
3. Use of processor-specific instructions/optimizations

Inspite of all these reasons, it is still possible to decompile a binary executable (though not 100% automated, and not 100% accurate!). Carry on reading...

How to decompile?

A simple approach to decompile a binary executable, is to first parse it and separate it into functions (C style). Once we know where the entry point of the program ("main" for a C program), we can start decompiling that function, and any other function it calls. This way, we can focus on one function at a time carefully.

To use this approach, the first thing that should be known is the entry-point of the program. For a normal C program, it is the "main" function, and for a Win32 program, it is the "WinMain" function. But to find out where these functions begin, we must analyze the executable and figure out which compiler was used, because each compiler has its own entry/exit code added to the program which we need not decompile. If the compiler used is known, we can trace out where the "main" function is starting, and from thereon, till we get a "return" instruction, we can separate out the function.

A simple method to decompile a code snippet

Let's say we have separated out the instructions for a function. To understand how this piece of code works, we need to emulate the processor, and interpret each and every machine instruction! (though it seems a roundabout way, there is nothing called the best method to understand the working of the code, so this is not the only way. If you think this can be done in some other way, please try it out and i'd be interested to hear about it.). And as we are interpreting the code, we need to combine logical group of instructions into simple high level language statements. And voila! We've decompiled the function!

The high level language statements can be grouped as assignment statements, condition evaluation and branches, and function calls. While interpreting the machine code for a function, we have to look for instructions which fall in one of these categories, and accordingly generate the high level code.

Understanding assignment statements and expressions

Take a look at the following code snippet.

   mov ax, [bp+4]
mov bx, 20
mul bx
add ax, 4
mov [bp+4], ax
Sample expression eval & assignment.

It is not difficult to understand what it does. To put it in steps,

  1. AX is loaded with value from memory [bp+4]
  2. BX is loaded with value 20
  3. AX and BX are multiplied, and the result is in DX:AX (of which we will ignore DX for the time being)
  4. A value of 4 is added with AX
  5. The result in AX is stored in memory location [bp+4]

And we can easily write a program which will interpret this code. Let's say we have two variables wAX, wBX. The above 5 steps can be translated by our program as

  1. wAX = [bp+4]
  2. wBX = 20
  3. wAX = wAX*wBX = [bp+4]*20
  4. wAX = wAX+4 = ([bp+4]*20) + 4
  5. [bp+4] = wAX = ([bp+4]*20) + 4

And if we substitute a variable name "i" for "[bp+4]", we have arrived at the high level language statement

i = ( i*20 ) + 4;

That was pretty easy, wasn't it? But then, when do we decide that we have got a full high-level language statement? Whenever there is a instruction which stores some value to external memory, it is a full high-level language statement by itself. Just think about it. All the following high-level language statements inevitably end with a memory store operation!

i = 0;
x = i*30 + (j>>1)+(i/2)
k = (i & 2) + z;

Understanding condition evaluation and branches

A condition evaluation almost always uses a "compare" instruction. So while interpreting the machine code, if we get a "cmp" instruction, we translate it into a "if" statement, and the branch instruction that follows this compare will lead us to the block of code which gets executed if the condition is true, and if it is false.

The following code snippet illustrates this.

   mov ax, [bp+4]
cmp ax, 10
jnz lab1

mov bx, 15
mov [bp+2], bx
jmp lab2
lab1:
mov bx,20
mov [bp+2], bx
lab2:
Sample condition eval & branch.

When we are interpreting this code and come across the "cmp" instruction, the value in our variable wAX is "[bp+4]" (which is a memory variable). So we now form a condition between "[bp+4]" and "10". But what are we comparing for? That can be found using the branch instruction which comes next. Since we find a "jnz" instruction ("jnz" means "jump if not zero", or "jump if not equal"), we can conclude that this is a equality compare i.e. we are comparing for "[bp+4]!=10". The rest is pretty easy, and after replacing "[bp+4]" with a name "i", we can generate the C code for this as below.

if (i != 10) goto lab1;
j = 15;
goto lab2;
lab1:
j = 20;
lab2:

After a bit of rearrangement, and removing the "goto" statements, we can get the 'beautified' C code as

  if (i!= 10)
{
j = 20;
}
else
{
j = 15;
}

But beware! Conditions need not always be evaluated using "compare" instructions. Even arithmetic instructions can set/reset the conditions flag bits in the processor's FLAGS register, and it is these condition flag bits which are actually used to determine if a branch should be taken or not! A classic example is the C statement "i--", as shown below.

 if (i--)
j = 20;
j++;

   sub [bp+4], 1
jz lab1
mov [bp+2], 20
lab1:
add [bp+2], 1
Sample "if" statement
Branch without "compare"

So if we come across such code, we must look at the previous arithmetic instruction, and find out which variable/expression is actually used as the condition.

Interpreting function calls and return values

Function calls are a bit different. The usual "C" convention of function calling, is to push the parameters (last parameter first!) onto the stack, and then call the function. The function will read the values from the stack, and the return value is usually placed in some register (usually the "AX" register). So the trick we can use here is, whenever we find a "push" instruction (which pushes a value on the top of the stack) we make a note of it. And eventually when we reach a "call" instruction (which is actually a subroutine branch instruction), we look at our variables to see what all values/variables have been pushed to the stack, and put them in reverse order to create the high-level C language statement for the function call!

The example for this method is given below. Please note that the code on the right is obtained after replacing "[bp+4]" with "i" and "[bp+2]" with "j".

 mov ax, [bp+4];
push ax
mov ax, [bp+2];
push ax
call _func
mov [bp+4], ax

 
i = func(j, i);
Sample function call
Equivalent C source code.

SQL INJECTION

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL Injection Example

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:

// a good user's name
$name = "timmy";
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "
";

// user input that uses SQL Injection
$name_bad = "' OR 1'";

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''

The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.

However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query

  • username = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

  • username = ' ' OR 1

This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!

More Serious SQL Injection Attacks

Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

MySQL & PHP Code:

$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";

// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";

// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' '

If you were run this query, then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

Injection Prevention - mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.

What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.

Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'";

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection:
" . $query_bad . "
";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection:
" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

Notice that those evil quotes have been escaped with a backslash \, preventing the injection attack. Now all these queries will do is try to find a username that is just completely ridiculous:

  • Bad: \' OR 1\'
  • Evil: \'; DELETE FROM customers WHERE 1 or username = \'

And I don't think we have to worry about those silly usernames getting access to our MySQL database. So please do use the handy mysql_real_escape_string() function to help prevent SQL Injection attacks on your websites. You have no excuse not to use it after reading this lesson!

Tuesday, March 17, 2009

Zion SMS

ZION SMS

Zion SMS 1.1 Beta is an application used to send your txt files stored in your external or internal phone memory.
You just need to browse and locate the text file that you wish to send.
After locating you can also modify that file.Then click done the text file is now ready to send.
Put recipient's address and click send.
Then wait for a while to verify that whether the message has been send or not.
It is mainly designed to send txt files in your mobile,you can place text files(file with extension .txt) in your mobile
from a PC or u can use 'ZION PLUS' editor.
I recommended you to store your files in the other(in external memory) because its quick search feature allows you to search for files in that folder,so you can easily locate your desired file.Note:This quick search is mainly designed for sony ericsson users.
You can try this application by clicking the following link.If you like this application post your comments to
e-mail:xpedition009@gmail.com or send an SMS to 09496340837,you will get the registration number.



Download Zion SMS Beta

Wednesday, March 11, 2009

MySQL Backup in java

This tutorial shows you to backup your MySQL database using java (Windows PC) First you have to create a batch file, say bak.bat,


mysqldump -umysql-user -pmysql-password dbname > c:\backup.sql

java method

public boolean doBackup() {
Runtime rt;
try {
rt = Runtime.getRuntime();
Process run = rt.exec(bak.bat); // specify the correct path to batch file, eg:- c:\bak.bat
}
catch(Exception ex) {
//exception handlers
return false;
}
return true;
}

The method will write backup.sql file into C drive



LinkWithin

Related Posts with Thumbnails