Posts Tagged PHP

BobbyeM71hxwPHP Development on the Facebook Platform- Build Your App

Wednesday, April 21st, 2010

Facebook API is very powerful and it allows you to create your own Facebook applications, which you, your friends or everyone else can then consume. You can use the Facebook applications you build on profile pages, canvas pages, and so on. You can even make money by developing practical applications. So, let’s get started with creating your own Facebook application.

What You Need-

To create your own Facebook application, you should know how to program in one of the supported languages, such as PHP, Ruby on Rails, or Python. With that knowledge, all you need to do to get started is:
1. Add Facebook Developer Application to your Facebook account.
Go to the Facebook Developers page and click “Add developer.” This is the central location for all your applications on Facebook. You can request as many as 100 API keys from the applications page, as well as manage and change the settings for all your applications. Now that you have added Facebook Developer Application to your account, let’s move on to adding your very first application.

2. Add your first Facebook application.
Go back to the Facebook Developers page and click the Set Up New Application button. This will take you to the “Create Application” page, where you are required to provide the name of your application and, as a rule, agree to certain terms and conditions.
After saving changes to this page, you will be taken to your application’s homepage, which serves as your application’s edit page. You can change all the settings related to your application here, such as its name, description, icon, logo and much more. You can add more developers if you are going to develop the application in a team.
On the same page, Facebook provides you with an API Key and a Secret Key, which are the passports for your application to interact with

Facebook core applications and the outside world. Do not share you secret key with anyone.

Pre-development Changes

To start developing your application, you need to make important changes to the following settings:

  • API Key – This unique key helps Facebook identify whatever request(s) you make. Enclose this API key along with all your requests.
  • Secret Key – As mentioned previously, you should keep this key safe and share it with no one, because it is responsible for authenticating your request.

Now, click on the Authentication tab, where you need to specify:

  • Post-Authorize Callback URL – When a user authorizes your application and adds it to a Facebook account, then Facebook pings this URL. So, this URL needs to be your site’s URL where you application is hosted. This cannot be a URL from Facebook.
  • Post-Authorize Remove URL – When your application is removed by a user, this URL will be pinged along with a post request, which will contain the User_id. This process allows you to log which user has removed your application.

Now click on the canvas tab, where you need to specify:

  • Canvas Page URL – Choose a canvas page URL for Facebook, such as http://apps.facebook.com/your-app-name.
  • Canvas Callback URL – This is the muscle of your application. Facebook pulls the content from this URL and displays it on the application’s canvas page. The URL can be where you have your application hosted.
  • Render Method – You need to selected this option according to your code. If your code is going to have FBML tags, then you should select “FBML” in this option. Otherwise, leave it default as “iframe” (for this example, you can choose either).

These settings should be enough to get you started with your first Facebook application. Undoubtedly, you can make many other changes to suit your needs in due course.

Now that you have set up the application, let’s have a look-see at how to put some muscle on your bare-bones application. In this example, you need to use Facebook’s PHP client library, which is a compressed file. After downloading the client library, extract the files. You will get two folders namely, footprints and php.

Footprints is a sample application provided to help you understand how the Facebook API works. However, because the API functions keep changing, this code might have some deprecated functions. The php folder contains the library files that you will use to talk back to the Facebook API.

Create a file called index.php and copy the following code into it:

<?php
 require_once 'php/facebook.php';
 $appapikey = 'INPUT YOUR APP KEY HERE';
$appsecret = 'INPUT YOUR APP SECRET KEY HERE';
 //create the object
$facebook = new Facebook($appapikey, $appsecret);
 /**
 * Check if we have an already logged in user ?
 * Yes - Skip the require_login
 * No - User is redirected to facebook login page
 */
if(!is_numeric($facebook->get_loggedin_user()) || !$facebook->api_client->users_hasAppPermission("publish_stream"))
  $facebook->require_login($required_permissions = 'publish_stream');
 /**
 * In case user reaches here and our application doesn't have proper permissions to publish,
 * then display this error message
 */
 if(!$facebook->api_client->users_hasAppPermission("publish_stream"))
{
  echo 'Darn !! Something just broke !!' ;
}
 /**
 * Check if we have Post data and a status to update
 */
