Tuesday, November 6, 2012

How to submit a form using PHP




http://www.webstockbox.com/wp-content/uploads/2008/06/dd_formmailer.gif

How to submit a form using PHP


There are situations when you want to send data using POST to a URL, either local or remote. Why would you want to do this? Probably you want to submit data to an opt-in form, but without taking a valuable visitor away from your site. Or maybe you want to send data to several applications for various purposes, which would be impossible to do in the usual manner. So how can we deal with this problem?

Simulate submitting a form using cURL

So what is cURL anyway? cURL stands for “Client URL", and it is a library of functions that can be used to connect through a wide range of protocols, such as HTTP, FTP, telnet and so on. cURL also speaks HTTPS, so it can be used to communicate with secure servers.
What we are going to use is, cURL HTTP. cURL supports POST and GET methods, file uploads, cookies, user/password authentications, even using proxy servers for connecting.
It can literally be used to programmatically simulate browsing behavior. It can connect to a remote site, login by posting username and password to the login form or by using HTTP authentication, then retrieve pages or upload files. All of this using pure PHP code.

So how do I use cURL to post data?

Begin by creating a new connection.
$curl_connection =
  curl_init('http://www.domainname.com/target_url.php');
A new connection is created using curl_init() function, which takes the target URL as parameter (The URL where we want to post our data). The target URL is same as the "action" parameters of a normal form, which would look like this:
<form method="post" action="http://www.domainname.com/target_url.php">
Now let's set some options for our connection. We can do this using the curl_setopt() function. Go to curl_setopt() reference page for more information on curl_setopt() and a complete list of options.
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl_connection, CURLOPT_USERAGENT,
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
What options do we set here?
First, we set the connection timeout to 30 seconds, so we don't have our script waiting indefinitely if the remote server fails to respond.
Then we set how cURL will identify itself to the remote server. Some servers will return different content for different browsers (or agents, such as spiders of the search engines), so we want our request to look like it is coming from a popular browser.
CURLOPT_RETURNTRANSFER set to true forces cURL not to display the output of the request, but return it as a string.
Then we set CURLOPT_SSL_VERIFYPEER option to false, so the request will not trigger an error in case of an invalid, expired or not signed SSL certificate.
Finally, we set CURLOPT_FOLLOWLOCATION to 1 to instruct cURL to follow "Location: " redirects found in the headers sent by the remote site.
Now we must prepare the data that we want to post. We can first store this in an array, with the key of an element being the same as the input name of a regular form, and the value being the value that we want to post for that field.
For example,if in a regular form we would have:
<input type="text" name="firstName" value="Name">
<input type="hidden" name="action" value="Register">
we add this to our array like this:
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register'
Do the same for every form field.
Data will be posted in the following format:
key1=value1&key2=value2
In order to format the data like this, we are going to create strings for each key-value pair (for example key1=value1), put them in another array ($post_items) then combine them in one string using PHP function implode() .
foreach ( $post_data as $key => $value)
{
    $post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
Next, we need to tell cURL which string we want to post. For this, we use the CURLOPT_POSTFIELDS option.
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
Finally, we execute the post, then close the connection.
$result = curl_exec($curl_connection);
curl_close($curl_connection);
By now, the data should have been posted to the remote URL. Go check this, and if it did not work properly, use curl_getinfo() function to see any errors that might have occurred.
print_r(curl_getinfo($curl_connection));
This line displays an array of information regarding the transfer. This must be used before closing the connection with curl_close();
You can also see number and description of the error by outputting curl_errno($curl_connection) and curl_error($curl_connection).
So let's put everything together. Here is our code:
<?php
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//create cURL connection
$curl_connection =
  curl_init('http://www.domainname.com/target_url.php');
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result = curl_exec($curl_connection);
//show information regarding the request
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
                curl_error($curl_connection);
//close the connection
curl_close($curl_connection);
?>

Post form data without using cURL

If your hosting server does not come with cURL installed (though this is rare as cURL is installed on most commercial hosting servers) and you also don’t have access to server in order to install it, there are alternatives.
One of them is using PHP’s functions fsockopen() and fputs() to send properly formatted data to a remote server. Here is a sample of code that does just this:
<?php
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('www.domainname.com', 80);
//sending the data
fputs($connection, "POST  /target_url.php  HTTP/1.1\r\n");
fputs($connection, "Host:  www.domainname.com \r\n");
fputs($connection,
    "Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>

Tuesday, July 31, 2012

5 Helpful Tips for Creating Secure PHP Applications



5 PHP Security Tips

PHP is one of the most popular programming languages for the web. Sometimes a feature-friendly language can help the programmer too much, and security holes can creep in, creating roadblocks in the development path. In this tutorial, we will take a look at 5 tips to help you avoid some common PHP security pitfalls and development glitches.

Tip 1: Use Proper Error Reporting

During the development process, application error reporting is your
best friend. Error reports can help you find spelling mistakes in your
variables, detect incorrect function usage and much more. However, once
the site goes live the same reporting that was an ally during
development can turn traitor and tell your users much more about your
site than you may want them to know (the software you run, your folder
structure, etc).
Once your site goes live, you should make sure to hide all error
reporting. This can be done by invoking the following simple function
at the top of your application file(s).

  1. error_reporting(0);  
Get rid of those public errors!
If something does go wrong, you still want and need to know about
it. Therefore, you should always make sure to log your errors to a
protected file. This can be done with the PHP function set_error_handler.
Sample Error Log

Tip 2: Disable PHP’s “Bad Features”

From its earliest days, PHP’s designers have always included some
features to make development easier. Or so they thought! Some of these
helpful features can have unintended consequences. I call these “bad
features” because they have allowed data validation nightmares and
created a pathway for bugs to finding their way into scripts. One of
the first things you should do when the development process begins is
disable certain of these features.
Note: Depending on your host, these may or may not be turned off for
you. If you are developing on your own computer or other similar local
environment, they probably won’t be turned off. Some of these features
have also been removed in the upcoming PHP6, but are ubiquitous in PHP4
applications and are only deprecated in PHP5 applications.
Register Globals (register_globals)
In short, register_globals was meant to help rapid application
development. Take for example this URL,
http://yoursite.tld/index.php?var=1, which includes a query string. The
register_globals statement allows us to access the value with $var
instead of $_GET['var'] automatically. This might sound useful to you,
but unfortunately all variables in the code now have this property, and
we can now easily get into PHP applications that do not protect against
this unintended consequence. The following code snippet is just one
common example you will see in PHP scripts:
  1. if( !empty$_POST['username'] ) && $_POST['username'] == 'test' && !empty$_POST['password'] ) && $_POST['password'] == "test123" )  
  2. {  
  3.     $access = true;  
  4. }  
