Posts tagged application

Writing a simple Facebook App

1

In this tutorial I am going to show you how to create a simple Facebook application.

Getting the basics

First of all you'll need to install the developer application on Facebook. To do this log in to your Facebook account and visit this link here to install the Developer application. You should be redirected to this screen:

Now you've installed the developer application you will need to create your first application. Click on the 'Apply for a key' and fill in the necessary details.

Give you application a name. In this example I have called mine 'My Test Application'. For the two email fields you should put in your email. Now for the callback URL. This is the directory on your host containing the files. Your application should definitely have it's own folder on your host (if not Facebook users will probably be able to access files you don't want them too). I've entered mine as http://www.urbanoalvarez.es/facebookApp/. All that's really left to do is your Facebook canvas page URL. I'm going to use aSimpleTestApp for mine. You can use anything you want as long as it's available. You shouldn't need to edit anything else. Just click 'Submit' to create the application.

You should have been redirected to the previous page only now you will see you have created an application. Note down the secret question, api key and your callback URL because you will need them in the next stage.

Now you've created your application you will need to install the Facebook Platform libraries on your host. You can download them here:
http://developers.facebook.com/clientlibs/facebook-platform.tar.gz

Once you've installed the libraries (read the README if you need any assistance) then you can start coding. First of all we need to create a config file which initiates the API and allows us to make a connection with Facebook.

The actual code

< ?php
   require_once 'client/facebook.php'; // Path to Facebook.php (either inside 'client' or 'php4client')
   $appapikey = 'apikey'; // Enter your API key you noted down earlier
   $appsecret = 'yoursecret'; // Enter your secret you noted down earlier
   $facebook = new Facebook($appapikey, $appsecret); // Initiate client
   $user = $facebook->require_login(); // Authorize current user
 
   $appcallbackurl = 'http://www.drcrazy4.info/fbapp/'; // Your callback URL
   // Has the logged in user installed the application
  try{
     if ($facebook->api_client->users_isAppAdded() == ""){ // If the application hasn't been added
          $facebook->redirect($facebook->get_add_url()); // Redirect the user to the add applciation link
     }
  }catch (Exception $ex){
         $facebook->set_user(null, null); // Clear current application cookies
         $facebook->redirect($appcallbackurl); // Redirect user to application
  }
  ?>

Save that file as config.php.

Now we have the authorization done we can get productive. For this application we're going to create a simple hello world application (I know how boring. In later tutorials I will discuss things like friends, photos etc.). Here is what's left:

< ?php
   include 'config.php'; // The file we made just now
 
   $echo = 'Hello there ' . $user; // $user is the logged in user. This will be displayed on the main application page
   $fbml = <<<EndHereDoc
   Hello world!
   EndHereDoc; // This is what will be displayed on users profile pages.
 
   $facebook->api_client->profile_setFBML($fbml, $user);
   // Set the profile box content for the logged in user
   ?>

Save that file as index.php.

Now test your application. You should see 'Hello world!' in a box on your profile and on the main application page you should see 'Hello [USERNAME]' ([USERNAME] being your current username). In later tutorials I will discuss a little more about FBML and how you can use the client libraries to get users friends etc. Tutorial source iscripting.com

If you have a question please feel free to ask.

PHP logging class v. 1.2

26

Hi guys,
I've decided to give out a PHP class I created to easily log anything we want in our websites.

Features

This are the things the logging class will do:

  • Store different security levels (Low, Medium, and High)
  • Get the real visitor's IP for every log entry
  • Allow several optional parameters, such as message, priority, page...
  • Easily translated into other languages
  • TABLE_LOGS.sql.txt - This file creates the table 'log'

And this is a screenshot of the log page in action (Or go to the sample page and take a look)
Screenshot of log

Class files and code:

The following files are the really important files:

  • log.class.php - This file contains the logging functions.
  • database.php - This file handles database connection and queries.
  • config.php - This file defines the configuration constants used for database queries. You should only edit this file.
  • logInit.php - This file includes all necessary files and initializes the classes storing them in the appropriate objects

Also, for the example, there are two other files: 'log.php' and 'test.php'. The log.php file shows a sample log, and the test.php shows a sample usage page.

Log in use:

I've set up a test page and a log page. In the test page there are several "common" stuff that you would normally log (A login form, an edit form, and a contact form)

I would recommend that you check those out, in any order you like, and experiment with the different options you'll see in the test page

Usage:

The usage of this logging class is VERY very simple, First of all download the zip with the needed files.
Then you must fill in all the variables in the config.php page.
Once all is configured, upload it to your server, and insert the following code in all the pages you will like to log activity:

 
< ?php
//Initialize logging clases
include('logInit.php');
//
?>
 

