Posts Tagged ‘Lt’

Alternating table row colors in php

Sunday, January 3rd, 2010

Most of the websites use this alternating color to tables which will make the user readability of table content. We can use any of the colors you want.

I am writing php code which will print the data present in the mysql table in a alternating color format.

<?php

//Database Connection inputs

$host=”localhost”; // Host name
$username=”"; // Mysql username
$password=”"; // Mysql password
$database=”mydb”; // Database name
$table=”mytable”; // Table name

// Connect to server and select databse

mysql_connect(“$host”, “$username”, “$password”)or die(“cannot connect”);
mysql_select_db(“$mydb”)or die(“cannot select DB”);
$sql=”SELECT * FROM $mytable”;
$result=mysql_query($sql);

// Define $color=1, this is a temporary variable to define color.

$color=”1″;

echo ‘<table width=”200″ border=”1″ cellpadding=”2″ cellspacing=”0″>’;
while($rows=mysql_fetch_array($result))

{

// If $color==1 table row color = #FFC600
if($color==1)

{
echo “<tr bgcolor=’#FFC400′>
<td>”.$rows['firstname'].”</td><td>”.$rows['lastname'].”</td><td>”.$rows['age'].”</td>
</tr>”;
// Set $color==2, for changing the color
$color=”2″;
}

// When $color not equal 1, use this table row color
else

{
echo “<tr bgcolor=’#C3FF00′>

<td>”.$rows['id'].”</td><td>”.$rows['name'].”</td><td>”.$rows['email'].”</td>
</tr>”;
// Set $color back to 1
$color=”1″;
}
}
echo ‘</table>’;

?>

Alternate colors for table rows

Alternate Color Table Format

You can also use CSS files instead of specifying the color.

td .d0

{

background-color: #FFC600;

}

td .d1

{

background-color:#fff

}

Linux Keylogger in Ubuntu

Sunday, October 25th, 2009

I am searching for a keylogger for Ubuntu Linux. Finally I found it in sourceforge.net. Here are the simple steps for keylogger in ubuntu

What is Keylogger?

Keystroke logger is the practice of noting (or logging) the keys struck on a keyboard, typically in a covert manner so that the person using the keyboard is unaware that their actions are being monitored. There are numerous keylogging methods, ranging from hardware- and software-based to electromagnetic and acoustic analysis.

keylogger in Linux

We have an opensource software available for Linux called lkl (Linux Key Logger).

LKL is a userspace keylogger that runs under linux–x86/arch. LKL sniffs and logs everything passes trought the hardware keyboard port (0×60).

Download key logger here

How to Install?

Step 1

Unzip or untar the file you have downloaded

Step 2

Change in to directory by typing cd lkl

Step 3

Give the below command

./confiure

This will check all the required resurces it needs

Step 4

Type `make‘ to compile the package.

Step 5

Optionally, type `make check’ to run any self-tests that come with the package.

Step 6