If the application is running with register_globals ON, a user could
just place access=1 into a query string, and would then have access to
whatever the script is running.
Unfortunately, we cannot disable register_globals from the script
side (using ini_set, like we normally might), but we can use an
.htaccess files to do this. Some hosts also allow you to have a php.ini
file on the server.
Disabling with .htaccess
php_flag register_globals 0
Disabling with php.ini
register_globals = Off
Note: If you use a custom php.ini file that is not applicable to the
entire server, you must include these declarations in every sub folder
that has PHP.
Flow of register global
Magic Quotes (magic_quotes_gpc, magic_quotes_runtime, magic_quotes_sybase)
Magic Quotes was a feature meant to save programmers the trouble of
using addslashes() and other similar security features in their code.
There are at least three problems associated with magic quotes. One
problem with this helpful feature is if both magic quotes and
addslashes() are used. If this is the case, then you end up with
multiple slashes being added, causing errors. The second problem is if
you make the assumption magic quotes is turned on and it actually is
not. Then all the input goes unchecked. The third problem is that magic
quotes only escapes single and double quotes, but if you are using a
database engine, there are also many database-specific characters that
also need to be escaped. It is recommended use that you disable this
feature and use proper variable validation instead (see below).
Unfortunately, we also cannot disable magic quotes from the script
side using ini_set. As with register_globals, we can use .htaccess or
php.ini files to do this.
Disabling with .htaccess
php_flag magic_quotes_gpc 0 php_flag magic_quotes_runtime 0
Disabling with php.ini
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
Note: If you use a custom php.ini file that is not applicable to the
entire server, you must include these declarations in every sub folder
that has PHP.
Example htaccess file

