Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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.

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.

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 - 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

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

Wednesday, June 10, 2009

PHP - How to prevent sql injection | prevent hacker using sql injection attack

$query_login = "SELECT * FROM user WHERE username = '" . mysql_real_escape_string(addslashes($username)) . "'";

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

Friday, December 19, 2008

How to compress CSS files

The Reinhold Weber method


This is the best method for me do far and it's cool:


<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}


/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');


ob_end_flush();
?>

Sunday, November 9, 2008

PHP headers

To change php header to text/plain:

code:

header('Content-Type: text/plain');


To set php header to no-cache

code:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0

Thursday, October 23, 2008

PHP email validation

code:

function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") ||
checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}

Friday, September 26, 2008

Flash loadPolicyFile() - how to impliment loadPolicyFile in proper way / correct way and how to host loadPolicyFile using PHP

For those people who are searching for XMLSocket function to work properly, I will tell you step by step on how to create PHP socket server to support XMLSocket function in Flash, and also how to host your crossdomain.xml so it can be use by the Flash 9 loadPolicyFile function.

Step 1:

Since Flash 9 do not support loading the crossdomain.xml file directly by url, we must first create a socket to host the crossdomain.xml.

PHP (policySocketServer.php):

#!/usr/bin/php -q
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
function __autoload ($className)
{
$fileName = "Classes/".str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
$status = (@include_once $fileName);
if ($status === false) {
eval(sprintf('class %s {func' . 'tion __construct(){throw new Project_Exception_AutoLoad("%s");}}', $className, $className));
}
}
$ip = '127.0.0.1'; //change it to your webserver path
$port = 9996; //any port no you wish and it must be greater than 1024

//new SocketServer($ip, $port);
try{
$mySocketServer = new SocketServer($ip, $port);
} catch (Project_Exception_AutoLoad $e) {
//echo "FATAL ERROR: CAN'T FIND SOCKET SERVER CLASS.";
}
?>


Create a folder named Classes, and inside the folder create Logger.php and SocketServer.php

PHP (Logger.php):

<?php
class Logger
{
private static $instance;
public static function getInstance()
{
if(!isset($instance))
$instance = new Logger();
return $instance;
}
function __construct()
{
}

function log($message)
{
//echo "[".date('Y-m-d')."] ".$message."\n";
}
}

?>


PHP (SocketServer.php):

