menu

Monday 17 December 2012

Most Useful functions to create the security in PHP

In programming Language security is a very important aspect for your project In PHP, there are some useful functions which prevent your website from various attacks like SQL Injection Attack , XSS attack etc.Let’s check some useful functions are available in PHP to tighten the security in your project. But note that this is not a complete list, it just list of functions which I found useful for using in your project.


1) mysql_real_escape_string() - This function is very useful for preventing from SQL Injection Attack in PHP . This function adds backslashes to the special characters like quote , double quote , backslashes to make sure that the user supplied input are sanitized before using it to query. But, make sure that you are connected to the database to use this function.

2) addslashes() – This function works similar as mysql_real_escape_string(). But make sure that you don’t use this function when “magic_quotes_gpc” is “on” in php.ini. When “magic_quotes_gpc” is on in php.ini then single quote(‘) and double quotes (“) are escaped with trailing backslashes in GET, POST and COOKIE variables. You can check it using the function “get_magic_quotes_gpc()” function available in PHP.

3) htmlentities() – This function is very useful for to sanitize the user inputted data. This function converts the special characters to their html entities. Such as, when the user enters the characters like “<” then it will be converted into it’s HTML entities < so that preventing from XSS and SQL injection attack.

4) strip_tags() – This function removes all the HTML, JavaScript and php tag from the string. But you can also allow particular tags to be entered by user using the second parameter of this function. 
For example,
echo strip_tags(“<script>alert(‘test’);</script>”);
will output
alert(‘test’);

5) md5() – Some developers store plain password in the database which is not good for security point of view. This function generates md5 hash of 32 characters of the supplied string. The hash generated from md5() is not reversible i.e can’t be converted to the original string.

6) sha1() – This function is similar to md5 but it uses different algorithm and generates 40 characters hash  of a string compared to 32 characters by md5().

7) intval() – Please don’t laugh. I know this is not a security function, it is function which gets the integer value from the variable. But you can use this function to secure your php coding. Well, most the values supplied in GET method in URL are the id from the database and if you’re sure that the supplied value must be integer then you can use this function to secure your code.
$sql=”SELECT * FROM product WHERE id=”.intval($_GET['id']);
As, you can see above, if you’re sure that the input value is integer you can use intval() as a secrity function as well.

Facebook login integration with website, Login with Facebook for websites

Facebook provide OAuth support provides web developers are able to create a Login or Sign In option with Existing Facebook Account without spending more time on new registration on your website.
Herewith we saw how to integrate in to your website using  Login with Facebook Button in easy way.

In Order to Create a "Login with Facebook"for your website you need a Facebook account to generate APP_ID and APP_SECRET, Create a Facebook user account and Navigate to the App Developer Page
http://www.facebook.com/developers/

In Top right  press "Create New App" Button.
Read more


<?php
session_start();
define('YOUR_APP_ID', 'YOUR_APP_KEY_HERE');
define('YOUR_APP_SECRET', 'YOUR_SECRET_KEY_HERE');

function get_facebook_cookie($app_id, $app_secret) { 
    $signed_request = parse_signed_request(@$_COOKIE['fbsr_' . $app_id], $app_secret);
    // $signed_request should now have most of the old elements
    $signed_request['uid'] = $signed_request['user_id']; // for compatibility 
    if (!is_null($signed_request)) {
        // the cookie is valid/signed correctly
        // lets change "code" into an "access_token"
  // openssl must enable on your server inorder to access HTTPS
        $access_token_response = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$app_id&redirect_uri=&client_secret=$app_secret&code={$signed_request['code']}");
        parse_str($access_token_response);
        $signed_request['access_token'] = $access_token;
        $signed_request['expires'] = time() + $expires;
    }
    return $signed_request;
}

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

if (isset($_COOKIE['fbsr_' . YOUR_APP_ID]))
{ 
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);

$user = json_decode(@file_get_contents(
    'https://graph.facebook.com/me?access_token=' .
    $cookie['access_token']));
 