Tip 3: Validate Input

In addition to escaping characters, another great to way to protect
input is to validate it. With many applications, you actually already
know what kind of data you are expecting on input. So the simplest way
to protect yourself against attacks is to make sure your users can only
enter the appropriate data.
For example, say we are creating an application that lists users
birthdays and allows users to add their own. We will be wanting to
accept a month as a digit between 1-12, a day between 1-31 and a year
in the format of YYYY.
Having this kind of logic in your application is simple and regular
expressions (regex) are the perfect way to handle input validation.
Take the following example:
  1. if ( ! preg_match( "/^[0-9]{1,2}$/"$_GET['month'] ) )  
  2. {  
  3.     // handle error  
  4. }  
  5. if ( ! preg_match( "/^[0-9]{1,2}$/"$_GET['day'] ) )  
  6. {  
  7.     // handle error  
  8. }  
  9. if ( ! preg_match( "/^[0-9]{4}$/"$_GET['year'] ) )  
  10. {  
  11.     // handle error  
  12. }  
In this example, we simply checked (in the first two if statements)
for integers [0-9] with a length of one or two {1,2} and we did the
same in the third if statement, but checked for a strict length of 4
characters {4}.
In all instances, if the data doesn’t match the format we want, we
return some kind of error. This type of validation leaves very little
room for any type of SQL attack.
Regex expressions like those above can be a little difficult to
grasp at first, but explaining them is out of the scope of this
article. The php manual has some additional resources to help you with validation. The PEAR database also has a few packages such as the Validate package to help with emails, dates, and URLS.
Below is an example of the above script in action using 200 as an input for a month, abc for the day and just 09 for the year.
Example of a validation script running

Tip 4: Watch for Cross Site Scripting (XSS) Attacks in User Input

A web application usually accepts input from users and displays it
in some way. This can, of course, be in a wide variety of forms
including comments, threads or blog posts that are in the form of HTML
code. When accepting input, allowing HTML can be a dangerous thing,
because that allows for JavaScript to be executed in unintended ways.
If even one hole is left open, JavasScript can be executed and cookies
could be hijacked. This cookie data could then be used to fake a real
account and give an illegal user access to the website’s data.
There are a few ways you can protect yourself from such attacks. One
way is to disallow HTML altogether, because then there is no possible
way to allow any JavaScript to execute. However, if you do this then
formatting is also disallowed, which is not always an option for forum
and blog software.
If you want HTML mostly disabled, but still want to allow simple
formatting, you can allow just a few selected HTML tags (without
attributes) such as <strong> or <em>. Or, alternatively,
you can allow a popular set of tags called “BBCode” or “BB Tags,”
commonly seen on forums in the format of [b]test[/b]. This can be a
perfect way to allow some formatting customization while disallowing
anything dangerous. You can implement BBCode using pre-existing
packages such as HTML_BBCodeParser or write your own BBCode implementation with regular expressions and a series of preg_replace statements.
Example of BBCode in action

Tip 5: Protecting against SQL Injection

Last, but not least, is one of the most well-known security attacks
on the web: SQL injection. SQL injection attacks occur when data goes
unchecked, and the application doesn’t escape characters used in SQL
strings such as single quotes (‘) or double quotes (“).
If these characters are not filtered out users can exploit the system by making queries always true and thus allowing them to trick login systems.
Pesky login box being hacked
Luckily, PHP does offer a few tools to help protect your database
input. When you are connected to an sql server you can use these
functions with a simple call, and your variables should be safe to use
in queries. Most of the major database systems offered with PHP include
these protection functions.
MySQLi allows you to do this in one of two ways. Either with the mysqli_real_escape_string function when connected to a server:
  1. $username = mysqli_real_escape_string( $GET['username'] );  
  2. mysql_query( "SELECT * FROM tbl_members WHERE username = '".$username."'");  