<?php
class SocketServer
{
var $ip;
var $port;
var $masterSocket;
var $logger;
private $currentSockets;

function __construct($ip, $port)
{
$this->ip = $ip;
$this->port = $port;
$this->logger = Logger::getInstance();
$this->initSocket();
$this->currentSockets = array();
$this->currentSockets[] = $this->masterSocket;
$this->listenToSockets();
}

private function initSocket()
{

//---- Start Socket creation for PHP 5 Socket Server -------------------------------------

if (($this->masterSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0)
{
$this->logger->log("[SocketServer] "."socket_create() failed, reason: " . socket_strerror($this->masterSocket));
}
socket_set_option($this->masterSocket, SOL_SOCKET,SO_REUSEADDR, 1);
if (($ret = socket_bind($this->masterSocket, $this->ip, $this->port)) < 0) {
$this->logger->log("[SocketServer] "."socket_bind() failed, reason: " . socket_strerror($ret));
}

if (($ret = socket_listen($this->masterSocket, 5)) < 0) {
$this->logger->log("[SocketServer] "."socket_listen() failed, reason: " . socket_strerror($ret));
}
}

private function parseRequest($socket, $data)
{
if(substr($data,0, 22) == "<policy-file-request/>")
{
//echo "POLICY FILE REQUEST\n";
$crossFile = file("http://localhost/crossdomain.xml"); //put your domain url where you uploaded the crossdomain.xml, it can also be any online webserver path
$crossFile = join('',$crossFile);
$this->sendMessage(array($socket),$crossFile);
return;
}
}

public function sendMessage($sockets, $message)
{
$message .= "\0";
if(!is_array($sockets))
$sockets = array($sockets);
foreach($sockets as $socket)
{
if($socket === NULL)
continue;
socket_write($socket, $message, strlen($message));
//$this->logger->log("[SocketServer] Wrote : ".$message." to ".$socket);
}
}

private function listenToSockets()
{
//---- Create Persistent Loop to continuously handle incoming socket messages ---------------------
while (true) {
$changed_sockets = $this->currentSockets;
$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
foreach($changed_sockets as $socket)
{
if ($socket == $this->masterSocket) {
if (($client = socket_accept($this->masterSocket)) < 0) {
$this->logger->log("[SocketServer] "."socket_accept() failed: reason: " . socket_strerror($socket));
continue;
} else {
// NEW CLIENT HAS CONNECTED
$this->currentSockets[] = $client;
socket_getpeername($client, $newClientAddress);
$this->logger->log("[SocketServer] "."NEW CLIENT ".$client." [IP: ".$newClientAddress."]");
}
} else {
$bytes = socket_recv($socket, $buffer, 4096, 0);
if ($bytes == 0) {
// CLIENT HAS DISCONNECTED
$this->logger->log("[SocketServer] "."REMOVING CLIENT ".$socket);
$index = array_search($socket, $this->currentSockets);
// Remove Socket from List
unset($this->currentSockets[$index]);
socket_close($socket);
}else{
// CLIENT HAS SENT DATA
$this->parseRequest($socket, $buffer);
}
}
}
}
}
}
?>


Create the crossdomain.xml file and put it in your webserver root:

XML (crossdomain.xml):

<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>


Step 2 (if you're running on local server):

Create a batch file in your desktop named runPolicyFile.bat:

Bat (runPolicyFile.bat):

c:/wamp/bin/php/php5.2.5/php.exe -q c:/wamp/www/policySocketServer.php

Click the batch file to run the script (make sure you have your webserver is up and running).

Alternative way is to run the policySocketServer.php straight away in your web browser.


Step 3:

In your flash file, include this script:

System.security.allowDomain("*");
System.security.loadPolicyFile("xmlsocket://127.0.0.1:9996"); //your webserver path and the port number you choose


You're done

You should be able to see that your XMLSocket function working now in the web browser :)

Check out the demo here . I have successfully implement PURE PHP SOCKET SERVER to build this chat application in Flash through XMLSocket function.
Any comment appreciated..

Tuesday, September 23, 2008

PHP list files in directory

code:

// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
//Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th><th>Created</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
$checkExt = explode(".", $dirArray[$index]);
if (substr("$dirArray[$index]", 0, 1) != "." && $checkExt[count($checkExt)-1] != "php"){ // don't list hidden and php files
print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
print("<td>");
print(filetype($dirArray[$index]));
print("</td>");
print("<td>");
print(filesize($dirArray[$index]));
print("</td>");
print("<td>");
print(date("F d Y H:i:s.", filectime($dirArray[$index])));
print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
clearstatcache();

Saturday, September 20, 2008

How to resize image using only PHP script

Here is the very small code sample that will resize images as they are uploaded from a web form. Please read the comments in detail. They explain exactly what is going on, and where you should make changes for the destination directory and output sizes.

This script only supports the JPG file format. The compression algorithm for GIF images is protected by a restrictive licensing agreement that prevents the developers of PHP from including support for GIF images in the base platform.

Part I: The HTML Form
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile"/>
<input type="submit"/>
</form>

Part II: Getting at the file, resizing the image, and saving to the server. (upload.php)
<?php
// This is the temporary file created by PHP
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);
// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);
// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.
?>

Friday, September 19, 2008

Flash load XML from php

code (in flash):

//set array
var company_name:Array = new Array();
var client_id:Array = new Array();

var ClientXML:XML = new XML();
ClientXML.ignoreWhite = true;
var height = 0;
ClientXML.onLoad = function() {
var nodes = this.firstChild.childNodes;
for (i=0;i<nodes.length;i++) {
movname="MovieClip_" + i;
company_name.push(nodes[i].firstChild.nodeValue);
client_id.push(nodes[i].attributes.id);
attachMovie("MovieClip_", movName, i);
eval("MovieClip_" + movName).company_name_tb.text = company_name[i];
eval("MovieClip_" + movName).clientID_tb.text = client_id[i];
eval("MovieClip_" + movName)._y = height;
height += eval("MovieClip_" + movName)._height;
}
}
ClientXML.load("clientflash.php");

-------------------------------------------------------------------------------------

code (clientflash.php - assuming you have the database connection, $client_listRS):

<?php
echo "<?xml version=\"1.0\"?>\n";
echo "<client>\n";
do {
echo "<company id="&quot; . $row_client_listRS[" client_id=""><![CDATA[" . $row_client_listRS['company_name'] . "]]></company>\n";
} while ($row_client_listRS = mysql_fetch_assoc($client_listRS));
echo "</client>\n";
?>