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

Thursday, January 21, 2010

PHP - Dynamically resize an image without storing it

It is really a hassle to resize an image uploaded to be stored in different sizes, why not we resize it dynamically? Here I will show you how to generate an image with php for different sizes as we wish:

code:

<?php
$newwidth = $_GET["width"];
$newheight = $_GET["height"];
$image = $_GET["url"];
$ratio = ($_GET["ratio"] != "")? $_GET["ratio"] : "false";
$dst_x = ($_GET["dst_x"] != "")? intval($_GET["dst_x"]) : 0;
$dst_y = ($_GET["dst_y"] != "")? intval($_GET["dst_y"]) : 0;
$src_x = ($_GET["src_x"] != "")? intval($_GET["src_x"]) : 0;
$src_y = ($_GET["src_y"] != "")? intval($_GET["src_y"]) : 0;

$src = imagecreatefromjpeg($image);
list($width,$height)=getimagesize($image);
$newwidth = ($newwidth != "")? $newwidth : $width;
$newheight = ($newheight != "")? $newheight : $height;
if ($ratio == "true") {
$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,$dst_x,$dst_y,$src_x,$src_y,$newwidth,$newheight,$width,$height);
imagejpeg($tmp);
header("Content-type: image/jpeg");
?>


How to use it :
-Save above as image.php
-Use it like : image.php?url=http://t2.gstatic.com/images?q=tbn:ZqzO2ew7hmrDJM%3Ahttp://farm3.static.flickr.com/2204/2403693037_0b63bdc4b4.jpg&width=100&height=100&ratio=true

Monday, December 21, 2009

Thursday, November 19, 2009

AS3 ExternalInterface | How to use ExternalInterface in AS3 | javascript to call function in flash using ExternalInterface

With ExternalInterface function in AS3, we can call javascript functions that are outside flash and vice versa.


code (flash):


//we can set a callback to our function in flash to enable javascript function to call it
if (ExternalInterface.available) {
ExternalInterface.addCallback("send_from_external", send_from_external);
}
function send_from_external(newText) {
trace(newText);
}

//to call a javascript function from flash
if (ExternalInterface.available) {
ExternalInterface.call("updateMsg", "your string");
}


code (html):

<script language="JavaScript">
function getFlashId(idIe, idMoz) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? idIe : idMoz;
}
function send_message() {
$("#txt_area").attr("disabled", "disabled");
getFlashMovie(getFlashId("swfObject", "swfEmbed")).send_from_external("test_string"); //trigger function inside flash
}
function updateMsg(string) {
alert(string); //from flash
}
</script>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="swfObject"
width="1"
height="1"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<param name="movie" value="test.swf" />
<param name="quality" value="low" />
<param name="allowScriptAccess" value="always" />
<param name="flashVars" value="" />
<embed id="swfEmbed"
src="test.swf"
quality="low"
width="1"
height="1"
name="ExternalInterfaceExample"
align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
flashVars="">
</embed>
</object>

Wednesday, November 11, 2009

AS3 LocalConnection | local connection between flash | flash internal connection

Here're the basic structure to simple LocalConnection for flash as3. LocalConnection is used when you want to connect 2 or more swf in a pc to exchange data.

To receive:

//receive
var receivingLC:LocalConnection;
receivingLC = new LocalConnection();
receivingLC.client = this;
receivingLC.connect('session_name');

function myMethod(textRecieved:String){
//do your things
}


To send:

//sending
var sendingLC:LocalConnection;
sendingLC = new LocalConnection();
sendingLC.send('message_input', 'myMethod', "test");
sendingLC.addEventListener(StatusEvent.STATUS, onStatus);

function onStatus(event:StatusEvent){
switch (event.level) {
case "error":
trace("LocalConnection.send() failed");
break;
case "status":
trace("LocalConnection.send() succeeded");
break;
default:break;
}
}

Wednesday, October 28, 2009

AS3 simple email validation check