Or with prepared statements.
Prepared statements are a method of separating SQL logic from the data being passed to it. The functions used within the MySQLi library filter our input for us when we bind variables to the prepared statement. This can be used like so (when connected to a server):
  1. $id = $_GET['id'];  
  2. $statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );  
  3. $statement->bind_param( "i"$id );  
  4. $statement->execute();  
One thing to note when using prepared statements is the “i” in bind_param. i stands for for integer but you can use s for string, d for double, and b for blob depending on what data we are passing.
Although this will protect you in most circumstances, you should
still keep in mind proper data validation as mentioned previously.

Closing

This short tutorial can only scratch the surface of web security.
Ultimately, it is up to developers to ensure that the applications they
build are safe by educating themselves about the dangers of the web and
the most common kinds of vulnerabilities and attacks. If you wish to
read more about security issues in PHP, there is a section on security in the php manual devoted to them.
What are your tips?

PHP Security / SQL Security

Web Security: The Big PictureWhether your site is the web presence for a large multinational, a gallery showing your product range and inviting potential customers to come into the shop, or a personal site exhibiting your holiday photos, web security matters. After the hard work put in to make your site look good and respond to your users, the last thing you want is for a malicious hacker to come along, perform a PHP hack and break it somehow.
There are a number of problems in web security, and unfortunately not all of them have definite solutions, but here we'll look at some of the problems that should be considered every time you set out to write a PHP script to avoid a PHP hack attack. These are the problems which, with well-designed code, can be eliminated entirely. Before looking in detail at the solutions, though, lets take a moment to define the problems themselves.
SQL InjectionIn this attack, a user is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field which causes a subsequent SQL query, generated from the PHP form processing code, to execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETE, for instance). In more subtle attacks, data could be changed, or new data added.
Directory TraversalThis attack can occur anywhere user-supplied data (from a form field or uploaded filename, for example) is used in a filesystem operation. If a user specifies “../../../../../../etc/passwd” as form data, and your script appends that to a directory name to obtain user-specific files, this string could lead to the inclusion of the password file contents, instead of the intended file. More severe cases involve file operations such as moving and deleting, which allow an attacker to make arbitrary changes to your filesystem structure.
Authentication IssuesAuthentication issues involve users gaining access to something they shouldn't, but to which other users should. An example would be a user who was able to steal (or construct) a cookie allowing them to login to your site under an Administrator session, and therefore be able to change anything they liked.
Remote Scripts (XSS)XSS, or Cross-Site Scripting (also sometimes referred to as CSS, but this can be confused with Cascading Style Sheets, something entirely different!) is the process of exploiting a security hole in one site to run arbitrary code on that site's server. The code is usually included into a running PHP script from a remote location. This is a serious attack which could allow any code the attacker chooses to be run on the vulnerable server, with all of the permissions of the user hosting the script, including database and filesystem access.
Processing User Data – Form Input Verification & HTML Display
Validating Input And Stripping TagsWhen a user enters information into a form which is to be later processed on your site, they have the power to enter anything they want. Code which processes form input should be carefully written to ensure that the input is as requested; password fields have the required level of complexity, e-mail fields have at least some characters, an @ sign, some more characters, a period, and two or more characters at the end, zip or postal codes are of the required format, and so on.
Each of these may be verified using regular expressions, which scan the input for certain patterns. An example for e-mail address verification is the PHP code shown below. This evaluates to true if an e-mail address was entered in the field named 'email'.
preg_match('/^.+@.+\..{2,3}$/',$_POST['email']);
This code just constructs a regular expression based on the format described above for an e-mail address. Note that this will return true for anything with an @ sign and a dot followed by 2 or 3 characters. That is the general format for an e-mail address, but it doesn't mean that address necessarily exists; you'd have to send mail to it to be sure of that.
Interesting as this is, how does it relate to security? Well, consider a guestbook as an example. Here, users are invited to enter a message into a form, which then gets displayed on the HTML page along with everyone else's messages. For now, we won't go into database security issues, the problems dealt with below can occur whether the data is stored in a database, a file, or some other construct.
If a user enters data which contains HTML, or even JavaScript, then when the data is included into your HTML for display later, their HTML or JavaScript will also get included.
If your guestbook page displayed whatever was entered into the form field, and a user entered the following,
Hi, I <b>love</b> your site.
Then the effect is minimal, when displayed later, this would appear as,
Hi, I love your site.
Of course, when the user enters JavaScript, things can get a lot worse. For example, the data below, when entered into a form which does not prevent JavaScript ending up in the final displayed page, will cause the page to redirect to a different website. Obviously, this only works if the client has JavaScript enabled in their browser, but the vast majority of users do.
Hi, I love your site. Its great!<script
language=”JavaScript”>document.location=”http://www.acunetix.com/”;</script>