/*
Uncomment this to show all available variables
echo "<pre>";
 - print_r function expose all the values available to get from facebook login connect.
print_r($user);
 1. Save nessary values from $user Object to your Database
 2. Register a Sesion Variable based on your user account code
 3. Redirect to Account Dashboard
echo "</pre>";
*/
 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facebook Login Connect for Website Demo</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 14px;
 color: #333;
}
body {
 margin-left: 50px;
 margin-top: 50px;
}
</style>
</head>
<body>
<?php if (@$cookie) { ?>
<h2>Welcome <?= $user->name ?> </h2> <br />
E-mail ID: <?= $user->email ?>
<br />
<a href="javascript://" onclick="FB.logout(function() { window.location='facebook-login.php' }); return false;" >Logout</a>
<?php } else { ?>
<h2>Welcome Guest! </h2>    
<div id="fb-root"></div>
<fb:login-button perms="email" width="width_value" show_faces="true" autologoutlink="true" size="large">Login with Facebook</fb:login-button>
<?php } ?>
<script src="http://connect.facebook.net/en_US/all.js"></script>   
<script>
 // Initiate FB Object
 FB.init({
   appId: '<?= YOUR_APP_ID ?>', 
   status: true,
   cookie: true, 
   xfbml: true
   });
 // Reloading after successfull login
 FB.Event.subscribe('auth.login', function(response) { 
 window.location.reload(); 
 });
</script>
</body>
</html>

Wednesday 12 December 2012

Cubet board is an open source pin based social photo sharing website that allows users to create and manage their image collections.


What is Cubet Board?

Cubet board is an open source pin based social photo sharing website that allows users to create and manage their image collections. The collections can be managed into different categories based on the users tastes. Users have the privilege to go through other collections as they like, re-pin the images to their personal or public collections.
Requirement
PHP 5.2 or newest.
MySQL 5.5
Support
Our support section is an easy to use community that helps you to ask questions and get answers of topics related to cubet board as well as on other areas of technology.
It's Free
Greatness of being open source


  • screen_1

Being Open




Read More  Demo

Tuesday 4 December 2012

JQuery Ajax CForms Form Generator

CForm is a JQuery plugin that generates html forms based on xml config files and css styles. All elements will be generated at runtime. Email fields will be validated and data will be send and received with AJAX.
All six examples are included in the package
A complete login php script and an example for the secure website section is included also.


Read more    Demo

Sunday 2 December 2012

Web Scraping Amazon with PHP

This snippet of PHP code demonstrates web scraping. It reads a sample page from Amazon.com, compares the HTML text against certain class name and outputs that matched text in an RSS feed.


<?php
$now   = date("D, d M Y H:i:s T");
$ASIN  = $url = $img = $title = $bio = $name = "";
$head = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$head .= '<rss version="2.0">';
$head .= '<channel>';
$head .= '<title>Amazon </title>';
$head .= '<link>http://www.amazon.com</link>';
$head .= '<description>Amazon RSS Feed</description>';
$url = "http://www.amazon.com/Best-Sellers-Kindle-Store/zgbs/digital-text/";
$text = file_get_html($url);
foreach ($text->find("div.zg_item_compact") as $class) {
  foreach ($class->find('strong.price') as $price) {
    if ($price->plaintext == "Free") {
            $rssfeed .= '<item>';
            foreach ($class->find("div.zg_title a") as $book) {                
              preg_match("/\/dp\/(.*)\/ref/", $book->href, $matches);                
              $ASIN  = trim($matches[1]);
              $url   = "http://www.amazon.com/dp/" . $ASIN . "/?tag=publisherapi-20";
              $img   = "http://images.amazon.com/images/P/" . $ASIN . ".01.LZZZZZZZ.jpg";
              $title = htmlentities(trim($book->plaintext));                
              $rssfeed .= '<title>' . $title . '</title>';
              $rssfeed .= '<link>' . $url . '</link>';
              $rssfeed .= '<guid isPermaLink="true">' . $url . '</guid>';
              $rssfeed .= '<description>';
            }
            foreach ($class->find("div.zg_byline a") as $author) {
                $bio  = "http://www.amazon.com" . $author->href . "/?tag=publisherapi-20";
                $name = htmlentities(trim($author->plaintext));
                $rssfeed .= 'By <a href="' . $authorURL . '">' . $name . '</a>';
            }
            $rssfeed .= '</description>';
            $rssfeed .= '<pubDate>' . $now . '</pubDate>';
            $rssfeed .= '</item>';
        }
    }
}
$footer  = '</channel></rss>';
$rssfeed = $head . $rssfeed . $footer;
$fh      = fopen("amazon.rss", "w");
fwrite($fh, $rssfeed);
fclose($fh);
?>

Code a Dynamic Questions & Answers FAQ Page with jQuery


You can perform many various effects using the jQuery JavaScript library. It’s an open source project which has been gaining followers for a couple years now. Aside from the many jQuery plugins you can build a lot of custom web functionality right from scratch.
I want to use this tutorial to showcase how we can build a custom FAQ webpage layout. I’ll be using a small bit of JavaScript to show and hide the answers. We could include any type of data like static text, images, or videos. Additionally you could port this code into your own layout and custom CSS codes. So without further ado let’s get started!