function checkMail(pmail:String) {
if (! (pmail.lastIndexOf(".") <= pmail.indexOf("@") || pmail.indexOf("@")==-1)) {
return true;
} else {
return false;
}
}

Tuesday, October 27, 2009

Chrome and safari css hacks

@media screen and (-webkit-min-device-pixel-ratio:0) {
#div { properties:value; }
}

Monday, September 28, 2009

AS3 Socket Connection

This example shows how to successfully connect flash to your ftp server..

var s:Socket = new Socket("YOUR_SERVER", 21);
s.addEventListener(ProgressEvent.SOCKET_DATA, sData);

function sData(e:ProgressEvent):void
{
var d:String = s.readUTFBytes(s.bytesAvailable);
trace(d);
if(d.indexOf("+OK Hello there") != -1)
s.writeUTFBytes("USERNAME\n");
if(d.indexOf("+OK Password required.") != -1)
s.writeUTFBytes("PASSWORD\n");
if(d.indexOf("+OK logged in.") != -1)
s.writeUTFBytes("STAT\n");
s.flush();
}

Tuesday, July 21, 2009

How to impliment fullscreen flash html in browser

<!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>
<style type="text/css">
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
body {
background-color: #000000;
}
</style>
<script language="JavaScript" type="text/javascript">
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 10;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 0;
// the version of javascript supported
var jsVersion = 1.0;
// -----------------------------------------------------------------------------
// -->
</script>
<script language="VBScript" type="text/vbscript">
<!-- // Visual basic helper required to detect Flash Player ActiveX control version information
Function VBGetSwfVer(i)
on error resume next
Dim swControl, swVersion
swVersion = 0

set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
if (IsObject(swControl)) then
swVersion = swControl.GetVariable("$version")
end if
VBGetSwfVer = swVersion
End Function
// -->
</script>
<script language="JavaScript1.1" type="text/javascript">
<!-- // Detect Client Browser type
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
jsVersion = 1.1;
// JavaScript helper required to detect Flash Player PlugIn version information
function JSGetSwfVer(i){
// NS/Opera version >= 3 check for Flash plugin in plugin array
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
descArray = flashDescription.split(" ");
tempArrayMajor = descArray[2].split(".");
versionMajor = tempArrayMajor[0];
versionMinor = tempArrayMajor[1];
if ( descArray[3] != "" ) {
tempArrayMinor = descArray[3].split("r");
} else {
tempArrayMinor = descArray[4].split("r");
}
versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
} else {
flashVer = -1;
}
}
// MSN/WebTV 2.6 supports Flash 4
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
// WebTV 2.5 supports Flash 3
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
// older WebTV supports Flash 2
else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
// Can't detect in all other cases
else {

flashVer = -1;
}
return flashVer;
}
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
reqVer = parseFloat(reqMajorVer + "." + reqRevision);
for (i=25;i>0;i--) {
if (isIE && isWin && !isOpera) {
versionStr = VBGetSwfVer(i);
} else {
versionStr = JSGetSwfVer(i);
}
if (versionStr == -1 ) {
return false;
} else if (versionStr != 0) {
if(isIE && isWin && !isOpera) {
tempArray = versionStr.split(" ");
tempString = tempArray[1];
versionArray = tempString .split(",");
} else {
versionArray = versionStr.split(".");
}
versionMajor = versionArray[0];
versionMinor = versionArray[1];
versionRevision = versionArray[2];

versionString = versionMajor + "." + versionRevision;
versionNum = parseFloat(versionString);

if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
return true;
} else {
return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
}
}
}
return (reqVer ? false : 0.0);
}
// -->
</script>
</head>
<body bgcolor="#ffffff" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0">
<link rel="Shortcut Icon" href="/favicon.ico">
<script language="JavaScript" type="text/javascript">
<!--
var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
if(hasRightVersion) {
var oeTags = '<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">'
+ '<tr>'
+ '<td width="100%" height="100%">'
+ '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
+ 'width="100%" height="100%"'
+ 'codebase="http://get.adobe.com/flashplayer/">'
+ '<param name="movie" value="loader.swf" /><param name="menu" value="false" /><param name="quality" value="high" />'
+ '<embed src="loader.swf" menu="false" quality="high"'
+ 'width="100%" height="100%" name="index" align="middle"'
+ 'play="true"'
+ 'loop="false"'
+ 'quality="high"'
+ 'allowScriptAccess="sameDomain"'
+ 'type="application/x-shockwave-flash"'
+ 'pluginspage="http://get.adobe.com/flashplayer/">'
+ '<\/embed>'
+ '<\/object>'
+'</td>'
+ '<td><div align="center"><img src="html_img/1x600.jpg" width="1" height="600"></div></td>'
+ '</tr>'
+ '<tr>'
+ '<td><div align="center"><img src="html_img/900x1.jpg" width="900" height="1"></div></td>'
+ '<td></td>'
+ '</tr>'
+ '</table>';
document.write(oeTags);
} else {
document.write('This content requires the Macromedia Flash Player.<a href="http://get.adobe.com/flashplayer/">Get Flash Player 10</a>');
}
// -->
</script>
<script type="text/javascript">
objects = document.getElementsByTagName("object");
for (var i = 0; i < objects.length; i++)
{
objects[i].outerHTML = objects[i].outerHTML;
}
</script>
<noscript>
This content requires the Macromedia Flash Player.
<a href="http://www.macromedia.com/go/getflash/">Get Flash</a>
</noscript>
</body>
</html>