For a split second when this is displayed, the user will see,
Hi, I love your site. Its great!
The browser will then kick in and the page will be refreshed from www.acunetix.com. In this case, a fairly harmless alternative page, although it does result in a denial of service attack; users can no longer get to your guestbook.
Consider a case where this was entered into an online order form. Your order dispatchers would not be able to view the data because every time they tried, their browser would redirect to another site. Worse still, if the redirection occurred on a critical page for a large business, or the redirection was to a site containing objectionable material, custom may be lost as a result of the attack.
Fortunately, PHP provides a way to prevent this style of PHP hack attack. The functions strip_tags(), nl2br() and htmlspecialchars() are your friends, here.
strip_tags() removes any PHP or HTML tags from a string. This prevents the HTML display problems, the JavaScript execution (the <script> tag will no longer be present) and a variety of problems where there is a chance that PHP code could be executed.
nl2br() converts newline characters in the input to <br /> HTML tags. This allows you to format multi-line input correctly, and is mentioned here only because it is important to run strip_tags() prior to running nl2br() on your data, otherwise the newly inserted <br /> tags will be stripped out when strip_tags() is run!
Finally, htmlspecialchars() will entity-quote characters such as <, > and & remaining in the input after strip_tags() has run. This prevents them being misinterpreted as HTML and makes sure they are displayed properly in any output.
Having presented those three functions, there are a few points to make about their usage. Clearly, nl2br() and htmlspecialchars() are suited for output formatting, called on data just before it is output, allowing the database or file-stored data to retain normal formatting such as newlines and characters such as &. These functions are designed mainly to ensure that output of data into an HTML page is presented neatly, even after running strip_tags() on any input.
strip_tags(), on the other hand, should be run immediately on input of data, before any other processing occurs. The code below is a function to clean user input of any PHP or HTML tags, and works for both GET and POST request methods.
function _INPUT($name)
{
    if ($_SERVER['REQUEST_METHOD'] == 'GET')
        return strip_tags($_GET[$name]);
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
        return strip_tags($_POST[$name]);
}

This function could easily be expanded to include cookies in the search for a variable name. I called it _INPUT because it directly parallels the $_ arrays which store user input. Note also that when using this function, it does not matter whether the page was requested with a GET or a POST method, the code can use _INPUT() and expect the correct value regardless of request method. To use this function, consider the following two lines of code, which both have the same effect, but the second strips the PHP and HTML tags first, thus increasing the security of the script.
$name = $_GET['name');
$name = _INPUT('name');

If data is to be entered into a database, more processing is needed to prevent SQL injection, which will be discussed later.
Executing Code Containing User InputAnother concern when dealing with user data is the possibility that it may be executed in PHP code or on the system shell. PHP provides the eval() function, which allows arbitrary PHP code within a string to be evaluated (run). There are also the system(), passthru() and exec() functions, and the backtick operator, all of which allow a string to be run as a command on the operating system shell.
Where possible, the use of all such functions should be avoided, especially where user input is entered into the command or code. An example of a situation where this can lead to attack is the following command, which would display the results of the command on the web page.
echo 'Your usage log:<br />';
$username = $_GET['username'];
passthru(“cat /logs/usage/$username”);

