Thursday, July 22, 2010

Facebook - How to use facebook connect on your site | facebook connect beginners guide

Recently I came across the facebook connect API when developing a site that uses facebook connect for it's football manager game. There are a lot of tutorials out there that shows how to do this and that but here I wanted to share a simple guideline on the first step to implement facebook connect to your site.

The first thing you have to do of course to register your application in facebook. You can do that here.

When finished, you will be given an API Key and Application Secret codes, these codes will be use later in the connect API.

You can now write your php file like the sample below:

<?php
define('FACEBOOK_API_KEY', 'YOUR API KEY');
define('FACEBOOK_SECRET', 'YOUR SECRET KEY');

function get_facebook_cookie($app_id, $application_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $application_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
$fb_cookie = get_facebook_cookie(FACEBOOK_APP_KEY, FACEBOOK_SECRET);

if ($fb_cookie) { //if logged in
}
?>
<!DOCTYPE html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
FB.init({appId: "<?php echo FACEBOOK_APP_KEY; ?>", status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
    document.location.href = 'document.location.href';
});

function fb_logout() {
    FB.logout(function(response) {
        document.location.href = 'document.location.href';
    });
}
</script>

<?php if (!$fb_cookie) { //if not login ?>
      <div>
             <fb:login-button perms="publish_stream,user_photos" v="2"><fb:intl>Connect with Facebook</fb:intl></fb:login-button>
      </div>
      <?php } else { ?>
              <div>
                  <div class="logout">
                       HI, <?php echo strtoupper(substr($user->first_name, 0, 17)); ?>! | <a href="javascript:fb_logout()">LOGOUT</a>
                  </div>
              </div>
      <?php } ?>

      <!-- do your things here-->

</body>
</html>

There you go, simple application that has a connect button and logout button to sign out. 

If you are using Jquery tools plugin, you cannot use the flashembed feature as it would give you error in Internet Explorer "your api key is not valid.... etc". That's the only issue that I found throughout my experience.

Wednesday, July 21, 2010

Using swfobject for fullscreen flash site

This simple guide will show how to use swfobject for a fullscreen flash site.

First you need to of course download swfobject at http://code.google.com/p/swfobject/downloads/list and extract it to js/ folder for example here.

In this case, the flash file name will be index.swf.

Here's the html code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<title></title>
<link rel="Shortcut Icon" href="favicon.ico">
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
var params = {wmode: "transparent"};
var attributes = {};
swfobject.embedSWF("index.swf", "flash", "100%", "100%",
"9.0.0","js/expressInstall.swf", flashvars, params, attributes);

function getViewportSize() {
var size = [0, 0];
if (typeof window.innerWidth != "undefined") {
size = [window.innerWidth, window.innerHeight];
}
else if (typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
}
else {
size = [document.getElementsByTagName("body")[0].clientWidth, document.getElementsByTagName("body")[0].clientHeight];
}
return size;
}
</script>
</head>
<body style="margin:0px; padding:0px;">
<div id="container">
<div id="flash">
<p><a href="http://www.adobe.com/go/getflashplayer"><img src=" " alt="Get Adobe Flash player" /></a></p>
</div>
</div>
<script type="text/javascript">
window.onresize = function() {
var el = document.getElementById("container");
var size = getViewportSize();
el.style.width = size[0] < 900 ? "900px" : "100%";
el.style.height = size[1] < 600 ? "600px" : "100%";
};
window.onresize();
</script>
</body>
</html>

You can specify the minimum size restriction that the flash can be viewed, in this case I specify 900x600.

Posted via email from weirdcalculator's posterous

Thursday, July 15, 2010

PHP - The magic of php eval() function

It's been a while since I last post to my blog and today I would like to share with you my experience with the so called eval() function in PHP.


The function eval() basically:
"Evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things incode_str. To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.
Also remember that variables given values under eval() will retain these values in the main script afterwards."

for example:
<?php eval("echo 'test';"); ?>
will have the same output as
<?php echo "test"; ?>



so by this method, we can do any dynamic programming in php as long as the syntax is correct.

I came out with an experiment where I host a class script somewhere and with just 2 lines of code I can use the class in another web server without any problem.

In the external server I set a script to output the class codes:http://hazrulamin.com/api/?class=common
In php, to include the class I just have to use these 2 lines:
$class_common = file_get_contents("http://hazrulamin.com/api/?class=common");
eval("?>".htmlspecialchars_decode($class_common)."<?php ");

So now I can use:
$common = new class_common();
$common->validEmail($email);

And the function will run as it is as it were on the same server.

The issue on this of course the load time of the script is vary depending on how fast the server can get the script from the other server but it is worthy in some cases.

Friday, February 26, 2010

Browser Compatibility Check for Internet Explorer Versions from 5.5 to 8

IETester is a free WebBrowser that allows you to have the rendering and javascript engines of IE8, IE7 IE 6 and IE5.5 on Windows 7, Vista and XP, as well as the installed IE in the same process.

link: http://www.my-debugbar.com/wiki/IETester/HomePage

Tuesday, February 23, 2010

PHP, MySql - Check table existance | table exist

This function is to check whether the required table exist or not

code:
function TableExists($tablename, $db) {

// Get a list of tables contained within the database.
$result = mysql_list_tables($db);
$rcount = mysql_num_rows($result);

// Check each in list for a match.
for ($i=0;$i<$rcount;$i++) {
if (mysql_tablename($result, $i)==$tablename) return true;
}
return false;
}

Wednesday, February 17, 2010

PHP - Image upload resizing script | Image resize by script

Process an image after upload.

code:

function process_image($image, $folder, $prefix = "", $newwidth = 800, $newheight = NULL,
$allow = array("image/jpeg", "image/png", "image/gif"), $sizelimit = 2000000) {

global $error;

if (!is_dir($folder)) {
mkdir($folder, 0777);
}

if (in_array($image["type"], $allow)) {
if ($image["size"] < $sizelimit) {
$uploadedfile = $image['tmp_name'];
switch($image["type"]) {
case "image/jpeg":
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$ratio_orig = $width/$height;
if ($newwidth/$newheight > $ratio_orig) {
$newwidth = $newheight*$ratio_orig;
} else {
$newheight = $newwidth/$ratio_orig;
}
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $folder.$prefix.$image['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
return true;
break;
case "image/png":
$src = imagecreatefrompng($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$ratio_orig = $width/$height;
if ($newwidth/$newheight > $ratio_orig) {
$newwidth = $newheight*$ratio_orig;
} else {
$newheight = $newwidth/$ratio_orig;
}
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $folder.$prefix.$image['name'];
imagepng($tmp,$filename);
imagedestroy($src);
imagedestroy($tmp);
return true;
break;
case "image/gif":
$src = imagecreatefromgif($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$ratio_orig = $width/$height;
if ($newwidth/$newheight > $ratio_orig) {
$newwidth = $newheight*$ratio_orig;
} else {
$newheight = $newwidth/$ratio_orig;
}
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $folder.$prefix.$image['name'];
imagegif($tmp,$filename);
imagedestroy($src);
imagedestroy($tmp);
return true;
break;
}
} else {
$error = "File size to big.";
return false;
}
} else {
$error = "File type not allow.";
return false;
}
}


note: $image is an array of the image uploaded (from $_FILES)

PHP - Send email with attachment | Email script

I've tested this in gmail, yahoo, and hotmail. So far, it worked fine.

code:


function send_email($data, $subject, $content, $attachment = NULL) {

$name_from = $data["name_from"]; // Who the email is from
$email_from = $data["email_from"]; // Who the email is from
$email_to = $data["email_to"]; // Who the email is to
$email_cc = $data["email_cc"]; // Who the email is cc
$email_bcc = $data["email_bcc"]; // Who the email is bcc
$fileatt = $attachment["tmp_name"]; // Path to the file
$fileatt_type = $attachment["type"]; // File Type
$fileatt_name = $attachment["name"]; // Filename that will be used for the file as the attachment
$email_subject = $subject; // The Subject of the email
$email_message = $content; // Message that the email has in it

$semi_rand = md5(time());
$mime_boundary = $semi_rand;

$headers = "From: $name_from<$email_from>\r\n";
$headers .= ($email_bcc != "")? "Bcc: ". $email_bcc ."\r\n" : "";
$headers .= ($email_cc != "")? "Cc: ". $email_cc ."\r\n" : "";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$mime_boundary."\r\n";

// This two steps to help avoid spam
//$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
//$headers .= "X-Mailer: PHP v".phpversion()."\r\n";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";

if (!is_null($attachment)) {
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
} else {
$email_message .= "--{$mime_boundary}--\n";
}
$ok = mail($email_to, $email_subject, $email_message, $headers);
return ($ok)? true : false;
}


note: $data and $attachment are arrays