Type `sudo make install‘ to install the programs

Now you are done with the installation

How to use?

You can send argument with the command lkl
-h help
-l start to log the 0×60 port (keyboard)
-b debug mode
-k <km_file> set a keymap file
-o <o_file> set an output file
-m <email> send logs to <email>
-t <host> hostname for sendmail. Default is localhost

Example: lkl -l -k us_km -o log.file // use USA kb and put logs in ‘log.file’

Please comment on the same if it doesn’t works for you

Sending data via XMLHttpRequest POST in PHP

Friday, July 24th, 2009

Implementing an AJAX feed data to a PHP script, and usually by sending data via GET, it had not experienced major problems, however this time the number of bytes far exceed the limited capacity of the GET. Before proceeding further, to clarify this point that we have reference …

Do limit the number of characters that can be passed by GET ($ _GET)?

In mid-1998 was published the HTTP protocol specification, a fairly complete, but inaccurate in the ceiling of the data transferred via GET, so long after the browsers by themselves have released their own specifications .

We emphasize the limits of the most popular:

  • Internet Explorer: 2.083 caracteres
  • FireFox: 65.536 caracteres
  • Safari: 80.000 caracteres
  • Opera: 190.000 caracteres

Thus

Depending on the same platform and web server, we must consider other standards, such as for example:

  • Apache: 4.000 caracteres
  • Microsoft Internet Information

Considering this could easily determine that the data above 2000 characters is preferable to pass POST.

Now, returning to the subject in which I lifted this morning, I commented that it is very common in the lives of professional development due to physical and mental fatigue, in many cases can last for hours solving one problem, otherwise we just take a few minutes.
In this case was no exception :-)

The original code that sends data via GET as follows:

<span onmouseover=”_tipon(this)” onmouseout=”_tipoff()”><span style=”direction: ltr; text-align: left;”>xml.open(‘get’, ‘http://www.webnesbay.com/script.php?variable_get=hello’);</span> xml.open ( ‘get’, ‘http://www.webnesbay.com/script.php?variable_get=hello”);</span>
<span onmouseover=”_tipon(this)” onmouseout=”_tipoff()”><span style=”direction: ltr; text-align: left;”>xml.onreadystatechange = handleResults;</span> xml.onreadystatechange = handleResults;</span>
<span onmouseover=”_tipon(this)” onmouseout=”_tipoff()”><span style=”direction: ltr; text-align: left;”>xml.send(null);</span> xml.send (null);</span>

Now, so we can send data by POST, so we must add a header data, as I do below:

<span onmouseover=“_tipon(this)” onmouseout=“_tipoff()”><span class=“google-src-text” style=“direction: ltr; text-align: left;”>xml.open(‘post’, ‘http://www.webnesbay.com/script.php?variable_get=hola’);</span> xml.open ( ‘post’, ‘http://www.webnesbay.com/script.php?variable_get=hello’);</span>

<span onmouseover=“_tipon(this)” onmouseout=“_tipoff()”><span class=“google-src-text” style=“direction: ltr; text-align: left;”>xml.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded; charset=ISO-8859-1′);</span> xml.setRequestHeader ( ‘Content-Type’, ‘application / x-www-form-urlencoded; charset = ISO-8859-1′);</span>

<span onmouseover=“_tipon(this)” onmouseout=“_tipoff()”><span class=“google-src-text” style=“direction: ltr; text-align: left;”>xml.send(“variable_post=1&variable_post2=1″);</span> xml.send (variable_post = 1 & variable_post2 = 1 ”);</span>

The problem was that to send data by POST need to send a previously that allows us to store the contents.

Special shortcuts in Perl

Thursday, July 2nd, 2009

Perl is renowned for being a language where you can express complicated commands in a very small amount of space. In this article, following up from my last Perl article, we’ll explore a little bit about how this is possible.

We’ll start with the simplest of programs, which simply reads in characters from the keyboard and repeats them back to the console. In Perl you might write this like so:

while ($line = <STDIN>) {
    print $line;
}

Even to start this program is quite compact, but what does it do? Simple: <STDIN> is a special file handle, in this case belonging to the standard input buffer (called STDIN), which is usually connected to the keyboard. Each time we assign <STDIN> to the variable $line we take the top line off the STDIN buffer and put it in $line. When the buffer runs out of lines, it returns EOF, which the while statement treats as being false. The rest of the program is fairly self explanatory, now that we have the input line in the variable $line then we use the print function to print it to screen, or more accurately, the standard output buffer (STDOUT), which is usually connected to the screen. Both the standard input and standard output buffers can be redirected, for example to files for storing the output of programs, but if you’re dealing with text it’s usually safe to assume they’re equivalent to the keyboard and screen.

You may think that this program is already as short as it can be, but through using Perl’s special variables, we can make it shorter:

The default scalar variable: $_

Perl has a number of special variables that are automatically assigned in the general course of a program, they can be used to access information about the program itself, such as the name or process id, the command line arguments, or the results of the last regular expression. The most general, and maybe the most useful of these special variables is $_, the default variable. The default variable is where the results of some Perl constructs and functions are put if you don’t specify an assignment, and is used as the argument to certain functions if none is given. This sounds vague and can be confusing until you’re familiar with it, but it can also be powerful. We can use $_ to eliminate the need for the variable $line in our program:

while (<STDIN>) {
    print $_;
}

This program is equivalent since when a file handle is used by itself in the test of a while statement, it puts its input into the default variable. Then when we print we can just reference $_ to access that input. But we can make this program shorter. Remember when I said that $_ is used as a default argument for some functions if none is given, well print is one of those functions. So we can now write this program as follows:

while (<STDIN>) {
    print;
}

Now we’ve got a program that does the same thing, but eliminates explicit variables all together. Since we’re really just connecting STDIN to STDOUT it would be nice if we could get rid of that while loop, it’s not doing anything interesting except iterating over the buffer. Well, this too is possible:

print <STDIN>;

How this works is a little more complicated. When we use $_ with print, we put the variable into what’s called a scalar context, meaning simply that it is treated as an individual object, such as a number or a character, and not a collection. print can also be used in an array context, meaning that the argument is treated like a list of objects, when used with print this will print each one in turn. When we use the file handle <STDIN> with print in this way it will treat standard input as an array of strings and print them in order, which has the same result of the while loop. It might be an extreme example, but by using a few Perl shortcuts we’ve cut the length of our program in half.

This is fine if we just want to mirror STDIN to STDOUT, but what if we’d like our program to act more like the Unix filter cat, which can open and print files as well. Now we could check the command line arguments and test to see if they’re valid files, open and print them in order, but since this is such a common thing to do Perl has an easier (and shorter!) way.

The special file handle: <>

Like the default variable, the special file handle — written as <> is a short cut in the language added to make programs easier to write. The special file handle treats all command line arguments as file names, and opens each in turn. If there are no command line arguments then it opens and reads from STDIN. As per the UNIX convention, if “-” is given as a command line argument it opens STDIN in place of a file. So if we wanted to write a version of the above program that could support files given on the command line it would be as simple as:

print <>;

When you consider that you can write a working implementation of cat in only eight characters, you can see why Perl is considered so powerful. But what if we want to do something more significant with the input rather than just echo it back to the screen?

Counting Line Numbers

If we want to process the lines of the input individually then it’s not enough to just link the file handle to print, let’s take a look at a simple program to add line numbers to the lines of input:

$num = 0;
while (<>) {
    $num = $num + 1;
    print "$num\t$_";
}

In this example we use the variable $num to keep track of the line number. For each line of input we increment this number, then print out the number and the line of input together. When we refer to variables inside strings with double quote characters (“) the variable name is replaced with the contents of that variable, this makes formatted output in Perl a breeze.

Even with these simple programs, it’s easy to see how using special variables can make your programs smaller and faster to write. If you’re interested, information about all of Perl’s special variables can be found in the perlvar section of the Perl manual

Sockets and TCP/IP Networking using PERL

Thursday, July 2nd, 2009

Perl provides support for the socket API natively. Although the interface is not that bad anyway, there is also a very convenient module, IO::Socket that works like a wrapper on the native API and provides a simpler and easier way to deal with sockets. We’ll use IO::Socket in this tutorial to demonstrate writing two simple programs that communicate with sockets.

The Receiver

The first thing we need to do is to create a socket. We will use it to receive connections. The code below shows how to create a receiving socket. Note that we need to specify the local hostname and the port to which the socket will be bound. Of course, if the port is already in use this call will fail. Also note the ‘Listen’ parameter: this is the maximum number of connections that can be queued by the socket waiting for you to accept and process them. For the time being we will only accept a maximum of one connection at any time. (This means that a connection attempt while we’re dealing with another connection, will return with an error like ‘connection refused’) Finally the ‘Reuse’ option tells the system to allow reuse of the port after the program exits. This is to ensure that if our program exits abnormally and does not properly close the socket, running it again will allow opening a new socket on the same port.

use IO::Socket; 
my $sock = new IO::Socket::INET ( 
                           LocalHost => 'thekla',LocalPort => '7070', 
                           Proto => 'tcp', 
                           Listen => 1, 
                           Reuse => 1,
                                 ); 
die "Could not create socket: $!\n" unless $sock;

Now the socket is ready to receive incoming connections. To wait for a connection, we use the accept() method which will return a new socket through which we can communicate with the calling program. Information exchange is achieved by reading/writing on the new socket. The socket can be treated like a regular filehandle.

my $new_sock = $sock->accept(); 
while(<$new_sock>) 
print $_;
}
close($sock);


The Caller

The other side of the communication is even simpler. All we need to do is to create a socket specifying the remote address and port. The constructor will return a socket object after the connection has been etablished, and we may start sending data right away by writing onto the socket like any other filehandle.

use IO::Socket; 
 my $sock = new IO::Socket::INET 
      (                                   
          PeerAddr => 'asomatos',
          PeerPort => '7070',
          Proto => 'tcp', 
      ); 
die "Could not create socket: $!\n" unless $sock; 
 print $sock "Hello there!\n"; 
 close($sock);


Go ahead and try it!

You can easily try out the example programs above. All you need to do is execute the receiver first and then the sender. On the receiver end, you will see the line “Hello there!” printed on the terminal screen. If you do not have a network, you can still use ‘localhost’ for the hostname of both the receiver and caller just to test it out.

Synchronization

An important issue to consider in this style of communication is that the two ends must follow a commonly-agreed procedure of data exchange. Otherwise it is very easy to end up in a deadlock situation where either both ends try to read, or both ends try to write. Ther is no way to guess whether the other end has finshed sending data, unless there is some protocol of communication between them that denotes logical sections of the communication in the contents of the transmitted messages. In the example above, the model is very simplistic: The caller sends a message and closes its end of the connection, while the receiver just reads the data until it’s all finished. Usually client-server transactions consist of a caller (the client) sending a request, followed by the receiver (server) sending back a reply. In order for the server to understand when the request is finished, there is some agreed marker (such as two consecutive empty lines, or a line saying “END REQUEST”) that denotes the last line in the request. The server, starts sending its reply only after this line has been received, and afterwards closes the socket. The receiver, after sending the entire request switches to reading until the socket is closed, so it will receive the reply. More complex schemes can be established in a similar mannere, according to your needs and taste. What is important is to make sure that the two ends of the communication have a way of knowing when to speak and when to listen, thus avoiding the possibility of getting locked up.


search & replace in several files in perl script

Sunday, June 14th, 2009

This is a script I use whenever I need to do search and replace in a bunch of files. It was meant as a quick hack, but since I does exactly what I need, I continue to use it (always make a backup of the original files in case something goes wrong).

 #!/usr/bin/perl -w
 #
 # More scripts and tips can be found at
 # http://www.edlin.org/
 #
 # Search and replace in several files
 #
 # I throw this file in my ~/bin/
 # Edit the variables $search, $replace and perhaps you want to change the globbing
 # then I jump to the directory with the files and just execute msr.pl (make sure that ~/bin is in your $PATH)

 use strict;

 my @infiles = glob("*.html");

 my $search ='dilbert';
 my $replace ='wally';

 # Here we go.........

 foreach my $file (@infiles){
   print "Processing $file\n";
   open(FH,$file) || die "Cannot load $file";
   my @lines=<FH>;
   close(FH);
   my $match=0;
   foreach my $line (@lines){
     if($line =~ s/$search/$replace/g){
       $match=1;
     }
   }

   if($match){
     print "...Saving $file\n";
     open(FS,">$file") || die "Cannot save $file";
     print FS @lines;
     close(FS);
   }
 }

output

when hacking some scripts it is useful to use $0 when printing out stuff, that way you can figure out which scripts that generate the output if you end up having scripts that use others scripts etc.

 print "$0: Some output from script $0\n";