Friday, July 3, 2009

PHP - cURL | how login to facebook without going to the site using cURL

1 - Update your Facebook status

Wanna update your facebook status, but don't want to go to facebook.com, login, and finally being able to update your status? Simply save the following code on your server, define the variables, and voilà!

<?PHP
/*******************************
* Facebook Status Updater
* Christian Flickinger
* http://nexdot.net/blog
* April 20, 2007
*******************************/

$status = 'YOUR_STATUS';
$first_name = 'YOUR_FIRST_NAME';
$login_email = 'YOUR_LOGIN_EMAIL';
$login_pass = 'YOUR_PASSWORD';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
$page = curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 1);
preg_match('/name="post_form_id" value="(.*)" \/>'.ucfirst($first_name).'/', $page, $form_id);
curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update');
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_exec($ch);
?>

Source: http://codesnippets.joyent.com/posts/show/1204

2 - Get download speed of your webserver

Do you ever wanted to know the exact download speed of your webserver (or any other?) If yes, you'll love that code. You just have to initialize the $url variable with any resources from the webserver (images, pdf, etc), place the file on your server and point your browser to it. The output will be a full report of download speed.

 $value)
{
printf("%-30s %s\n", $label, $value);
}
?>

Source: http://cowburn.info/2008/11/29/download-speed-php-curl

3 - Myspace login using cURL

<?php