if($_POST['update_me'] == 1)
{
    $res=$facebook->api_client->stream_publish($_POST['st'],'');
  $uid = $facebook->get_loggedin_user();
   $tmp = explode ("_",$res);
  if($uid == $tmp[0])
  {
    echo "Timeline updated successfully, <a href='http://www.facebook.com/?id=$uid'> Go back to your profile page</a>";
  }
  else
  {
    echo "Couldn't update your status, Please try again";
  }
}
/**
 * Display the form to update status
 */
else
{
  ?>
 
<form method="POST" action="http://www.your_domain.com/index.php" >
  <input value="1"/>
  <textarea></textarea> <br>
  <input value="Update status" />
 </form>
  <?php
}
?>

Important Tasks to Remember

Make sure you complete the following tasks to properly build your application:

  1. Include the library file (facebook.php) and change the path in require_once to match your folder hierarchy.
  2. Copy/paste the API key and secret key before trying to use your application. It won’t work without these anyhow.
  3. Input the canvas page URL right to the path of the script on your server/domain.

When you execute the above script, it will look for logged in users, if any. If a user is not logged in, then it redirects the user to the Facebook login page. This is also handled by the require_login function, but the problem with require_login is that it redirects so often that any post data to your page is lost. So, you have put a check before calling the require_login function. In the same line, you also check whether or not your application has permission to post updates onto a user’s stream. If you do not have permission, the user is prompted to allow your application.

When you have permissions and post data, the status is updated to the user. When a status is successfully posted, a response of the typeuserid_postid is returned. If it fails, then different error codes are returned. Find a list of error codes on Facebook’s wiki page.

You can extend the above code to suit your requirements. If you feel confident, you can move on to write some advanced programs using FBJS and XFBML. Other than that, you should keep abreast of any functions that Facebook deprecates — particularly those that your code might be using. Otherwise, your application might crash all of a sudden.

Tags: , , , , , ,
Posted in Opensource, Purely Technical

BobbyeM71hxwHow to generate readable/remeberable random password?

Saturday, March 27th, 2010

<?php
$randPwd = generatePassword(12);
?>

Fast, simple, and easy way to generate readable/remeberable random password

<?php
//Generates readable/rememberable random password.
function generatePassword($length = 6) {
$chars = array(“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”, “j”, “k”, “l”, “m”, “o”, “p”, “r”, “s”, “t”, “u”, “v”, “x”,”y”, “z”);
$vocals = array(“a”, “e”, “i”, “o”, “u”);
$password = “”;
mt_srand ((double) microtime() * 1000000);
for ($i = 1; $i <= $length; $i++)
$password .= ($i % 2 == 0)?$chars[mt_rand(0, count($chars) – 1)]:$vocals[mt_rand(0,count($vocals) – 1)];
return $password;
}
?>
<?php

//Generates readable/rememberable random password.
function generatePassword($length = 6) {
       $chars = 
        array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "o", "p", "r", "s", "t", "u", "v", "x","y", "z");
       $vocals = array("a", "e", "i", "o", "u");
       $password = "";
       mt_srand ((double) microtime() * 1000000);
       for ($i = 1; $i <= $length; $i++)
           $password .= ($i % 2 == 0)?$chars[mt_rand(0, count($chars) - 1)]:$vocals[mt_rand(0,count($vocals) - 1)];
return $password;
}
?>

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , ,
Posted in Purely Technical

BobbyeM71hxwNew Release: PHP 5.3.2 Released

Monday, March 8th, 2010

PHP 5.3.2 has been released, as the PHP.net site has posted the release announcement for the latest PHP version in the PHP 5.3.x series – 5.3.2.

PHP 5.3.2 is a maintenance release in the 5.3 series, which includes a large number of bug fixes.

Security/bug fixes included in this release take care of things like:

  • Safe_mode validation inside tempnam
  • A possible open_basedir/safe_mode bypass in sessions
  • Added support for SHA-256 and SHA-512 to php’s crypt.
  • Fixed a bug in the garbage collector that could cause a crash
  • Crashing when using ldap_next_reference