This is the initialization of the logging object and all other needed stuff.

The logging function is:

 
< ?php
$log->logg('page','message','priority','class','mail');
?>
 

Parameters explanation:

  • Page: This is the page where the log is placed. Set to 1 and it will be automatically detected.
  • Message: This is the message you want to have the log store. You can have some preset messages which are stored in the log.class.php file. Set to 1 to have a preset message stored.
  • Priority: This is the priority or Importance of the log entry. Values can be: High,Medium,Low.
  • Class: This is the class you want the log entry to have. Values are: Red, Danger, Yellow, Green, and Blue.
  • Mail: This setting can be yes or no. If it is not specified it will be set to "no".

You can edit the list of pre-set important pages in the file log.class.php, which is strongly recommended.

Download

Here you may download the zip file containing all necessary files to get the logging running:

Download zip - v. 1.2 - 22kb (3163 downloads)
Mirror #2 Zip file - @ PHP Classes (Without the icons)

It includes a css file with all needed styles, the icons, a log emptying page, a log sample page, the test page, and all the other files needed for the logging.

If you improve this script, or you find any bugs, report them using the comments please!
And remember, for any doubt or problem you have with the usage of this class, comment here and leave an email in the field email so I can answer you!

Creating an IRC bot in PHP from scratch

7

IRC Bot :DI came across several articles about this topic, and I decided to take a look at it, combine them, and actually have the bot work.

The way this bot works is it will open up a server, join an IRC chat channel and post a message, going into idle status after that, waiting to receive a ping in response. If you don't want to wait, once the message is posted you can cancel page loading and enter the page again (Not reload it, since that would send the message again), and you would have the message posted.
A good use for this bot (Although not recommended because of the high traffic) would be to send messages to hundreds of different IRC channels, or to have the program refresh the page every minute or so and send a message to certain IRC channels every x time.

We will create a new file, named "irc_bot.php" with the following function:

 
< ?php
function writeIRC($msg){
	// define your variables
	$host = "irc.dal.net";
	$port=6666;
	$nick="demoTester";
	$ident="DemoTester";
	$chan="#frih";
	$readbuffer="";
	$realname = "Demo Tester";
 
	// open a socket connection to the IRC server
	$fp = fsockopen($host, $port, $erno, $errstr, 30);
 
	// print the error if ther eis no connection
	if (!$fp) {
		echo $errstr." (".$errno.")\n";
	} else {
		// write data through the socket to join the channel
		fwrite($fp, "NICK ".$nick."\r\n");
		fwrite($fp, "USER ".$ident." ".$host." bla :".$realname."\r\n");
		fwrite($fp, "JOIN :".$chan."\r\n");
 
		// write data through the socket to print text to the channel
		fwrite($fp, "PRIVMSG ".$chan." :$msg\r\n");
 
		$timep = 0; //set up timer
		$timep = round(microtime(), 3); //start microtime
		// loop through each line to look for ping
		 while (!feof($fp)) {
 
			$line =  fgets($fp, 128);
			echo $line."\n";
 
			$line = explode(":ping ", $line);
 
			echo $line[0]."\n";
 
			if ($line[1]) {
 
				fwrite($fp, "PONG ".$line[1]."\r\n");
			}
			$time2 = round(microtime(), 3); //set up second timer
			$gen = $time2 - $timep; //find the difference
			if($gen > 30){
				//timeout - break loop
				echo '
 
Operation finished without receiving ping. Check out the stats iframe to see your message.
 
';
				break;
			}
		}
 
		fclose($fp);
	}
}
?>

Using it:

So now you should join a channel in the server you like, for this example I will be using one of frihost.com's IRC channels (Server: irc.dal.net Channel: #frih)

The way you would use this bot would be to send messages every set period of time for example, with loop functions, or to manage IRC channels, if you leave the last loop of code and you examine every single line posted on the channel.
You could also use it to warn users, or to post to several channels at the same time... The uses are varied, and here you have a base code to start from... :D

Have fun, and if you use it, post a link in the comments and I'll include it here in the article, as examples of usage.

Example of Bot working

Well I have created a simple page that will use POST to send data to the IRC server, and then I included the channel stats in an iframe below, so you can see the results live... ;) It's pretty cool, so try it, and if you wonder how it is done download the demo page.

  1. Go to demo page
  2. Download demo page (3kb)

For any questions/suggestions please comment

Simple CMS with language changer functions (v. 1.1)

0

Introduction:

