Archives for category —php

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>"
;
}
?>

© 2010 Dynamic Guru All rights reserved — About UsContactMujtaba