Key Bug Fixes in PHP 5.3.2 include:

  • Added protection for $_SESSION from interrupt corruption and improved “session.save_path” check.
  • Fixed bug #51059 (crypt crashes when invalid salt are given).
  • Fixed bug #50940 Custom content-length set incorrectly in Apache sapis.
  • Fixed bug #50847 (strip_tags() removes all tags greater then 1023 bytes long).
  • Fixed bug #50723 (Bug in garbage collector causes crash).
  • Fixed bug #50661 (DOMDocument::loadXML does not allow UTF-16).
  • Fixed bug #50632 (filter_input() does not return default value if the variable does not exist).
  • Fixed bug #50540 (Crash while running ldap_next_reference test cases).
  • Fixed bug #49851 (http wrapper breaks on 1024 char long headers).

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , , , ,
Posted in Technical News

BobbyeM71hxwHow to build a PHP Link Scraper with cURL?

Thursday, March 4th, 2010

Let’s build a robot, which scrapes links from web pages and dumps them in a database, and then it read those links from the database and follows them, scraping up the links on those pages, and so on ad infinitum.

To begin, let’s have a look at the groundwork.

The cURL Component-

cURL (or “client for URLS”) is a command-line tool for getting or sending files using URL syntax. It was first used in 2007 by Daniel Stenberg as a way to transfer files via protocols such as HTTP, FTP, Gopher, and many others, via a command-line interface. Since then, many more contributors has participated in further developing cURL, and the tool is used widely today.

Using cURL with PHP-

PHP is one of the languages that provide full support for cURL. (Find a listing of all the PHP functions you can use for cURL.) Luckily, PHP also enables you to use cURL without invoking the command line, making it much easier to use cURL while the server is executing. The example below demonstrates how to retrieve a page called example.com using cURL and PHP.

