Browse Author: sonal.raut

Display Facebook likes / Shares PHP function

The Code
Below is a super simple function that retrieves a JSON feed of comments, likes and shares for any URL you provide.

function facebook_shares($url){

$fql = “SELECT url, normalized_url, share_count, like_count, comment_count, “;
$fql .= “total_count, commentsbox_count, comments_fbid, click_count FROM “;
$fql .= “link_stat WHERE url = ‘”.$url.”‘”;

return json_decode($fb_json);


How to use

$fb = facebook_shares(‘’);

// facebook share count
echo $fb[0]->share_count;

// facebook like count
echo $fb[0]->like_count;

// facebook comment count
echo $fb[0]->comment_count;

Show Google Plus’s – PHP function

It’s worth pointing out you must have CURL enabled on your web server, I believe it’s enabled by default on PHP5 setups. Also the Key below Isn’t a unique API key you must leave the key as is to ensure the code works properly.

function gplus_shares($url){

// G+ DATA
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, “”);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, ‘[{“method”:”pos.plusones.get”,”id”:”p”,
“params”:{“nolog”:true,”id”:”‘ . $url . ‘”,”source”:”widget”,”userId”:”@viewer”,”groupId”:”@self”},
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-type: application/json’));

$result = curl_exec ($ch);
curl_close ($ch);
return json_decode($result, true);


Example Usage

$gplus = gplus_shares(‘’);

echo $gplus[0][‘result’][‘metadata’][‘globalCounts’][‘count’];

Create Secure Scripts with PHP Programming

Believe it or not, there is no such thing as a secure program or application, not even with all the firewalls and encryption added in it. Vulnerabilities are already present even when the program or application is still being coded by the programmer, and there is no way for a programmer to eliminate these vulnerabilities. What he or she can do is to minimize the occurrences of these vulnerabilities, which adds more security to the application or program. With programming scripts like PHP, you can also do other things that can enhance the security of both the program and its coding syntax.

The most popular programming language used by almost every programmer is PHP. It is a mortal sin in the programming world if you do not know what PHP is, or even know the basics of it. PHP is commonly used for developing web applications, yet it is not without its own security holes. These holes can actually hinder any programmer from completing the program because they need to fill it out first before continuing. In this article, I will tell you how to avoid common security pitfalls and glitches in PHP programming.

1 Proper reporting is a must – when you’re developing something using PHP, application reporting is your best friend. These error reports are important, especially when it comes to detecting wrongly spelled variables and incorrect function usage amongst many others. However, it is important to disable or hide application or error reporting once your site goes live because your users will know what’s wrong with your program instantly.

2 Disable bad features – Most developers tried to include applications that made development a lot easier. These applications have unwanted consequences like creating data validation and allowing bugs to find their way into the script. Before your site goes live, make sure you disable any of the features that would create potential errors.

3 Be vigilant of XSS attacks in user input – XSS or Cross Site Scripting is mostly seen on forums. When you are creating the option of writing input via HTML, you are allowing users to run JavaScript outside its intended purpose. When this happens, JS can create holes within your script, which will then turn off the security for the cookies. It’s like turning off the electricity in your electric fence. Once the cookies are exposed, real time data can be gathered by hackers and use this for malicious intent.

There’s no such thing as a perfect software, web application, or programming language, but you can always create something close to perfection.


The PHP scripting language has become popular and it was designed specifically for producing web pages. Many web design company Sydney use PHP as the implementation language because it allows them to build a dynamically-generated web page quickly and easily. It gives you the option to create a PHP template that you can use to create and design your website faster. Here are steps on how to design your website using PHP code easily:

Step 1: Start by creating a folder. Inside the folder, create two new files: index.html and style.css.

Step 2: inside the folder, create two additional folders: the first one should be named “includes” and the second folder “variables”.

Step 3: Open the index.html file using your favorite html editor and start creating your basic html website.

Step 4: Open the .css file and add the div you will be using. Use your own styling in creating your website to suit your needs.

Step 5: Create some more files to be used when we start converting the template to PHP. Open the folder with the name “variables”, then create a blank file called variables.php. Go to the “includes” folder created earlier and add the following files: header.php, nav.php, sidebar.php, and footer.php.

Step 6: Add content to the index.html file.

Step 7: Convert the template to PHP. Take a brief look at the html code and decide which areas will be sliced.

Step 8: After slicing the html code, place the code in the proper PHP files created.

Step 9: Do the sidebar. Copy and cut the sidebar div and place it into the sidebar.php file created located inside the “includes” folder. Do the same thing in the footer area.

Step 10: Once our index.html are completely and properly sliced, rename it to index.php. This will now become your template, as long as the PHP includes are on any page you only have to modify the one single file to make it visible across the entire website. With this, there’s no need

Detect User Language With PHP

This function uses php server variables to detect the “possible” language of the browser of the connected user. This let you show information with the correct language.
Since the HTTP_ACCEPT_LANGUAGE variable contains many information there is some dirty job to do with regular expression to clean the variable and determine the most important value from the ones contained.
The HTTP_ACCEPT_LANGUAGE contains language and q factor. This “q factor” indicates the importance of the language. The bigger is q factor the most important is the language, so the function split the variable, detect q factor and sort to extract the most important.

function getUserLanguage() {
$langs = array();
// break up string into pieces (languages and q factors)
if (count($lang_parse[1])) {
// create a list like “en” => 0.8
$langs = array_combine($lang_parse[1], $lang_parse[4]);
// set default to 1 for any without q factor
foreach ($langs as $lang => $val) {
if ($val === ”) $langs[$lang] = 1;
// sort list based on value
arsort($langs, SORT_NUMERIC);
//extract most important (first)
foreach ($langs as $lang => $val) { break; }
//if complex language simplify it
if (stristr($lang,”-“)) {$tmp = explode(“-“,$lang); $lang = $tmp[0]; }
return $lang;

Web Services and PHP – SOAP vs XML-RPC vs REST

What is web services?

In a typical web surfing scenario, a visitor visits a website and use the functionality provided by that particular website.HTTP request is send to server from web browsers and server responses are translated by browser to display the desired result of the visitor. But, this scenario has been changed in the recent days. You don’t need to visit the particular website to use their service and functionality if they are providing web services. Web services are set of platform independent exposed APIs(functions) which can be used used from remote server over the Internet. There are basically two parties involved in this, one which provides a set of exposed APIs and the another one ,commonly know as web services consumers,is the party which uses the functionality and services provided by web services providing party.

There are different method for providing web services but the most common are SOAPXML-RPC and REST .


SOAP was the acronym of Simple Object Access Protocal but this acronym was dropped in the version of 1.2 of SOAP. It is method for exchanging XML based message over the Internet for providing and consuming web services. SOAP message are transferred forming the SOAP-Envelope.You can view the typical SOAP Message articture from here. SOAP is widely criticized for it’s design complexity.

In PHP 5, there is built-in extension for the providing and consuming web services. But, I personally prefer Nusoap toolkit of PHP for providing and consuming web services using SOAP in PHP.


XML-RPC (remote procedure call) another way of providing and consuming web services. It uses XML to encode and decode the remote procedure call along with it’s parameter. Compared to the articture of SOAP, it has simpler architecture. You can even define data type of parameters of procedure in XML-RPC. You can visit the official website to know more about XML-RPC.

In PHP, there is extension which contain various functions for facilating XML-RPC request and response. But the functions xmlrpc_encode_request() and xmlrpc_decode_request() available in PHP is very useful for when it comes to encode and decode XML-RPC request and response.


Representational State Trasfer(REST) is comparatively simpler method for providing and consuming web services. Nowadays, this method is becoming popular in the arena of web services. Unlike above two method, it is not necessary to use XML as a data interchange format in REST. REST architecture is basically focused on two things : Resources and Interface. RESTful is another term to define REST web services .

Resources are application’s state and functionality which is represented by a unique URL. The resources share a uniform interface to transfer the state between the client and server.

For example the URL, can be a resource.Suppose, GET method is used to retrieve product detail from that URL, POST method is used to modify the production information and DELETE method can be used to delete the product from the same URL. Here, the HTTP methods works as a interface to access the resources.

Talking about PHP, the format of information(representation) returned can be in XML, JSON or even in HTML format. DOM functions, SimpleXML functions and JSON functions comes handy when you are handling RESTful interfaces in PHP.

How to run cronjobs per second in php?

To run cronjob per second you have to execute crontab/cronjob per minute and then have to run task in cron file per second using PHP function time_sleep_until().


$start = microtime(true);



/// here is the tasks which need to run per second…


time_sleep_until($start + $ii + 1);
} // end for

if (!function_exists(‘time_sleep_until’))
function time_sleep_until($future)
if ($future < time())
trigger_error(“Time in past”, E_USER_WARNING);
return false;

usleep(($future – microtime(1))*1000000);
return true;


PHP Debug Log – Trace Errors

“Debug Log” is good sort of tool for monitoring programs.

Trouble shooting is quite simple with Log Files. Log file can be used with analysis tools, it’s possible to get a good idea of where errors are coming from, how often errors return.

Here you can see a simple PHP script to trace PHP programs…


function debugLog($log, $text)
$log_dir = dirname($log);
if( !file_exists($log_dir) or !is_dir($log_dir) or !is_writable($log_dir) )
return false;

$write_mode = ‘w’;
if( file_exists($log) && is_file($log) && is_writable($log) )
$write_mode = ‘a’;

if( !$handle = fopen($log, $write_mode) )
return false;

if( fwrite($handle, $text. “n”) == FALSE )
return false;


Debugging Tools:

Web Services with SOAP in PHP

The SOAP and XML-RPC extensions are packaged with the PHP 5 installation. The SOAP extension and the XML-RPC extension are not enabled by default in a PHP installation. To enable the SOAP and XML-RPC extensions add the following extension directives in the php.ini configuration file.


Restart the Apache server to activate the SOAP and XML-RPC extensions.

ini_set( ‘soap.wsdl_cache_enable’ , 0 );
ini_set( ‘soap.wsdl_cache_ttl’ , 0 );

$client = new SoapClient( ‘stockquote.wsdl’,
‘trace’         => 1,
‘exceptions’   => 1,
‘style’         => SOAP_DOCUMENT,
‘use’         => SOAP_LITERAL,
‘soap_version’   => SOAP_1_1,
‘encoding’      => ‘UTF-8’

echo $client->getQuote( ‘nano’ ); //92.32



$quotes = array( ‘nano’ => 92.32 );

function getQuote( $symbol ){
global $quotes;
return $quotes[ $symbol ];

ini_set( ‘soap.wsdl_cache_enable’ , 0 );
ini_set( ‘soap.wsdl_cache_ttl’ , 0 );

$server   = new SoapServer(
‘exceptions’   => 1,
‘style’         => SOAP_DOCUMENT,
‘use’         => SOAP_LITERAL,
‘soap_version’   => SOAP_1_2,
‘encoding’      => ‘UTF-8’

$server->addFunction( ‘getQuote’ );

<?xml version =”1.0″ encoding =”UTF-8″ ?>

<xsd:schema targetNamespace=”urn:StockQuote”>
<xsd:element name=”symbol” type=”xsd:string” />
<xsd:element name=”Result” type=”xsd:float” />

<wsdl:message name=”getQuoteRequest”>
<wsdl:part element=”tns:symbol” name=”symbol” />
<wsdl:message name=”getQuoteResponse”>
<wsdl:part element=”tns:Result” name=”Result” />

<wsdl:portType name=”StockQuotePortType”>
<wsdl:operation name=”getQuote”>
<wsdl:input message=”tns:getQuoteRequest” />
<wsdl:output message=”tns:getQuoteResponse” />

<wsdl:binding name=”StockQuoteBinding” type=”tns:StockQuotePortType”>
<soap:binding style=”document” transport=”” />
<wsdl:operation name=”getQuote”>
<soap:operation soapAction=”urn:StockQuote/getQuote” />
<soap:body use=”literal” />
<soap:body use=”literal” />

<wsdl:service name=”StockQuoteService”>
<wsdl:port name=”StockQuotePort” binding=”tns:StockQuoteBinding”>
<soap:address location=”http://localhost/WebServices/SOAP_EXTENSION/StockQuote/Server1.php” />

Salesforce form integration (web-to-lead) with PHP and cURL

In the example below I am only showing the basic process. I am leaving out the validation code for the fields and any submission code to MySQL database.

One security advantage of this process is hiding your organisation id within a variable in the submission page rather than on the live page with the form.

// SF Org Id.
$oid = "0113543434646";

I first check if cURL is enabled before processing any further.

// Make sure cURL is enabled
if (!function_exists('curl_init')) {
	error("Curl is not setup on this PHP server and is
    required for this script");

I then loop through all the data input from the form. I first check there is data there (twice). Then I loop through each POST data using a foreach. Within the foreach loop I run stripslashes()function to stop the backslashes getting added twice. I don’t do any other form of validation as the data is going to Salesforce and I rely on them checking the data. At the end I add the organisation to the array.

if (isset($_POST)) {

if (count($_POST) == 0) exit("Error.  No data was passed
     to this script.");

// variable to hold cleaned up a version of $_POST data
$cleanPOST = array();	

// Loop through the $_POST data and process it
foreach ($_POST as $key=>$value){
 $cleanPOST[stripslashes($key)] = stripslashes($value);

// Add the Org ID
$cleanPOST["oid"] = $oid;

} else {
 exit("Error.  No data was passed to this script.");

Once the POST data is in an array we can send it to Salesforce. I have commented each step below. I add a return URL to the data sent which then redirects the user to that URL. You could do the redirect in the PHP file itself.

// Create a new cURL resource
$ch = curl_init();	

if (curl_error($ch) != "") {
    echo "Error: $errorn";

// Point to the Salesforce Web to Lead page
curl_setopt($ch, CURLOPT_URL,

// Set the method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Pass POST data
$ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));

curl_exec($ch); // Post to Salesforce
curl_close($ch); // close cURL resource

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box