function login( $data, $useragent = 'Mozilla 4.01', $proxy = false ) {
$ch = curl_init();
$hash = crc32( $data['email'].$data['pass'] );
$hash = sprintf( "%u", $hash );
$randnum = $hash.rand( 0, 9999999 );
if( $proxy ) curl_setopt( $ch, CURLOPT_PROXY, $proxy );
curl_setopt( $ch, CURLOPT_COOKIEJAR, '/tmp/cookiejar-'.$randnum );
curl_setopt( $ch, CURLOPT_COOKIEFILE, '/tmp/cookiejar-'.$randnum );
curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_POST, 0);
curl_setopt( $ch, CURLOPT_URL, 'http://www.myspace.com' );
$page = curl_exec( $ch );
preg_match( '/MyToken=(.+?)"/i', $page, $token );
if( $token[1] ) {
curl_setopt( $ch, CURLOPT_URL, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] );
curl_setopt( $ch, CURLOPT_REFERER, 'http://www.myspace.com' );
curl_setopt( $ch, CURLOPT_HTTPHEADER, Array( 'Content-Type: application/x-www-form-urlencoded' ) );
curl_setopt( $ch, CURLOPT_POST, 1 );
$postfields = 'NextPage=&email='.urlencode( $data['mail'] ).'&password='.urlencode( $data['pass'] ).'&loginbutton.x=&loginbutton.y=';
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postfields );
$page = curl_exec( $ch );
if( strpos( $page, 'SignOut' ) !== false ) {
return $randnum;
}
else {
preg_match( '/MyToken=(.+?)"/i', $page, $token );
preg_match( '/replace\("([^\"]+)"/', $page, $redirpage );
if( $token[1] ) {
curl_setopt( $ch, CURLOPT_POST, 0 );
curl_setopt( $ch, CURLOPT_URL, 'http://home.myspace.com/index.cfm?&fuseaction=user&Mytoken='.$token[1] );
$page = curl_exec( $ch );
curl_close( $ch );
if( strpos( $page, 'SignOut' ) !== false ) {
return $randnum;
}
}
elseif( $redirpage[1] ) {
curl_setopt( $ch, CURLOPT_REFERER, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] );
curl_setopt( $ch, CURLOPT_URL, $redirpage[1] );
curl_setopt( $ch, CURLOPT_POST, 0 );
$page = curl_exec( $ch );
curl_close( $ch );
if( strpos( $page, 'SignOut' ) !== false ) {
return $randnum;
}
}
}
}
return false;
}
?>

Source: http://www.seo-blackhat.com/article/myspace-login-function-php-curl.html

4 - Publish a post on your WordPress blog, using cURL

