How to get image height and width dynamically using PHP?

Hello friends,

In last week while performing my task I had a requirement to get image height and width dynamically with PHP programming. To satisfy that requirement I had searched the web and found the optimum way to do so, that I want to discuss here.

PHP provides an inbuilt function named getimagesize() to get the size of an image.

The getimagesize() function accepts one argument i.e. image path and returns an array with 7 elements.


array getimagesize (string $filepath)

The returning array consist dimensions of given image file along with the file type.

Index 0 and 1 indicates the width and height of the image respectively.

Index 2 is the constant indicating the type of the image.

Index 3 is a text string with the height=”yyyy” width=”xxxx” string.

The last argument mime is the correspondent MIME type of an image.

Hope this will help you.

Thanks.

Pass PHP array as argument to JavaScript function

We all know that, we widely use JavaScript in our PHP page to perform some task. Those tasks could be either any small calculation or anything else. We know that we use array in PHP for our tasks. Some time it’s a requirement to use PHP array into JavaScript function. So I write this blog to fulfill that requirement.

There are two ways to pass the PHP array to JavaScript function as arguments. I have explained both of them here.

Method 1: USE JSON_ENCODE

First method is to convert the PHP array into JSON_ENCODE so that function that receives that array use as a JavaScript array. Complete example is given as follows:

<script type="text/javascript">
function displayarrayelement(demoarray)
{
	for(i=0;i< demoarray.length;i++) 
	{
alert(demoarray [i]); 
}
}
</script>
<?php
	$newarray = array();
	For($i = 10; $i<100; $i=$i+10)
	{
		$newarray [] = $i;
	}
?>
<a onclick="displayarrayelement(<?php echo json_encode($newarray) ?>);"> Array in JavaScript </a>

Method 2: Manually make PHP array like JavaScript array (use implode and split)

In Second method, we make the PHP array format like the JavaScript array manually. So the function direct use that array. Complete example is given as follows:

<script type="text/javascript">
function displayarrayelement(demoarray)
{
	demoarray = demoarray.split(",");
	for(var i=0;i<demoarray.length;i++) 
	{
		alert(demoarray [i]); 
	}
}
</script>
<?php
	$newarray = array('a','b','c');
	$mov_str = implode(",", $newarray);
?>
<a href="#" onclick="displayarrayelement('<?php echo $mov_str ?>');"> Array in JavaScript </a>

Hope this will help you as it did to me.
Thanks.

Get social media activity count of url using php

Hello Friends,

We all know that we widely used social media for the marketing of our different thinks over the world. So we get the information about what status of our thinks. The status means information in the form people like’s, share, comment’s etc.

For that I post this blog to get complete information of the URL from following social media.

  1. Facebook.
  2. Twitter.
  3. Linkedin.
  4. Google Plus (G-Plus).

There are following ways to get information from site.

Method-1: Code for getting like’s of particular URL from face-book, twitter and Google plus.  


<?php

$url = 'http://www.indieswebs.com/';

$json = file_get_contents("http://api.sharedcount.com/?url=" . rawurlencode($url));

$counts = json_decode($json, true);

echo "This page has " . $counts["Twitter"] ." tweets, " . $counts["Facebook"]["like_count"] . " likes, and ". $counts["GooglePlusOne"] . "+1's";

?>

Method-2: Code for getting activities of particular URL from face-book, twitter, Google plus and LinkedIn. 


<?php

//Get Number of Tweets from Twitter

function get_tweets($url)

{

$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);

$json = json_decode($json_string, true);

return intval( $json['count'] );

}

//Get Number of LinkedIn Shares

function get_shares($url)

{

$json_string = file_get_contents("http://www.linkedin.com/countserv/count/share?url=$url&format=json");

$json = json_decode($json_string, true);

return intval( $json['count'] );

}

//Get Number of Facebook Shares/Like/Comment/Click

function get_likes($url)

{

$json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);

$json = json_decode($json_string, true);

return intval( $json[$url]['shares'] );

}

//Get Number of Google+1′s

function get_plusones($url)

{

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");

curl_setopt($curl, CURLOPT_POST, 1);

curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$curl_results = curl_exec ($curl);

curl_close ($curl);

$json = json_decode($curl_results, true);

return intval( $json[0]['result']['metadata']['globalCounts']['count'] );

}

$facecount = get_likes('http://www.indieswebs.com/');

echo "<br />The Answer For Facebook".$facecount;

$linkdinshare = get_shares('http://www.indieswebs.com/');

echo "<br />The Answer For LINKDIN".$linkdinshare;

$tweetcount = get_tweets('http://www.indieswebs.com/');

echo "<br />The Answer For Tweet".$tweetcount;

$gpcount = get_plusones('http://www.indieswebs.com/');

echo "<br />The Answer For Google".$gpcount;

?>

I Hope this will help you

Thank you

PHP: Code to download a file

Hello friends,
In last week I had a requirement to give links of files to user. And if user will click on that file’s link then that file will be downloaded to his/her PC.
To satisfy the above requirement I had searched the web and found many solutions for that. But our site is in PHP language, so all the solutions were not valid for me. Where at last I found a good PHP code to download a file and here I want to share that code with you people.
Now to implement download file facility using PHP code follow the under given steps.
Step 1: Copy and paste under given code in your PHP file.