passthru() runs a command and displays the output as output from the PHP script, which is included into the final page the user sees. Here, the intent is obvious, a user can pass their username in a GET request such as usage.php?username=andrew and their usage log would be displayed in the browser window.
But what if the user passed the following URL?
usage.php?username=andrew;cat%20/etc/passwd
Here, the username value now contains a semicolon, which is a shell command terminator, and a new command afterwards. The %20 is a URL-Encoded space character, and is converted to a space automatically by PHP. Now, the command which gets run by passthru() is,
cat /logs/usage/andrew;cat /etc/passwd
Clearly this kind of command abuse cannot be allowed. An attacker could use this vulnerability to read, delete or modify any file the web server has access to. Luckily, once again, PHP steps in to provide a solution, in the form of the escapeshellarg() function. escapeshellarg() escapes any characters which could cause an argument or command to be terminated. As an example, any single or double quotes in the string are replaced with \' or \”, and semicolons are replaced with \;. These replacements, and any others performed by escapeshellarg(), ensure that code such as that presented below is safe to run.
$username = escapeshellarg($_GET['username']);
passthru(“cat /logs/usage/$username”);

Now, if the attacker attempts to read the password file using the request string above, the shell will attempt to access a file called “/logs/usage/andrew;cat /etc/passwd”, and will fail, since this file will almost certainly not exist.
It is generally considered that eval() called on code containing user input be avoided at all costs; there is almost always a better way to achieve the desired effect. However, if it must be done, ensure that strip_tags has been called, and that any quoting and character escapes have been performed.
Combining the above techniques to provide stripping of tags, escaping of special shell characters, entity-quoting of HTML and regular expression-based input validation, it is possible to construct secure web scripts with relatively little work over and above constructing one without the security considerations. In particular, using a function such as the _INPUT() presented above makes the secure version of input acquisition almost as painless as the insecure version PHP provides.
How to check for PHP vulnerabilitiesThe best way to check whether your web site & applications are vulnerable to PHP hack attacks is by using a Web Vulnerability Scanner. A Web Vulnerability Scanner crawls your entire website and automatically checks for vulnerabilities to PHP attacks. It will indicate which scripts are vulnerable so that you can fix the vulnerability easily. Besides PHP security vulnerabilities, a web application scanner will also check for SQL injection, Cross site scripting & other web vulnerabilities.
Acunetix Web Vulnerability Scanner ensures website security by automatically checking for SQL injection, Cross site scripting and other vulnerabilities. It checks password strength on authentication pages and automatically audits shopping carts, forms, dynamic content and other web applications. As the scan is being completed, the software produces detailed reports that pinpoint where vulnerabilities exist. Take a product tour or download the evaluation version today!
Scanning for XSS vulnerabilities with Acunetix WVS Free Edition! To check whether your website has cross site scripting vulnerabilities, download the Free Edition from http://www.acunetix.com/cross-site-scripting/scanner.htm. This version will scan any website / web application for XSS vulnerabilities and it will also reveal all the essential information related to it, such as the vulnerability location and remediation techniques. Scanning for XSS is normally a quick exercise (depending on the size of the web-site).
Later In The SeriesThis series will go on to look at SQL databases, and protecting against SQL injection attacks, as well as file operations and session management, including a look at one of the features of PHP designed to increase security and avoid PHP hack attacks- the PHP Safe Mode.

Sunday, July 22, 2012

Connecting JSP To Mysql Database Lesson

My brother Ravi Tamada request one mail about his college presentation. He is planning to do web dynamic project. So i am giving small explanation about JSP (Java Server Pages) to Mysql Connection structure, Tomcat directory structure and simple database examples.

Login.html


Code :
<body>
<form action="login.jsp" method="post">

User name :<input type="text" name="usr" />
password :<input type="password" name="pwd" />
<input type="submit" />

</form>
</body>

Reg.html



code:
<form action="reg.jsp" method="post">

Email :<input type="text" name="email" />
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
User name :<input type="text" name="userid" />
password :<input type="password" name="pwd" />
<input type="submit" />

</form>

Mysql Create Database Test:
Mysql no doubt about it best open source database http://mysql.com/


Create Table Users:


login.jsp