Definition of languageToday I'll show you a way of translating your website very easily, and then have the browser detect user language automatically.

First you need some sort of php template system, I'll show you the one that I've developed, which is not very advanced but works perfectly for small sites.

What it does is in each page there is always a part that repeats. In my main page the repeating part is the header, left sidebars, and footer. And the only thing that changes is the content. What I did is a class called page, and that class generated the code needed for the header, sidebar and footer. The content is included from a folder called "content", which then contains subfolders, each named with the language code, so if the folder contains the spanish translation it would be named "es". (See all language codes)

Another class is "session", it does a check for new users or returning users based on session variables that store their preferred language, it also checks for the URI changer (?lang=...), and if none of that is found, it then checks for the user OS language, then checks if it is available and if it is, it sets it as preferred language of the site, if not, the default language is selected.

Codes for this:

The following codes must go in a folder structure like so "lib/content/". This can be change, but it makes it more easy to understand.

At the bottom of this there is a link to a zip file containing all necessary files to have this work

The filenames I used are: "page.php" for the page object, and "session.php" for the session object.

The page object (simplified):

//This contains the page object - Used to generate the page layout
 
class Page
 
{
 
var $timep = 0;
 
//functions to display a page:
 
function genTop($title,$extraCSS='',$extraScripts='',$extras=''){ //for the top part (doctype...)
 
//setup time counter
 
$this-&gt;timep = round(microtime(), 3);
 
//start file inclusion
 
include('lib/content/core/doctype.htm'); //includes opening html tag and head
 
include('lib/content/core/metas.htm'); //includes the meta data (All the same)
$metaLang = $_SESSION['lang'].'-'.strtoupper($_SESSION['lang']);
echo '&lt;meta http-equiv="Content-Language" content="'.$metaLang.'" /&gt;'; //language meta tag
 
if($title !== ''){ $title = $title.' | '; } //add | if necesary
 
echo '&lt;title&gt;'.$title;
 
switch($_SESSION['lang']){
 
case 'es':
 
echo 'Fundacion Urbano Alvarez';
 
break;
 
case 'en':
 
echo 'Urbano Alvarez Foundation';
 
break;
 
}
 
echo '&lt;/title&gt;';
 
include('lib/content/core/link-rel.htm'); //includes the linking css
 
if($extraCSS !== ''){
 
//Get an array with all extra style sheets
 
$css = explode(',',$extraCSS);
 
$totalCSS = count($css);
 
//now iterate through all extra css
 
for($i=0; $i&lt;$totalCSS; $i++){
 
echo '&lt;link rel="stylesheet" type="text/css" href="'.$css[$i].'" media="all" /&gt;';
 
}
 
//
 
}
 
include('lib/content/core/scripts.php'); //includes all javascript scripts
 
if($extraScripts !== ''){
 
//get an array with all extra scripts
 
$scripts = explode(',',$extraScripts);
 
$totalScripts = count($scripts);
 
//Now include all extra scripts
 
for($i=0; $i&lt;$totalScripts; $i++){
 
echo '&lt;script language="javascript" type="text/javascript" src="'.$scripts[$i].'"&gt;&lt;/script&gt;';
 
}
 
//
 
}
 
echo $extras; // Any extra code that may be entered before the head
 
echo '&lt;/head&gt;';
 
//
 
echo '&lt;body&gt;';
 
include('lib/content/core/top.php');
 
include('lib/content/core/left.php'); //The left navigation column
 
echo '&lt;div id="content"&gt;';
 
}
 
function genContent($pageName=''){
 
global $session;
 
if($pageName == ''){
 
$pageName = $session-&gt;url;
 
}
 
include('lib/content/'.$_SESSION['lang'].'/'.$pageName);
 
}
 
function genBottom($extraFooter='',$extraScripts=''){
 
if($_SESSION['lang'] == 'es'){
 
$changeLang = 'Cambiar idioma a: &lt;a href="?lang=en"&gt;English&lt;/a&gt;';
 
}else{
 
$changeLang = '...'; //Here goes code for extra stuff (I use it for stumbleupon)
 
}
 
echo '&lt;p&gt;'.$changeLang.'&lt;/p&gt;';
 
echo '&lt;/div&gt;&lt;!-- end .content  --&gt;';
 
echo '&lt;div id="footer"&gt;';
 
echo '&lt;div id="footerLeft"&gt;&lt;img src="img/body/footerLeft.jpg" width="41" height="93" /&gt;&lt;/div&gt;';
 
echo '&lt;div id="footerText"&gt;';
 
$time2 = round(microtime(), 3);
 
$gen = $time2 - $this-&gt;timep;
 
if($_SESSION['lang'] == 'es'){
 
echo 'Spanish footer';
 
}else if($_SESSION['lang'] == 'en'){
 
echo 'English footer';
 
}
 
if($extraFooter !== ''){
 
echo $extraFooter;
 
}
 
echo '&lt;/p&gt;';
 
if($_SESSION['lang'] == 'es'){
 
echo 'Spanish bottom links';
 
}else if($_SESSION['lang'] == 'en'){
 
echo 'English bottom links';
 
}
 
echo '&lt;/div&gt;';
 
echo '&lt;/div&gt;&lt;!-- end .footer  --&gt;';
 
include('lib/content/core/analytics.htm'); //google analytics code
 
if($extraScripts!==''){
 
echo $extraScripts;
 
}
 
echo '&lt;/body&gt;&lt;/html&gt;';
 
}
 
};
 
