Showing posts with label Google. Show all posts
Showing posts with label Google. Show all posts

Tuesday, 29 November 2011

Prepared Statements in PHP and MySQLi

This article is intended for readers who have experience using PHP and MySQL. You should also have a general understanding of databases and programming (both procedural and object-oriented) as well as how to use PHP to execute a simple query to MySQL. I will not cover how to install PHP or MySQL, however at the end of the article are some links to help you get started with the installation process and for some further reading on the subject. I will be covering the basics of prepared statements in PHP and MySQLi and why you should consider using them in your own code as well as some technical explanation as to why you should use them.

Introduction

If you are like me and most other people, you probably have not taken the time to learn about web security when you first started writing server-side code. This is very dangerous as most people never even go back and try to make their code secure (or they simply forget). Writing their code in the same way that they originally learned how to can cause some serious vulnerabilities in the code, allowing hacking techniques such as SQL Injections to be fairly easy. If you have no idea what MySQL injections or cross side scripting is, then you should do some research, for example just go to Google and type in "SQL Injections" and there will be plenty of reading for you. I also would recommend a book called, "How to Break Web Software", it is a fantastic book that one of my professors told one of my classes about. It can teach you a lot about security, it is highly recommended. I will have an article written shortly on SQL Injections, so check back soon! If you do know what some of these nasty hacking techniques are then you are probably wondering why you should want to use prepared statements. There are basically three reasons why you should seriously consider writing prepared statements to execute your queries.

1. Prepared statements are more secure.
2. Prepared statements have better performance.
3. Prepared statements are more convenient to write.

Now that we know why prepared statements are better, let’s build an example so you can see for yourself. We’ll build a simple login example using prepared statements. First, I’ll show you the way most people would write it, then I’ll show you the way you could do it with a prepared statement which will be more secure, have better performance and be more convenient to write. Let’s get started!

The Well-known Way

If you are reading this article, chances are you already know how to execute a simple MySQL query in PHP. For those of you who do not know how to do this, it would look similar to this:

/* Connect to the Database */

$dbLink = mysql_connect("localhost", "username", "password");

if (!dbLink) {
echo 'db link fail';
}

/* Select the database */
mysql_select_db("databaseName");

/* Query and get the results */
$query = "SELECT * FROM testUsers WHERE username='$user' AND
password='$pass'";
$result = mysql_query($query);

/* Loop through the results */
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Username: " . $row["username";
}


What is the problem with this code? Simple, someone could use a simple SQL injection to get around the password authentication. Why is this code angerous? If you know what an SQL injection does, it basically bypasses the password condition by commenting it out and uses an always true statement which allows access. Building strings on the fly like this should make you very nervous, but how do we make it more secure? Say hello to prepared statements.

Prepared Statements

What is so great about prepared statements and why are they more secure? The simple answer is because prepared statements can help increase security by separating the SQL logic from the data being supplied. In the previous example we saw how the data is basically built into the SQL logic by building the query as a string on the fly. Let’s take a look at what a prepared statement can look like.

/* Create a new mysqli object with database connection parameters */

$mysqli = new mysql('localhost', 'username', 'password', 'db');

if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */

if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters

s - string, b - boolean, i - int, etc */

$stmt -> bind_param("ss", $user, $pass);

/* Execute it */
$stmt -> execute();
/* Bind results */

$stmt -> bind_results($result);
/* Fetch the value */

$stmt -> fetch();

echo $user . "'s level of priviledges is " . $result;
/* Close statement */

$stmt -> close();
}
/* Close connection */

$mysqli -> close();


Doesn’t look too bad, right? In short, the above code basically creates a new mysqli object and connects to the database. We then create a prepared statement and bind the incoming parameters to that statement, execute it and get the result. We then close the statement and connect and we’re done! Pretty easy!

Let’s take a look at where the security happens in these few lines:
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
$stmt -> bind_param("ss", $user, $pass);

Instead of grabbing and building the query string using things like $_GET['username'], we have ?'s instead. These ?'s separate the SQL logic from the data. The ?'s are place holders until the next line where we bind our parameters to be the username and password. The rest of the code is pretty much just calling methods which you can read about by following some of the links at the end of the article.

I hope this was helpful to you and if you have any questions feel free to post some comments below!

Friday, 25 November 2011

Getting started

To use jQuery, you need to include it on the pages where you wish to take advantage of it. You can do this by downloading jQuery from their website at www.jquery.com. There is usually a choice between a "Production" version and a "Development" version. The first is for your live website, because it has been minified and compressed to take up the least amount of space, which is important for your visitors, whose browser will have to download the jQuery file along with the rest of your website. For testing and development, the "Development" version is best. It hasn't been minified or compressed, so when you run into an error, you can actually see where in jQuery it happens.

Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:

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

A part of your page should now look something like this:

<head>
        <title>jQuery test</title>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
</head>

A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.

You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:

http://code.google.com/intl/da/apis/libraries/devguide.html#jquery

Or if you prefer to use it from Microsoft:

http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

Read on to learn how to start using jQuery.

Getting and setting attributes [attr()]

In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:

<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
        alert($("#aGoogle1").attr("href"));
});
</script>

In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:

<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>

This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:

<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle3").attr(
        {
                "href" : "http://www.google.co.uk",
                "title" : "Google.co.uk"
        });
});
</script>

The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:

<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />

<script type="text/javascript">
$(function()
{
        $("a.google").attr("href", function(index, oldValue)
        {
                return oldValue + "imghp?tab=wi";
        });
});
</script>

We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.

Thursday, 21 July 2011

Has Google’s search quality gone down the drain?



Lately, there has been a lot of discussion on how Google has ranked low quality content farms and websites filled with ads over websites that contain higher quality content. People who own these content farms and ad sites have got sophisticated with their SEO methods and techniques allowing them to consistently rank their websites higher than genuine authoritative websites. Google has said that it will get tough with these content farms that are setup primarily to make money via pay per click ads.

But, it looks like things haven’t improved much. For example, search for the text “cricket world cup 2011” and look at the sites that are listed first on the search engine result page. The very first website is a site fully loaded with Adsense ads and other affiliate links. The fact that this website’s domain name matches the exact search phrase could have boosted its rankings to claim the number one spot. This is absurd!

The official website of the ICC Cricket World Cup is listed on a distant seventh place!

cricket_world_cup_google_search

Many of you have heard about the new search engine Blekko that has made headlines in the recent past. Blekko promises better quality searches using slash tags. In a nutshell a slash tag allows one to refine and narrow their search. For example, instead of just searching for the term “ipad 2”, you could search it with a slash tag. For example, “ipad 2 /techblogs”. In this example, we have narrowed the search to only technology blogs.

So, I decided to use the slash tag ‘”cricket” in my blekko search and performed the following search: “cricket world cup 2011 /cricket”.

The results returned by blekko were much better in quality than the Google search results. Blekko gave importance to high profile websites such as cricinfo in the search results. But, Blekko too listed the official website at the exact seventh spot as Google.

So what do you think? Has Google’s search quality gone down the drain? Love to hear your thoughts.