I know that most of you enjoy WordPress, so here is a nice "hack" as the ones I regulary publish on my other blog WpRecipes.
This function can post on your WordPress blog. You don't need to login to your WP dashboard etc.
Though, you must activate the XMLRPC posting option in your WordPress blog. If this option isn't activated, the code will not be able to insert anything into WordPress database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8')
{
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
?>

Source: http://porn-sex-viagra-casino-spam.com/coding/poster-automatiquement-sur-wordpress-avec-php/

5 - Test the existence of a given url

I know, it sounds basic. In fact, it is basic, but it is also very useful, especially when you have to work with external resources.

 

Source: http://www.jellyandcustard.com/2006/05/31/determining-if-a-url-exists-with-curl/

6 - Post comments on WordPress blogs

In a previous article, I have discussed how spammers spams your WordPress blog. To do so, they simply have to fill the $postfields array with the info they want to display and load the page.
Of course, this code is only for educationnal purposes.


Source: http://www.catswhocode.com/blog/how-spammers-spams-your-blog-comments

7 - Follow your Adsense earnings with an RSS reader

Most bloggers uses Adsense on their blog and (try to) make money with Google. This excellent snippet allows you to follow your Adsense earnings...with a RSS reader! Definitely awesome.
(Script too big to be displayed on the blog, click here to preview)
Source: http://planetozh.com/blog/my-projects/track-adsense-earnings-in-rss-feed/

8 - Get feed subscribers count in full text

If you're a blogger, you're probably using the popular FeedBurner service, which allo you to know how many people grabbed your rss feed. Feedburner have a chicklet to proudly display your subscriber count on your blog. I personally like the chicklet's look, but I heard lots of bloggers complaining about it. happilly, cURL can simply grab the count value and return it to you as a variable so you can display it as you want on your blog.

//get cool feedburner count
$whaturl="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=feedburner-id";

//Initialize the Curl session
$ch = curl_init();

//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Set the URL
curl_setopt($ch, CURLOPT_URL, $whaturl);

//Execute the fetch
$data = curl_exec($ch);

//Close the connection
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
//end get cool feedburner count

Source: http://www.hongkiat.com/blog/display-google-feed-subscriber-count-in-text/

9 - Get the content of a webpage into a PHP variable

This is a very basic thing to do with cURL, but with endless possibilities. Once you have a webpage in a PHP variable, you can for example, retrieve a particular information on the page to use on your own website.


10 - Post to Twitter using PHP and cURL

Twitter is very popular since some time now, and you probably already have an account there. (We have one too) So, what about using cURL to tweet from your server without connectiong to Twitter?


Source: http://morethanseven.net/2007/01/20/posting-to-twitter-using-php/

Original source: http://www.catswhocode.com/blog/10-awesome-things-to-do-with-curl

Thursday, June 11, 2009

AS3 - Load xml, another approach

var xmlloader:URLLoader = new URLLoader();
xmlloader.addEventListener(Event.COMPLETE, handleComplete);
xmlloader.load(new URLRequest("test.xml"));
var theXML:XML = new XML();
theXML.ignoreWhitespace = true;

function handleComplete(e:Event){
theXML = XML(e.target.data);

var itemList:XMLList = theXML.child("*");

for each (var _item:XML in itemList) {
trace(_item.title.toString());
trace(_item.description.toString());
}

}

Wednesday, June 10, 2009

Tuesday, June 9, 2009

ASP - Create dsn less connection to ms access | ms access database dsn less connection

<% Set MyConn = Server.CreateObject("ADODB.Connection")
ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & server.mappath("your.mdb") & ";"
'ConnectionString = ConnectionString & "Password=YourPassword;"
MyConn.Open ConnectionString
SQL_query = "SELECT * FROM user"
Set RS = MyConn.Execute(SQL_query)
IF (RS.EOF) then response.write("nothing")
WHILE NOT RS.EOF %>
<li><%=RS("Name")%>
<% RS.MoveNext
WEND
%>
</li>

Sunday, June 7, 2009

PHP - Bad words filter using eregi_replace | bad words filter list

//bad word filter function

$openFileBW = fopen("badwords.txt", "r"); //open the text file
while(!feof($openFileBW))
{
$bw .= fgets($openFileBW);
}
fclose ($openFileBW);
$bad_words = explode(',', $bw);
$strToReplace = $theSentence; //the sentence u want to check
foreach ($bad_words as $naughty)
{
$strToReplace = eregi_replace($naughty, "#love#", $strToReplace); //replace with #love# ;)
}
$theSentence = $strToReplace;



The bad words filter list (save it to badwords.txt):

ahole,anus,ash0le,ash0les,asholes,ass,Ass Monkey,Assface,assh0le,assh0lez,asshole,assholes,assholz,asswipe,azzhole,bassterds,bastard,bastards,bastardz,basterds,basterdz,Biatch,bitch,bitches,Blow Job,boffing,butthole,buttwipe,c0ck,c0cks,c0k,Carpet Muncher,cawk,cawks,Clit,cnts,cntz,cock,cockhead,cock-head,cocks,CockSucker,cock-sucker,crap,cum,cunt,cunts,cuntz,dick,dild0,dild0s,dildo,dildos,dilld0,dilld0s,dominatricks,dominatrics,dominatrix,dyke,enema,f u c k,f u c k e r,fag,fag1t,faget,fagg1t,faggit,faggot,fagit,fags,fagz,faig,faigs,fart,flipping the bird,fuck,fucker,fuckin,fucking,fucks,Fudge Packer,fuk,Fukah,Fuken,fuker,Fukin,Fukk,Fukkah,Fukken,Fukker,Fukkin,g00k,gay,gayboy,gaygirl,gays,gayz,God-damned,h00r,h0ar,h0re,hells,hoar,hoor,hoore,jackoff,jap,japs,jerk-off,jisim,jiss,jizm,jizz,knob,knobs,knobz,kunt,kunts,kuntz,Lesbian,Lezzian,Lipshits,Lipshitz,masochist,masokist,massterbait,masstrbait,masstrbate,masterbaiter,masterbate,masterbates,Motha Fucker,Motha Fuker,Motha Fukkah,Motha Fukker,Mother Fucker,Mother Fukah,Mother Fuker,Mother Fukkah,Mother Fukker,mother-fucker,Mutha Fucker,Mutha Fukah,Mutha Fuker,Mutha Fukkah,Mutha Fukker,n1gr,nastt,nigger,nigur,niiger,niigr,orafis,orgasim,orgasm,orgasum,oriface,orifice,orifiss,packi,packie,packy,paki,pakie,paky,pecker,peeenus,peeenusss,peenus,peinus,pen1s,penas,penis,penis-breath,penus,penuus,Phuc,Phuck,Phuk,Phuker,Phukker,polac,polack,polak,Poonani,pr1c,pr1ck,pr1k,pusse,pussee,pussy,puuke,puuker,queer,queers,queerz,qweers,qweerz,qweir,recktum,rectum,retard,sadist,scank,schlong,screwing,semen,sex,sexy,Sh!t,sh1t,sh1ter,sh1ts,sh1tter,sh1tz,shit,shits,shitter,Shitty,Shity,shitz,Shyt,Shyte,Shytty,Shyty,skanck,skank,skankee,skankey,skanks,Skanky,slut,sluts,Slutty,slutz,son-of-a-bitch,tit,turd,va1jina,vag1na,vagiina,vagina,vaj1na,vajina,vullva,vulva,w0p,wh00r,wh0re,whore,xrated,xxx,b!+ch,bitch,blowjob,clit,arschloch,fuck,shit,ass,asshole,b!tch,b17ch,b1tch,bastard,bi+ch,boiolas,buceta,c0ck,cawk,chink,cipa,clits,cock,cum,cunt,dildo,dirsa,ejakulate,fatass,fcuk,fuk,fux0r,hoer,hore,jism,kawk,l3itch,l3i+ch,lesbian,masturbate,masterbat,masterbat3,motherfucker,mofo,nazi,nigga,nigger,nutsack,phuck,pimpis,pusse,pussy,scrotum,sh!t,shemale,shi+,sh!+,slut,smut,teets,tits,boobs,b00bs,teez,testical,testicle,titt,w00se,jackoff,wank,whoar,whore,damn,dyke,fuck,shit,amcik,andskota,arse,assrammer,ayir,bi7ch,bitch,bollock,breasts,butt-pirate,cabron,cazzo,chraa,chuj,Cock,cunt,d4mn,daygo,dego,dick,dike,dupa,dziwka,ejackulate,Ekrem,Ekto,enculer,faen,fag,fanculo,fanny,feces,feg,Felcher,ficken,fitt,Flikker,foreskin,Fotze,Fu,fuk,futkretzn,gay,gook,guiena,h0r,h4x0r,hell,helvete,hoer,honkey,Huevon,hui,injun,jizz,kanker,kike,klootzak,kraut,knulle,kuk,kuksuger,Kurac,kurwa,kusi,kyrpa,lesbo,mamhoon,masturbat,merd,mibun,monkleigh,mouliewop,muie,mulkku,muschi,nazis,nepesaurio,nigger,orospu,paska,perse,picka,pierdol,pillu,pimmel,piss,pizda,poontsee,poop,porn,p0rn,pr0n,preteen,pula,pule,puta,puto,qahbeh,queef,rautenberg,schaffer,scheiss,schlampe,schmuck,screw,sh!t,sharmuta,sharmute,shipal,shiz,skribz,skurwysyn,sphencter,spic,spierdalaj,splooge,b00b,testicle,titt,twat,vittu,wank,wetback,wichser,wop,yed,zabourah,puki,pukimak,lancau,cibai,niama,babi,mak kau,bapak kau,nenek kau,sial,siol,taik,kote,anjingan,banjingan,bangsat,bangang,bengong,bodoh,bodo,dogol,pepek,pepet,pantat,konek,kotek,haramjadah,anak haram,sundal,cinabeng,keling,buto,butoh