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

Hack your Own Web Project ? SQL Injection

Are you looking for some useful tips to improve your web projects security? In this post I suggest you some interesting points about this topic.

Hacking is very interesting topic you can improve programming skill.

SQL Injection

SQL Injection like this

Login Java Code

String userid = request.getParameter("userid");
String password = request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:projectDB");

query = "SELECT * FROM Users WHERE user_id ='" + userid + "' AND password ='" + password +"'";

PreparedStatement ps = connection.prepareStatement(query);
ResultSet users = ps.executeQuery();

if(users.next()){

//some thing here
}
else{

}
Injection Works like this
query = "SELECT * FROM Users WHERE user_id ='' OR 1=1; /* AND password ='*/--'";

Login PHP Code;
Username = ' OR 1=1;//
Password = ....
$myusername=$_POST['usr'];
$mypassword=$_POST['pwd'];

$sql="SELECT * FROM users WHERE user='$myusername' and password='$mypassword'";

$result=mysql_query($sql);
$count=mysql_num_rows($result);

if($count==1){

//some code
}
else {

}
Injection Works like this
$sql="SELECT * FROM users WHERE user=''OR 1 = 1;//' and password='....'";

How to avoid these mistakes Use addSlashes() function adding slashes(/) to the string in java and php

//Java Code
addSlashes(String userid);

// PHP Code
$myusername=addslashes($_POST['usr'];);
Hacker is intelligent than programmer. So always hide the file extension (eg: *.jsp,*.php,*.asp).

http://xyz.com/login.php to http://xyz.com/login
http://xyz.com/login to http://xyz.com/signin.do
In Java redirect this URL links using Web.xml file and inn php write .htaccess file in root directory.

My Best Hacking Training Site Hackthissite.org

Hacker's Game full control with Unix based commands. Play and learn many more hacking things

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.

Secure PHP Login Page Example

PHP - Hypertext Preprocessor before it was a Personal Home Page now a days very popular open source language in web world.


Voting system with jQuery, Ajax and PHP.

This post about Dzone like voting system with jQuery, Ajax and PHP. This script helps you to display user votes on blog post. IP address based voting system I hope you like this thanks! Take a look at live demo and give your votes.

Voting system with jQuery, Ajax and PHP.

Download Script     Live Demo

Database Design

Messages Table :
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT,
up INT,
down INT);

Voting_IP Table : Storing IP address
CREATE TABLE Voting_IP(
ip_id INT PRIMARY KEY AUTO_INCREMENT,
mes_id_fk INT,
ip_add VARCHAR(40),
FOREIGN KEY(mes_id_fk)
REFERENCES messages(mes_id));


Voting.php
Contains javascript, PHP and HTML code. $(".vote").click(function(){}- vote is the class name of anchor tag. Using element.attr("id") calling vote button value(messsage Id).
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);

if (name=='up')
{
$(this).fadeIn(200).html('<img src="dot.gif" />');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,

success: function(html)
{
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('<img src="dot.gif" />');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,

success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
<script

//HTML Code

<?php
include('config.php');
$sql=mysql_query("SELECT * FROM messages LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$up=$row['up'];
$down=$row['down'];
?>
<div class="main">
<div class="box1">
<div class='up'>
<a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>

<div class='down'>
<a href="" class="vote" id="<?php echo $mes_id; ?>;" name="down">
<?php echo $down; ?></a></div>
</div>

<div class='box2' ><?php echo $msg; ?></div>
</div>

<?php } ?>




up_vote.php
Contains PHP code.
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];

if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);