<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String userid=request.getParameter("user");
session.putValue("userid",userid);
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/
test","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where user_id='"+userid+"'");
if(rs.next())
{
if(rs.getString(2).equals(pwd))
{
out.println("welcome"+userid);

}
else
{
out.println("Invalid password try again");
}
}
else
%>


reg.jsp


<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"',
'"+lname+"','"+email+"')");


%>


welcome.jsp


<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String user=session.getValue("userid").toString();
%>
Registration is Successfull. Welcome to <%=user %>

Tomcat Directory Structure
Tomcat open source web server you can download from this link http://tomcat.apache.org/



Run Your Project

Make Windows Genuine

Have you updated your copy of Windows and received the "This copy of Windows is not genuine" notification. Have you ever wondered how to get rid of it?

The Windows Genuine Advantage notification checks if you have a genuine copy of Windows registered to that computer. It allows you to update your computer with the Windows updates. If you have installed it, and you do not have a genuine copy of Windows XP installed, then you may notice an icon at the bottom of your window before you Login. It will make you wait three seconds before allowing you to login.

JUST OPEAN START THEN CLICK RUN.Type "regedit"(without quotes) and press enter.

follow this path:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WPAEvents

u'll find "OOBETimer" in the right side..
double click it..
and in value data
change the last part of first line.....
i dun care just change it.....

save it & close it.....
now opean RUN and type this widout quotes
"C:\WINDOWS\system32\oobe\msoobe.exe /a"

select the option telephone customer service now click next.. now u have a button at the bottom of ur screen "CHANGE PRODUCT KEY" click this... now u see the screen where u have to enter the key...

there u enter one of these:-

(1)T6T38-WJTK6-YVJQ7-YC6CQ-FW386
(2)V2C47-MK7JD-3R89F-D2KXW-VPK3J
(3)JG28K-H9Q7X-BH6W4-3PDCQ-6XBFJ

Open C:\Windows\System32\

Search for WgaTray.exe and Delete it.

C:\Windows\System32\dllcache\ and delete WgaTray.exe here also.

Next you have to modify your registry.

Press the Start Button > Run and type regedit and then press enter.

Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify and delete the WGALOGON folder.

That's all you have to do, now you are WGA free. Just make sure you don't automatically install the WGA update again. Restart your computer to see if you did it correctly. The WGA logo should not appear on your login screen.

DISCLAIMER: We do not condone having pirated copies of Windows on your computer. You should have one CAL per computer. This is for educational purposes only.

Hacking Algorithm

In a security context, a hacker is someone involved in computer security/insecurity, specializing in the discovery of exploits in systems (for exploitation or prevention), or in obtaining or preventing unauthorized access to systems through skills, tactics and detailed knowledge.



void main()
{

for(i = 0 knowledge; i < knowledge; i++)
while(you don't know how something works)
{

   Read(Your Brain, i);
   Experiment(Your Brain, i);
   Learn(Your Brain, i);

}

}

Being a hacker is so easy..
It is all a mindset.

Send Mail using SMTP and PHP.

This post about "Sending Mail using SMTP and PHP". Now you can send emails with SMTP authentication using this script. Every mail needed server authentication, So you have to buy mail server. It's very useful you can implement this on your web projects.

Send Mail using SMTP and PHP
This tutorial contains three files.

- Index.php
- SMTPconfig.php // SMTP Server Cofiguration
- SMTPClass.php // SMTP Mail Sending Class


Download Script



SMTPconfig.php
You have to change SMTP server details.
<?php
//Server Address
$SmtpServer="127.0.0.1";
$SmtpPort="25"; //default
$SmtpUser="username";
$SmtpPass="password";
?>

SMTPclass.php
SMTP mail sending class.
<?php
class SMTPClient
{

function SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body)
{

$this->SmtpServer = $SmtpServer;
$this->SmtpUser = base64_encode ($SmtpUser);
$this->SmtpPass = base64_encode ($SmtpPass);
$this->from = $from;
$this->to = $to;
$this->subject = $subject;
$this->body = $body;

if ($SmtpPort == "")
{
$this->PortSMTP = 25;
}
else
{
$this->PortSMTP = $SmtpPort;
}
}

function SendMail ()
{
if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP))
{
fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n");
$talk["hello"] = fgets ( $SMTPIN, 1024 );
fputs($SMTPIN, "auth login\r\n");
$talk["res"]=fgets($SMTPIN,1024);
fputs($SMTPIN, $this->SmtpUser."\r\n");
$talk["user"]=fgets($SMTPIN,1024);
fputs($SMTPIN, $this->SmtpPass."\r\n");
$talk["pass"]=fgets($SMTPIN,256);
fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n");
$talk["From"] = fgets ( $SMTPIN, 1024 );
fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n");
$talk["To"] = fgets ($SMTPIN, 1024);
fputs($SMTPIN, "DATA\r\n");
$talk["data"]=fgets( $SMTPIN,1024 );
fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");
$talk["send"]=fgets($SMTPIN,256);
//CLOSE CONNECTION AND EXIT ...
fputs ($SMTPIN, "QUIT\r\n");
fclose($SMTPIN);
//
}
return $talk;
}
}
?>

