Archives for category —php

Weather forecast script in php using Google Weather API

A few days back , we published an article about currency conversion using Google calculator API and php. Today we are going to show you how to display current weather information and forecast data using php and Google Weather API.
The API is situated at http://www.google.com/ig/api?weather and the callback URL for a specific place looks like this :

www.google.com/ig/api?weather=PlaceName&hl=en

The returned data in XML form contains information such as current temperature , weather condition , humidity , winds and forecast for the next few days. Continue Reading

Currency conversion using php and Google calculator api

Google is a wonderful ! While most of us use it for searching the web for information , few are aware that it has an inbuilt calculator which can also be used for converting a currency into another . Doing so is really simple , you just type ” AMOUNT CURRENCY_CONVERTING_FROM in CURRENCY_CONVERTING_TO ” and search , the inbuilt calculator will give you the result .For example , if one wants to convert 1 U.S Dollar into Euro , he shall type “1 USD in EUR” .

Now lets get to the topic of this post , Google also has a secret calculator API ( http://www.google.com/ig/calculator ) that is usually used for iGoogle gadgets , but since its free and open , anyone can use it .
Continue Reading

30+ Best Practices for PHP Beginners : Nettuts+

Nettuts+ recently published a very nice article summarising “30+ Best Practices for PHP Beginners” . The article is a must read for all PHP beginners. Check out the article here :
http://net.tutsplus.com/tutorials/php/30-php-best-practices-for-beginners/

How to know what keywords visitors Googled to reach your site?

Here is a simple php script that will detect if your visitor is coming from Google and then log the keyword used to reach your site to a file. The script logs the visitors ip address along with the keyword and exact date and time to a file in the form x.x.x.x googled for “key word here” on Month Date, Year, at Hours:minutes am/pm. To use the script, just paste the following code into your php pages , and set the variable $log_file appropriately.
Here is the code :

<?php

/* JUST A FEW SETTINGS FIRST
The log file name,
this is where the key words will be stored,
make sure to keep a difficult-to-guess name
for privacy reasons
*/

 
$log_file="google-keywords-log.log";

/*
 Set your timezone (just to make sure you can analyze the data better)
 Some useful time zone values :
 Asia/Karachi
 Asia/Dacca
 Asia/Qatar
 Asia/Muscat
 Asia/Tokyo
 for a complete list, refer to http://www.php.net/manual/en/timezones.php
*/

date_default_timezone_set("Asia/Calcutta");

// THE CODE
if (strpos($_SERVER[‘HTTP_REFERER’],‘http://google’) OR strpos($_SERVER[‘HTTP_REFERER’],‘http://www.google’)) {
$referer=$_SERVER[‘HTTP_REFERER’];
$url=parse_url($referer);
parse_str($url["query"],$query);
$data=$_SERVER[‘REMOTE_ADDR’]." googled for \"".$query["q"]."\" on ".date("F j, Y,")." at ".date("g:i a")."\r\n\r\n";
$fp=fopen($log_file,"a+");
fwrite($fp,$data);
fclose($fp);

}
?>

Code Explained

We first check to see if our visitor has been refered to our site by google by checking the predefined variable $_SERVER["HTTP_REFERER"] for occurences of the string http://www.google or http://google using the strpos() function. Then we parse the referer url using parse_url() function. Then we go on to parse the “query” component of the array returned by parse_url() using the parse_str() function which parses the strings as if it were the query string passed via a URL and sets variables in the current scope. Once the string is parsed into the array $query , we can access our keyword term at $query["q"] .Finally we open our log file (set in $log_file ) in the append mode (a+) and append the visitors IP adress, the keyword and date and time to the file.

Sniffing Googlebot using php

Ever wanted to know when Googlebot (google’s search engine spider) visits your site? . Googlebot can be sniffed (detected) easily using php. It is identifiable by the “Googlebot” string in the HTTP_USER_AGENT field it sends with the headers. Here is a simple function called is_google() which returns TRUE if the visitor is Googlebot, else FALSE.

//The function
function is_google() {
if (strpos($_SERVER[‘HTTP_USER_AGENT’],"Googlebot"))
 return true
else
 return false
}

Usage

To use the function, just call it using an if statement, here is how :

if (is_google())
{
 //do something here if the visitor is Googlebot
//like log the date and time to a file/database
}

Some common uses of this function can be :

  • Analyzing the visit of Googlebot to your sites
  • Spamdexing,Cloaking ( deceiving )
    serving different content (like bulk of links,high ranking keywords etc…) to Googlebot for better rankings
NOTE
Using this function for cloaking and spamdexing is a black hat SEO technique and can cause your site to be blacklisted by Google

Parsing “ini” configuration files using php


Many times during development involving php, one would want to store some variables as settings. The most common way developers do this is by defining those variables at the beginning of the script. For example, while writing a contact form script, I would like to define a few handy variables first, including admin email, contact log file name/path and etc… The most common way to do this would be to write something similar in your php script.

/******* S E T T I N G S *********/
$admin_email="you@yourdomain.com";
$file="logs/contact.log";
$success_msg="Thanks! your submission was recieved, we will get back to you soon!";
/****** E N D ****************/

Read the rest of the article on Devils Workshop

Wordpress – How to display featured posts in your theme

“Featured Posts” are a key feature of any news/journal wordpress site. It is pretty easy to develop a wordpress theme to display a fixed number of featured posts from a specific category on the homepage. It can be done using the query_posts() function of wordpress. Here are few lines of code that displays latest 10 posts from the news category , you can edit it to tailor to your needs.

<?php
/* Name of your category you want to show posts from */
$cat = "news";

/* No. of posts to display*/
$num = "10";
 
?>

        <!– Show x Posts from $cat category–>
        <?php query_posts(’showposts=’.$num.‘&category_name=’.$cat.);
          while (have_posts()) : the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <div class="entry">
        <?php the_content(‘Continue…’); ?>
        <p class="postmetadata">Posted in <?php the_category(‘, ‘) ?> | <?php edit_post_link(‘Edit’, , ‘ | ‘); ?>  <?php comments_popup_link(‘No Comments &#187;’, ‘1 Comment &#187;’, ‘% Comments &#187;’); ?></p>
       
        <a href="<?php the_permalink(); ?>" class="permalink">Link to this article</a>
        </div>
<?php endwhile; ?>

The function query_posts(); can be used to control which posts are displayed in the loop. More information on using query_posts(); can be found here : http://codex.wordpress.org/Template_Tags/query_posts .

How to list all registered users on your wordpress site

In my latest project i was required to add a community touch to a site by listing the Name, Email, Nickname, URI and Gravatar of all the registered users on the site. I came with the following solution : I made a new page template called users and added the following lines of php to the template :

<?php
/*
        First we set how we’ll want to sort the user list.
        * ID – User ID number.
        * user_login – User Login name.
        * user_nicename – User Nice name ( nice version of login name ).
        * user_email – User Email Address.
        * user_url – User Website URL.
        * user_registered – User Registration date.
*/

$sort= "user_registered";

//the default avatar to display in case gravatar is not available for a user
$default = "http://www.somewhere.com/some-directory/some-image.png";

//the size of the gravatar , here 96px
$size = 96;

//Build the custom database query to fetch all user IDs
$all_users_id = $wpdb->get_col( $wpdb->prepare(
        "SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s ASC"
        , $sort ));

//we got all the IDs, now loop through them to get individual IDs
foreach ( $all_users_id as $i_users_id ) :

// get user info by calling get_userdata() on each id
$user = get_userdata( $i_users_id );

//GETTING INFO FROM EACH USERS
//get the user’s email ID
$email = $user->user_email;

//build the gravatar URL
$grav_url = "http://www.gravatar.com/avatar.php?
gravatar_id="
.md5( strtolower($email) ).
"&default=".urlencode($default).
"&size=".$size;

//get the user’s full name
$user_fullname=$user->first_name . ‘ ‘ . $user->last_name;

//get the user’s URI
$user_url=$user->user_url;

//get the user’s nickname
$user_nickname=$user->nickname;

//get the user’s description ( the biographical info field, )
$user_profile=$user->description;

?>

<!– Now here you can display each users info using the variables defined above –>

<?php
endforeach; // end the users loop.
?>

Hope you found it useful, cheers :) , WORDPRESS ROCKS

Drive your php code viewers mad! Encode your php script

If you are among the ones who give away free self written php scripts to everybody but want some way to stop script kiddies and newbies just copy-pasting and modifying your script or you just dont want code newbies to know the original code then this post is probably for you. The trick is to encode your php code as a string and then parse the encoded string as php code after decoding it. This trick is very commonly usede by developers. Though this trick cannot stop code copying but can discourage the viewer to a certain extent to copy the code.
Here is how to do it:

  1. Encode your code as string using any encoding method/functions . the most commonly used is base64_encode. You can even use Dynamicguru’s Online base 64 encoder and decoder to instantly convert your code to base64 format
  2. In your script file, decode the generated string using base64_decode function and assign it to a variable
  3. Now call the function eval() passing your decoded string as argument and you are done!

Example :

Consider the following piece of code :

<?php
echo "hello world";
?>

Now suppose you want to disguise the code and make it look un-interpretable , Encode it using our Online base 64 encoder and decoder . here is what the code looks like after encoding :

PD9waHANCmVjaG8gXCJoZWxsbyB3b3JsZFwiOw0KPz4=
//Amazing isnt it?

Now call the eval() function :

eval(base64_decode("PD9waHANCmVjaG8gXCJoZWxsbyB3b3JsZFwiOw0KPz4= "));

//the above code is equal to :

<?php
echo "hello world";
?>
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Note
This trick should not be used if you want to completely disguise your code, as anybody can go a step further and decode it using base64_decode function.

The eval fucntion evaluates a string as a php code and is of immense help in situations where you want a piece of code to be stored in a file / database and executed at a later time

hope you enjoyed the post and learnt something new and useful :D

PHP contact form script

The most common use of php on the internet is probably to make Contact Forms or mail forms . Here is a free php contact form script that takes input from 5 fields : name,email,url,subject and message. The script also validates the input and checks to see if the name , email and message fields are filled out properly and also checks if the email address provided is valid. the script then sends a mail to the administrator containing the message and the visitor info and also writes (appends) the input to a “contact.log” file . The script is quiet easy to understand and edit as it is commented and well written. Just place the following code in a “contact.php” file and change the value of $admin_mail to your email id. You can style the form to your taste using css.

<?php

error_reporting(0);
        //Replace with your email ID
        $admin_mail="mujtaba_91@yahoo.com";
       
if (isset($_POST[‘button’])) {
        $date=date(‘l dS \of F Y h:i A e’);
        $name=htmlentities($_POST[‘name’]);
        $email=htmlentities($_POST[‘email’]);
        $url=htmlentities($_POST[‘url’]);
        $subject=htmlentities($_POST[’subject’]);
        $message=htmlentities(stripslashes($_POST[‘message’]));
        //Form Validation
        $errors="";
        if(empty($name)) {
                $errors.="Please enter your name <br />";
        }
       
        if(empty($email) || !strpos($email, "@") || !strpos($email, ".")) {
                $errors.="Please enter a valid email ID <br />";
        }
       
        if(empty($message)) {
                $errors.="Please enter a message <br />";
        }
       
        if(!empty($url) && !strpos($url,"http://")) {
                $url="http://".$url;
        }
       
       
        //Building mail if the input is valid
       
        if ($errors=="") {
        $mail_subject="Message from :".$email;
         //Required for html formatted mail, do not remove
        $headers  = ‘MIME-Version: 1.0′ . "\r\n";
        //Required for html formatted mail, do not remove
        $headers .= ‘Content-type: text/html; charset=iso-8859-1′ . "\r\n";
        $headers .= "To: Admin <".$admin_mail.">" . "\r\n";
        $headers .= "From: ".$name." <".$email.">" . "\r\n";
       
        //The mail
        $mail_message="
        <html>
        <head>
        <title> Message from "
.$name." </title>
        </head>
        <body>
        <b>Name</b> :<br /> $name <br />
        <b>Email</b> :<br /> $email <br />
        <b>URL</b> :<br /> <a href=\"$url\">$url</a> <br />
        <b>IP Address</b> : <br/>
        "
.$_SERVER[‘REMOTE_ADDR’]." <br />
        <b>Date and Time</b> : <br />
        $date <br />
        <b>Message</b> :<br/> "
.nl2br($message)."
        </body>
        </html>"
;
       
        if(mail($admin_mail,$mail_subject,$mail_message,$headers)) {
                $status="Mail Sent Successfully";
                //echo "<div class=’success’>$status</div>";
        }
        else {
                $status="Mail Failed to Send";
                //echo "<div class=’error’>$status</div>";
        }
       
        //Logging the message to a file
        $file="contact.log";
        $log_message="
        Name : $name\r\n
        Email : $email\r\n
        URL: $url\r\n
        Subject: $subject\r\n
        Time: $date\r\n
        IP Address: "
.$_SERVER[‘REMOTE_ADDR’]."\r\n
        Message:
$message\r\n
        Mailing Status: $status\r\n
        _______________________________________________________________________\r\n
        "
;
        $fh=fopen($file,"a+");
        fwrite($fh,$log_message);
        fclose($fh);
       
        echo "Thanx! i will get back to you soon";
        }
        else {
                echo $errors;
        }

       
}

else {
        echo "
        <form action=\"contact.php\" method=\"post\" id="
myform" >
        <input type=\"text\" name=\"name\" /> Name <br />
        <input type=\"text\" name=\"email\" /> Email <br />
        <input type=\"text\" name=\"url\" /> URL <br />
        <input type=\"text\" name=\"subject\" /> Subject <br />
        <textarea cols=\"30\" rows=\"20\" name=\"message\" ></textarea>
        <input type=\"submit\" name=\"button\" value=\"Submit\" />
        </form>"
;
}
?>

Display your visitors IP address using php

The following line of code shows your visitors their IP address,

<?php echo $_SERVER['REMOTE_ADDR'] ?>

For knowing what all super globals are available for you use the function phpinfo(); or print the complete $_SERVER array using print_r($_SERVER);

© 2010 Dynamic Guru All rights reserved — About UsContactMujtaba