if($count==0)
{
// Update Vote.
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query( $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}

$result=mysql_query("select up from Messages where mes_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
echo $up_value;

}
?>

down_vote.php
You have to modify up_vote.php code just replace word up to down in SQL statements.

CSS Code:
#main
{
height:80px;
border:1px dashed #29ABE2;
margin-bottom:7px;
width:500px;
}
.box1
{
float:left;
height:80px;
width:50px;
}
.box2
{
float:left;
width:440px;
text-align:left;
margin-left:10px;
height:60px;
margin-top:10px;
font-weight:bold;
font-size:18px;
}
.up
{
height:40px;
font-size:24px;
text-align:center;
background-color:#009900;
margin-bottom:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
.down
{
height:40px;
font-size:24px;
text-align:center;
background-color:#cc0000;
margin-top:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}

PHP Login Script with Encryption.

In this post I want to explain how to insert encrypted password while registration and accessing the same with login time. I had implement this at labs.9lessons.info login page. I'm just storing encrypted user password in database. Demo username ='test' and password = 'test'

PHP Login Script with Encryption.

Download Script     Live Demo

Database
MySQL admin table columns id, username, passcode.
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
passcode VARCHAR(50)
);



Encrypted Password
Here database table admin password:test encrypted and storing like this


registration.php
Contains PHP and HTML code. Just inserting form values into database table admin
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password); // Encrypted Password
$sql="Insert into admin(username,passcode) values('$username','$password');";
$result=mysql_query($sql);
echo "Registration Successfully";
}
?>
<form action="registration.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />


<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Registration "/><br />
</form>

login.php
Login Script accessing the encrypted password.include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password); // Encrypted Password
$sql="SELECT id FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count==1)
{
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>

db.php
Database configuration file.
<?php
$mysql_hostname = "hostname";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

The testking 642-845 php tutorials and testking 642-982 live demos are definitely good source of learning especially for php learners. Download the testking EX0-101 tutorial to learn about php login script.

Twitter Like More Button with jQuery and Ajax.

This is an interesting tutorial I had developed this using jQuery and Ajax. Some days back twitter added new feature like 'more' button it's nice the some thing I'm presenting in this post.

Twitter Like More Button with jQuery and Ajax.

Download Script     Live Demo

Updated Version

First create a database table.
CREATE TABLE messages(
msg_id INT AUTO_INCREMENT PRIMARY KEY,
msg TEXT
);

Step 1


first.js
javascript code..
<script type="text/javascript" >
$(function() {
$(".more").click(function() {
var element = $(this);
var msg = element.attr("id");
$("#morebutton").html('<img src="ajax-loader.gif" />');

$.ajax({
type: "POST",
url: "more_ajax.php",
data: "lastmsg="+ msg,
cache: false,
success: function(html){

$("#more_updates").append(html);
$(".more").remove();

}
});
return false;
});
});
</script>

more_tut.php
You have to run this file first. The first.js jquery code calling more_ajax.php.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>

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

<?php
include('db.php');
$sql = mysql_query("SELECT * FROM messages order by msg_id desc limit 5;");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['msg_id'];
$msg=$row['msg'];
?>
<div>
<?php echo $msg; ?>
</div>
<?php } ?>
<div id="more_updates"></div>
<div class="more" id="morebutton" >
<a id="<?php echo $msg_id; ?>" class="more"  href="#" >
More </a>
</div>
</div>

Step 2


second.js
javascript code

<script type="text/javascript" >
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$("#morebutton").html('<img src="ajax-loader.gif" />');

$.ajax({
type: "POST",
url: "more_ajax.php",
data: "lastmsg="+ msg,
cache: false,
success: function(html){
$("#more_updates").append(html);
$(".more"+msg).remove();
}
});

return false;
});
});
</script>



more_ajax.php
Ya.. here jQuery recalling the same file 'more_ajax.php' so you have to change the div tag class name just adding msg_id value.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>

<script type="text/javascript" src="second.js">
</script>
<?php
include('db.php');
if(isSet($_POST['lastmsg']))
{
$lastmsg = $_POST['lastmsg'];
$sql_check = mysql_query("SELECT * FROM messages where msg_id<'$lastmsg' order by msg_id desc limit 5;");
if(mysql_num_rows($sql_check))
{
while($row=mysql_fetch_array($sql_check))
{
$msg_id=$row['msg_id'];
$msg=$row['msg'];
?>
<div>
<?php echo $msg; ?>
</div>
<?php } ?>
<div id="more_updates"></div>
<div class="more<?php echo $msg_id; ?>" id="morebutton" >
<a id="<?php echo $msg_id; ?>" class="more"  href="#" >
More </a>
</div>
</div>
<?php } } ?>

If you feel free just post a comment don't spam.