index.php
<?php
include('SMTPconfig.php');
include('SMTPClass.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['sub'];
$body = $_POST['message'];
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
}
?>
<form method="post" action="">
To:<input type="text" name="to" />
From :<input type='text' name="from" />
Subject :<input type='text' name="sub" />
Message :<textarea name="message"></textarea>
<input type="submit" value=" Send " />
</form>

Displaying RSS Feed with PHP

This article explains to displaying RSS(XML format) feed like popurls.com (popular urls in one place) using simplexml_load_file() a PHP function. It's very useful to display your blog feeds as like Recent articles(headlines) list.

RSS- Really Simple Syndication.

Reading XML data and presenting with HTML.

Download Script     Live Demo

Index.php RSS display page:
File contains HTML tags and PHP included rssclass.php. You have to change the RSS feed URL.
<div>
  <?php
  include('rssclass.php');
  $feedlist = new rss('http://feeds2.feedburner.com/9lesson');
  echo $feedlist->display(9,"9lessons");
 
  $feedlist = new rss('http://feeds.feedburner.com/nettuts');
  echo $feedlist->display(9,"Nettuts");
 
  $feedlist = new rss('http://feeds.labnol.org/labnol');
  echo $feedlist->display(9,"Labnol");
  ?> 
  </div>
Popurls.com screen shot

rssclass.php
A beautiful PHP function simplexml_load_file() to load and read XML file. simplexml_load_string() XML string reader.
<?php
 class rss {
     var $feed;

  function rss($feed) 
    {   $this->feed = $feed;  }
 
  function parse() 
    {
    $rss = simplexml_load_file($this->feed);
    
    $rss_split = array();
    foreach ($rss->channel->item as $item) {
    $title = (string) $item->title; // Title
    $link   = (string) $item->link; // Url Link
    $description = (string) $item->description; //Description
    $rss_split[] = '<div>
        <a href="'.$link.'" target="_blank" title="" >
            '.$title.' 
        </a>
   <hr>
          </div>
';
    }
    return $rss_split;
  }
  function display($numrows,$head) 
  {
    $rss_split = $this->parse();

    $i = 0;
    $rss_data = '<div class="vas">
           <div class="title-head">
         '.$head.'
           </div>
         <div class="feeds-links">';
    while ( $i < $numrows ) 
   {
      $rss_data .= $rss_split[$i];
      $i++;
    }
    $trim = str_replace('', '',$this->feed);
    $user = str_replace('&lang=en-us&format=rss_200','',$trim);
    $rss_data.='</div></div>';
    return $rss_data;
  }
}
?>

CSS code :
Style just view the Live Demo
.vas{
    float:left;
    width:270px;
    padding:10px;
}
.title-head {
    font-size:18px;
    font-weight:bold;
    text-align:left;
    background-color:#006699;
    color:#FFFFFF;
    padding:5px;}
.feeds-links {
    text-align:left;
    padding:5px;
    border:1px solid #dedede;
 }
Download Script     Live Demo