?&gt;

So now the session class:

//proc all page display
include('lib/content/lang.php'); //language detector
include('lib/content/page.php');
$page = new Page;
class Session
{
	var $lang;     	   //Username given on sign-up
	var $url;          //The page url current being viewed
    var $referrer;     //Last recorded site page viewed
 
	/* Class constructor */
   function Session(){
      $this-&gt;time = time();
      $this-&gt;startSession();
   }
 
   function cf($filename){//function to clean a filename string so it is a valid filename
   		$fp = explode('/',$filename);
		$num = count($fp);
		return $fp[$num-1];
	}
 
   /**
    * startSession - Performs all the actions necessary to
    * initialize this session object. Tries to determine if the
    * the user has logged in already, and sets the variables
    * accordingly. Also takes advantage of this page load to
    * update the active visitors tables.
    */
   function startSession(){
   		session_start();   //Tell PHP to start the session
 
		/* Set referrer page */
      if(isset($_SESSION['url'])){
         $this-&gt;referrer = $search = $this-&gt;cf($_SESSION['url']);
      }else{
         $this-&gt;referrer = "/";
      }
 
      /* Set current url */
      $this-&gt;url = $_SESSION['url'] = $this-&gt;cf($_SERVER['PHP_SELF']);
 
	  /* Set user-determined language: */
	  	//set up languages array:
		  $langs = array('en','es');
		//
	  if(isset($_GET['lang'])){
	  	if(in_array($_GET['lang'],$langs)){
			$this-&gt;lang =  $_SESSION['lang'] = $_GET['lang'];
		}
	  }
	  if(!isset($_SESSION['lang']) || !in_array($_SESSION['lang'],$langs)){
	  	  $this-&gt;lang = $_SESSION['lang'] = language();
	  }
	}
};
/**
 * Initialize session object
 */
$session = new Session;
 
?&gt;

Well so those are the classes used to format page display. I think they are pretty self-explanatory but if you have any doubt about their usage, comment it.

Using it:

So once you have all set up create a new php file in the root "/". I'll name it "test.php". This file is the generator of the test page. What you need now is a folder inside "lib/content/" with the language code of the language used. I have two, one with "es" and another one with "en", for spanish and english respectively.

To change languages, put a link with this: <a href="?lang=((New lang code here))">Change language to...</a>

Now paste the following code in there:

$title['es'] = 'Bienvenido a la pagina de prueba';
$title['en'] = 'Welcome to the test page';
$page-&gt;genTop($title[$_SESSION['lang']]);
$page-&gt;genContent();
$page-&gt;genBottom();
?&gt;

What this does is it first includes the session.php, with the object initializers. Then it creates an array with the different titles, one for each language offered. Then it calls the object "page" to create the page, in three steps. Top, content, and footer.

The content is retrieved from the appropriate folder ("en" for english, "es" for spanish, and so on ...), by including a file called exactly the same as the generator file, so in this case ("test.php"), supposing you are browsing the english version, it will include the file "lib/content/en/test.php" which should contain plain html like the following:

 
<h2>This is a test page</h2>
 
This is some content...

And this is it!

Download example (zip):

Here you can download a zip with all files for example purposes:

Pack with all necessary files (Zip package)

File structure of the zip:

  • lib
    • content
      • page.php
      • session.php
      • lang.php
      • otherLangs.php
      • core
        • doctype.htm
        • metatags.htm
        • Other .htm files needed
      • en
        • test.php
      • es
        • test.php
  • test.php

The otherLangs.php contains an array with all possible language codes, so if you don't know a language code you can check it there.

The lang.php file contains a function used to check the user preferred language, you can probably understand how it works by looking at it.

Go to Top