$filepath = 'Give full path of your file';
$filename = 'Give file name'.
ob_end_clean();
header('MIME-Version: 1.0');
header('Pragma: ');
header('Cache-Control: public');
header('Content-length: '.filesize($filepath));
header('Content-type: '.mime_content_type($filepath));
header('Content-transfer-encoding: 8bit');
header('Content-disposition: attachment; filename="'.$filename.'"');
$handle = fopen($filepath, 'rb');

if ($handle)
{
	while (!feof($handle)) {
		print fread($handle, 8192);
	}
	fclose($handle);
}
flush();

Step 2: On first line replace the ‘Give full path of your file’ with full path of your file which you want to download.
Step 3: On second line replace the ‘Give file name’ with file name of your file which you want to download.
Step 4: Save the file and execute it.
Hope this will help you.
Thanks.

MYSQL: Solve the error related to SQL_BIG_SELECTS

Hello friends,
In our site we had a PHP script page which executes a MYSQL database query to fetch records and display report.
That page worked fine for few months, but since last few days it started giving an error message:

The SELECT would examine too many records and probably take a very long time. Check your WHERE and use SET OPTION SQL_BIG_SELECTS=1 if the SELECT is ok

Now to solve the above error I searched the web and found a proper solution, which I would like to discuss here.
The error had occurred because in our MYSQL server SQL_BIG_SELECTS variable was turned off.
Some basic information about SQL_BIG_SELECTS variable is as under:
1. SQL_BIG_SELECTS variable prevents users from accidentally executing unnecessary large queries.
2. MYSQL determines whether or not a query is large based on the value of MAX_JOIN_SIZE variable. If the query is examining more than this number of rows, it will consider it as a big select or a large query. We can execute SHOW VARIABLES command to view values of MYSQL server variables.
3. I believe that indexing and good WHERE clause can prevent this problem.
Now if we want to turn on the SQL_BIG_SELECTS variable then we can do it from my.cnf file or at server startup. But some VPS (Virtual Private Server) servers do not allow us to do that.
So as an alternate solution I executed

mysql_query("SET OPTION SQL_BIG_SELECTS = 1");

query in our PHP script just after the database connection, and it works fine.
The solution works fine. But this could be said a temporary solution, because some servers don’t provide enough permissions. If the sever provides it you can change the my.cnf file or at server startup and implement it permanently.
Otherwise implement the above given solution. It remains in effect during the current database session between our PHP application and the database. So we have to execute above query after each database connection.
Hope this will help you.
Thanks.

Salting Passwords with One way Hash Function

The most common practice for any website or application to check for authentic users is to assign secret keys or passwords to get access to their accounts. Now one way to store these passwords is to directly store them into database. That would be a huge security hole in any server’s database since anyone who can get access to that database can hack into anyone’s account using that password.

A good solution for this loop hole was to provide some kind of encryption. Change the clear text password into such unrecognizable form that it is not possible to determine what the actual password was. Many hashing functions are used to accomplish this task. What they do is they take the password entered by the user and convert it into some unrecognizable form using a one way hashing function(for example MD5). The advantage of using this cryptographic technique is that once you have encoded the password it can’t be decoded back to its original form. So there is no way a hacker would be able to decode the password.

This solution seems quite elegant but wait.. now again a new problem arises. Any site with probably hundreds and thousands of uses will have users with same passwords, right? So there is still a big security threat when such same password user can get access to anyone’s email or username then they can compromise someone’s account. Enter “salting”. Salting a password means you concatenate a random string with the user’s password and THEN encrypt it using a hash function. This way each user will have unique password even if their original password is same!

Let me give a simple illustration. Say there are two users with the password “mypasscode” on a site called example.com. Now example.com uses their email ids as usernames. So if user A (let’s call him Anon) can get his hands on the email address of user B (call him Bnon) then he will be able to access Bnon’s account without his permission. If example.com were to use salting, they will not only encode both the user’s passwords but also use salting technique while saving their passwords. So they will take the password “mypasscode” concatenate it with both their names, “mypasscode:anon”, “mypasscode:bnon” and then encrypt then and store in the database. This way each use gets a unique password no matter what! Here is a small sample code in PHP to implement our little example. When user registers on any site we can use this simple lines to add salting:


<?php
     //get data from the registration form and store in variables
     $user = "anon";
     $pwd = "mypasscode"; //contains the password selected by the new user
     echo $pwd.":".$user;
     $hashpwd = md5 ($pwd.":".$user);
     echo "<br />".$hashpwd;
     //Store $hashpwd in database with the user.
?>

There is no restriction as to what to use as the concatenating string with the passwords. It can be the users’ email addresses, or names as we used in the example or it could be any other random string they wish to use for hashing. But the end result is a very secure user table in your database. Most modern websites use this technique to store passwords. That’s the reason they don’t know your password when you forget it. You just have to reset it yourself they will not send your original password as they don’t know it! If any site sends you your password back then it’s a clear sign that they store your password without proper security measures. So beware of such sites.

Happy Coding 🙂