<?php
$ch = curl_init(“http://www.example.com/”);
$fp = fopen(“example_homepage.txt”, “w”);
curl_setopt($ch, cURLOPT_FILE, $fp);
curl_setopt($ch, cURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

<?php


$ch = curl_init(“http://www.example.com/”);
$fp = fopen(“example_homepage.txt”, “w”);


curl_setopt($ch, cURLOPT_FILE, $fp);
curl_setopt($ch, cURLOPT_HEADER, 0);


curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

The Link Scraper-

For the link scraper, you will use cURL to get the content of the page you are looking for, and then you will use some DOM to grab the links and insert them into your database. You can build the database from the information below; it is really simple stuff.

$query = mysql_query(“select URL from links where visited != 1);
if($query)
{

 	while($query = mysql_fetch_array($result))
 	{

$target_url = $query[‘url’];
$userAgent = ‘ScraperBot’;

Next, grab the URL from the database table inside a simple while loop.

$ch = curl_init();
curl_setopt($ch, cURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, cURLOPT_URL,$target_url);

After instantiating cURL, you use curl_setopt() to set the USER AGENT in the HTTP_REQUEST, and then tell cURL which page you are hoping to retrieve.

curl_setopt($qw, cURLOPT_FAILONERROR, true);
curl_setopt($qw, cURLOPT_FOLLOWLOCATION, true);
curl_setopt($qw, cURLOPT_AUTOREFERER, true);
curl_setopt($qw, cURLOPT_RETURNTRANSFER,true);
curl_setopt($qw, cURLOPT_TIMEOUT, 20);

You’ve set a few more HEADERS with curl_setopt(). This time, you made sure that when an error occurs the script will return a failed result, and you set the timeout of each page followed to 20 seconds. Usually, a standard server will time-out at 30 seconds, but if you run this from your localhost you should be able to set up a no-timeout server.

$html= curl_exec($qw);
if (!$html)
{

 	echo "ERROR NUMBER: ".curl_errno($ch);
 	echo "ERROR: ".curl_error($ch);
 	exit;

}

Grab the actual page by sending the HEADERS along while executing the cURL request using curl_exec(). If an error occurs, it will be reported to PHP by the number and description inside curl_errno() and curl_error, respectively. Obviously, if such an error exists, you exit the script.

$dom = new DOMDocument();
@$dom->loadHTML($html);

Next, you create a document model of your HTML (that you grabbed from the remote server) and set it up as a DOM object.

$xpath = new DOMXPath($dom);
$href = $xpath->evaluate(“/html/body//a”);

Use XPATH to grab all the links on the page.

for ($i = 0; $i < $href->length; $i++) {

 	$data = $href->item($i);
        $url = $data->getAttribute('href');
 	$query = "INSERT INTO links (url, gathered_from) VALUES ('$url', '$gathered_from')";
 	mysql_query($query) or die('Error, insert query failed');
        echo "Successful Link Harvest: ".$url;
 	}

}

Dump all the links into the database, as well as the URL they are gathered from, just so you never go back there again. A more intelligent system might have a separate table for URLs already visited, as well as a normalized relationship between the two.

Going a step further than just grabbing the links enables you to harvest images or entire HTML documents as well. This is kind of where you start when building a search engine. Creating your own search engine may seem naively ambitious, and this little bit of code may inspire you a bit.

Source:- http://www.developer.com

http://www.all1social.com

http://www.all1martpro.com

Tags: , , , , ,
Posted in Editorial, Expert's Opinions, Purely Technical

BobbyeM71hxwPHP 5.2.13 Release Announcement

Wednesday, March 3rd, 2010

PHP 5.2.13 has been released, focusing on improving the stability of the PHP 5.2.x branch with over 40 bug fixes, some of which are security related.

All users of PHP 5.2 are recommended to upgrade to this release.

Security Enhancements and Fixes in PHP 5.2.13:

  • Fixed safe mode validation inside tempnam() when the directory path does not end with a /). (Martin Jansen)
  • Fixed a possible open_basedir/safe_mode bypass in the session extension identified by Grzegorz Stachowiak. (Ilia)
  • Improved LCG entropy. (Rasmus, Samy Kamkar)

Key enhancements in PHP 5.2.13 include:

  • Fixed bug #50940 Custom content-length set incorrectly in Apache sapis.
  • Fixed bug #50847 (strip_tags() removes all tags greater then 1023 bytes long).
  • Fixed bug #50661 (DOMDocument::loadXML does not allow UTF-16).
  • Fixed bug #50632 (filter_input() does not return default value if the variable does not exist).
  • Fixed bug #50540 (Crash while running ldap_next_reference test cases).
  • Fixed bug #49851 (http wrapper breaks on 1024 char long headers).

http://get-a-designer.com
http://www.all1sourcetech.com

Tags: , , , ,
Posted in New Product Release, Purely Technical

BobbyeM71hxwWordPress Plugin-Tweelow Plugin 1.1

Tuesday, March 2nd, 2010

Tweelow Plugin1.1, the plugin will show the number of Twitter followers anywhere on the WP blog. It will connect to the Twitter API and retrieve all the necessary data.

Installation: Unpack and upload it to the /wp-content/plugins/ directory. Activate the plugin through the ‘Plugins’ menu in WordPress.

Requirements: • WordPress 2.7 or higher

New in this release:-

• Plugin works with database now
• Plugin will get the latest data if you used API limit
• Now you can manage what to write After and Before status and counter
• Bugged versions are not downloadable anymore

Language: php

Tags: , , , ,
Posted in New Product Release, Technical News

BobbyeM71hxwNew Plugin- WP-Status.net 1.0

Tuesday, March 2nd, 2010

WP-Status.net 1.0, the WordPress plugin will push a status update to the Status.net servers and the specified Twitter accounts each time a new blog post is published.

It supports an unlimited number of accounts on an unlimited number of servers. The plugin can be configured to post to different accounts on the same Status.net server.

The links to the blog can be shortened via one of seven different URL shortening services.

Installation: Unpack and upload it to the /wp-content/plugins/ directory.
Activate the plugin through the ‘Plugins’ menu in WordPress.
Requirements: WordPress 2.7.0 or higher

Language: PHP

Tags: , , ,
Posted in New Product Release, Purely Technical

LolaTheriot[PHP]Sending MySQL data.

Saturday, February 27th, 2010
<?Php
$db_host = "1.3.3.7"; // mySQL database host
$db_user = "dbplz"; // mySQL database user
$db_password = "rofl"; // mySQL database password
$db_name = "dbplz"; // the name of your mySQL database

//connect to our database.
  mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
// Select the database.
  mysql_select_db($db_name) or die(mysql_error());
//Define the data as $query
$query = "INSERT INTO tablename (row1, row2, row3, row4)
VALUES ('$variable1','$variable2','$variable3','$variable4')";
  mysql_query($query);
  mysql_close();

// it's almost always imperative to strip tags or the data usually doesn't send properly.
$variable = strip_tags($_POST['variable'], '');
//and now send the data
  mysql_query($query);
  mysql_close();
?>

http://www.all1martpro.com

http://www.all1sourcetech.com

Tags: , , , ,
Posted in Editorial, Purely Technical

LolaTheriotHTML Tools: Haml 2.3.0

Friday, February 26th, 2010

Haml 2.3.0 is a markup language, which is used to describe the HTML of any web document easily and simply, without the use of inline code.

It is compiled into XHTML, similarly to ERB, and attempts to fix many flaws in templating engines like explicitly coding HTML into the template.

Haml itself is a description of the HTML, with code to generate dynamic content. And it functions as a replacement for inline page templating systems such as PHP, ASP, and ERB.

Example:
The #foo Hello World! line of code will output this HTML line of code: <div id=”foo”>Helo World!</div>

Automatically, Haml handled the end tag and tag defining. For CSS stylings, SASS does the same thing as Haml does for HTML. SASS is bundled with Haml by default.

Platform: Windows/ Linux/ Mac OS/ BSD/ Solaris
Language: Ruby

http://www.all1martpro.com

http://www.all1sourcetech.com

Tags: , , , , , ,
Posted in Purely Technical

LolaTheriotDell plans new line of ‘private cloud’ servers this year

Tuesday, February 9th, 2010

Dell is planning to take some of the custom servers designed by its Data Center Solutions division for Web giants like Yahoo and Facebook and sell them to a wider range of companies, including large enterprises, according to Dell executives.

About three years ago, the DCS unit was formed to help Dell get more business from large Internet firms. Its engineers often spend several weeks on-site with those companies to design low-cost, low-power systems that meet the special requirements of their search, social networking and other Web applications.

In an interview, Dell executives said that hands-on role means the DCS group designs servers only for large companies, such as Ask.com and Microsoft’s Azure division, which order tens of thousands of servers per year, but that’s about to change.

Dell will turn some of those custom servers into standardized products and sell them to companies that order lower volumes of systems later this year, including enterprises building “private cloud” environments in their data centers, and a second tier of smaller Internet companies. They will likely be sold under a new brand, CloudEdge.

Andy Rhodes, a director with Dell’s DCS group, said “What we’ve found is, there are a whole bunch of other customers who want access to those designs but who are not buying in those types of quantities”. “So the big thing we’re solving now, and we’ll talk more publicly about over the next couple of months, is how to provide more of that capability to many, many more customers.”

Dell isn’t discussing specific products yet and is still working out details, such as whether the servers will be sold by DCS or through Dell’s standard server channels. But the goal is to offer the designs to a wider market, even while DCS continues to do custom work for very large customers..

DCS aims to build highly energy-efficient servers that pack a lot of computing power into a small space. The systems often forego redundant power supplies and fans, for example, which saves on component costs and energy bills.

That also makes the servers less resilient to failure — a trade-off large Internet companies are willing to make for lower operational costs. Companies like Google and Yahoo design their Web applications to run on such “fail in place” architectures, so that workloads are rerouted around failed servers with little or no disruption to services.

According to Barton George, cloud evangelist for Dell, the main thing with these hyperscale systems is that the availability and resiliency are baked into the customers’ applications rather than into the hardware.

Tags: , , , , , , , , , , ,
Posted in Opensource, Technical News