Saturday, August 28, 2010

Get query string values from javascript easily

Use the simple javascript function
<script type="text/javascript">

function querystring(qstr)
{

qstr  = window.location.search.substring(1);

q_vars = qstr.split("&");

for (i=0;i<q_vars.length;i++)
{

ft = q_vars[i].split("=");

if (ft[0] == qstr)
{

return ft[1];

}

}

}
</script>

Call using querystring("string")

Sample : www.example.com/index.php?name=aravind&place=venjaramood

var reqQrstr= querystring("name");
document.write(reqQrstr);

Will output : aravind

Monday, August 16, 2010

Add Delicious Button To Your WordPress Blog

As for most of us know that Google treats the links that are published on Delicious.com higher on search results as compared to normal result links. For that we all must have a delicious save button on our blog. Moreover this is so far the best online bookmarking site.

delicious button

One Step Tutorial:

Place below code where you want to display your Delicious Save Button:

http://delicious.com/post?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>

And if you are not using images in your excerpts and want to add it too automatically, then you can use below code:

http://delicious.com/post?url=<?php
the_permalink(); ?>&title=<?php the_title();
?>&notes=<?php the_excerpt(); ?>

New Official Twitter Button To Your WordPress Blog

As Twitter launched its official tweet button, many
sites have already implemented it. Tweetmeme button never showed the
correct count for tweets, but with this new Official Tweet Button from
Twitter, we hope to have the correct tweet count for our tweets. This
simple tutorial will help you integrate three different types of Twitter buttons with counters and without counters. Hope this helps.

retweet buttons

One Step Tutorial:

Place below code where you want to display your Official Tweet Button:

Type 1
retweet button type1

<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="TutZone">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>



Type 2
retweet button type2

<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="TutZone">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>



Type 3
retweet button type3

<a href="http://twitter.com/share" class="twitter-share-button" data-count="none" data-via="TutZone">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Top 10 Form Validation Techniques

Form Validation with jQuery from Scratch

jQuery Form Validation Tutorials

In this article you will be shown how to build a simple, yet powerful and extensible jQuery form validation plugin.
This article does not show you how to use the jQuery validate plugin,
it covers building a lightweight, flexible solution from scratch. It
won't be nearly as advanced and powerful as the official plugin.
Nevertheless, you'll learn something new from a jQuery, JavaScript and
Object-Oriented aspect.

How to Validate Forms in both sides using PHP and jQuery

jQuery Form Validation Tutorials

You
are going to learn how to validate your forms, in this indepth
tutorial, using PHP and jQuery in both sides: client side (using
javascript with jQuery) and server side (using PHP).
At the end of
the tutorial, you will get a final real working example that will
validate your fields with / without javascript enabled, amd always
making use of server side validaton.

jQuery Contact Form with PHP & jQuery Validation

jQuery Form Validation Tutorials

In
this tutorial, you will learn how to create your own jQuery contact
form using PHP and JQuery. The tut takes you through the initial
basics, creating a single page for your contact form that contains the
markup, PHP to process our contact form and then on to the tricky
process of jQuery validating.

Adding Form Validation to WordPress Comments using jQuery

jQuery Form Validation Tutorials

When
it comes to simpler user experience, having your form validation happen
instantly on the same page is a lot cleaner than reloading pages and
possibly losing some form content. In this tutorial you'll be shown how
to use jQuery to do some instant checking on an example comment form.

Advanced Form Styling & Functionality

jQuery Form Validation Tutorials

This
screencast walks you through the code that powers a fairly advanced web
form. It utilizes jQuery to hide and show inputs as needed as well as
power three plugins. One for applying fancy styling, one for
validation, and one for the serializing of the inputs and AJAX
submission. You will then use PHP to optionally save the users name and
email, as well as send the actual email.

WordPress and jQuery Contact Form without a Plugin

jQuery Form Validation Tutorials

There
are lots of WordPress plugins for contact forms, but wouldn’t it be
nice to have more control over the markup? In this tutorial, you will
be shown how to use a custom page template to create a contact form in
WordPress without a plugin, and use conditional statements, for
validation, to determine if the form had been submitted or not.

A jQuery inline form validation, because validation is a mess

jQuery Form Validation Tutorials

When
it comes to form validation, it’s hard to have a versatile solution
that works with every form. Figuring out how to display errors is not a
simple task.
In this tutorial you will be shown how to create a
form, and when an error needs to be displayed, the script will create a
div and positions it in the top right corner of the input. This way you
will not have to worry about your HTML form structure. The rounded
corner and shadow in the tutorial hasbeen built with CSS3 and degrades
well in non compliant browsers.

Form Validation using jQuery

jQuery Form Validation Tutorials

This
article discusses client-side validation using jQuery's validation
plugin. That is, you will use JavaScript to validate the fields before
submitting the form to the server. This is fast and efficient and
provides quick replies to your visitor in the event of any errors.
However, it is advisable to also validate the data on the server-side
before adding it into the database.
In the tutorial you will create
a form that contains four fields: name, e-mail, comment and URL. The
first three fields are required, whereas the URL field is optional.
And, if you submit the form without filling in the required fields, you
will be prompted with an error message.

Using jQuery and Ajax to Validate Forms

jQuery Form Validation Tutorials

This tutorial expects you to have already built your form up to the point where it works, but now needs some validation.

When you finish this tutorial, the username example, you have built,
will check with the server whether the chosen name is a) valid and b)
available. And the avatar example will try to load the URL in to a
hidden image, if it fails, it will show the appropriate message.

jQuery Form Validation JavaScript Tutorial

jQuery Form Validation Tutorials

There
are many jQuery plugins available to download that are similiar to what
you will build in this tutorial. But if you need more flexibilty with
your form or a better understanding of validation this tutorial will
help you. So, here is a step-by-step approach to achieving client side
JavaScript validation using jQuery.

Web Form Validation: Best Practices and Tutorials
jQuery Form Validation Tutorials
In
this article, from Smashing magazine, you will learn to go beyond the
validation of a form itself and explore different validation and error
feedback techniques, methods and approaches. The article gives you
indepth analysis of the pros and cons of server-side and client-side
validation, and offers some great advice.

Monday, August 9, 2010

Passing an array from a form to another page PHP

Hi,



First, you probably want to use implode, and not explode, to construct your $to variable ;-)



<code><span class="pln">$ids </span><span class="pun">=</span><span class="pln"> array</span><span class="pun">(</span><span class="lit">a@a.com</span><span class="pun">,</span><span class="pln"> </span><span class="lit"></span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="lit"></span><span class="pun">,</span><span class="pln"> </span><span class="lit"></span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="lit"></span><span class="pun">,</span><span class="pln"> </span><span class="lit"></span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="lit"></span><span class="pun">);</span><span class="pln">
$to </span><span class="pun">=</span><span class="pln"> implode</span><span class="pun">(</span><span class="str">','</span><span class="pun">,</span><span class="pln"> $ids</span><span class="pun">);</span><span class="pln">
var_dump</span><span class="pun">(</span><span class="pln">$to</span><span class="pun">);</span><span class="pln">
</span></code>


Which would give you



<code><span class="kwd">string</span><span class="pln"> </span><span class="str">'</span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="str">,</span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="str">,</span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="str">,</span></code><code><span class="lit">a@a.com</span><span class="pun"></span></code><code><span class="str">'</span><span class="pln"> </span><span class="pun"></span><span class="pun"></span><span class="pln"><br /></span></code>


You then inject this in the form ; something like this would probably do :



<code><span class="pln"><input type="hidden"  value="</span><span class="pun"><?</span><span class="pln">php echo $to</span><span class="pun">;</span><span class="pln"> </span><span class="pun">?></span><span class="pln">"><br /></span></code>






Then, on the PHP script that receives the data from the form when it's been submitted, you'd use explode to extract the data as an array, from the string :



<code><span class="kwd">foreach</span><span class="pln"> </span><span class="pun">(</span><span class="pln">explode</span><span class="pun">(</span><span class="str">','</span><span class="pun">,</span><span class="pln"> $_POST</span><span class="pun">[</span><span class="str">'mail'</span><span class="pun">])</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> $mailid</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br />    print_r(</span><span class="pun"></span><span class="pln">$mailid</span><span class="pun">);</span><span class="pln"><br /></span><span class="pun">}</span><span class="pln"><br /></span></code>


Which will get you each items:





And, now, you can use thoses ids...


Wednesday, August 4, 2010

Some PHP Snippets

Highlight specific words in a phrase

Sometimes, for example,
when displaying search results, it is a great idea to highlight
specific words. This is exactly what the following function can do:

1.function highlight($sString, $aWords) {
2.    if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
3.        return false;
4.    }
5. 
6.    $sWords = implode ('|', $aWords);
7.    return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
8.}

Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

Get your average Feedburner subscribers

Recently,
Feedburner counts had lots of problems and it’s hard to say that the
provided info is still relevant. This code will grab your subscriber
count from the last 7 days and will return the average.

01.function get_average_readers($feed_id,$interval = 7){
02.    $today = date('Y-m-d', strtotime("now"));
03.    $ago = date('Y-m-d', strtotime("-".$interval." days"));
04.    $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
05.    $ch = curl_init();
06.    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
07.    curl_setopt($ch, CURLOPT_URL, $feed_url);
08.    $data = curl_exec($ch);
09.    curl_close($ch);
10.    $xml = new SimpleXMLElement($data);
11.    $fb = $xml->feed->entry['circulation'];
12. 
13.    $nb = 0;
14.    foreach($xml->feed->children() as $circ){
15.        $nb += $circ['circulation'];
16.    }
17. 
18.    return round($nb/$interval);
19.}

Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count

Automatic password creation

Although
I personally prefer leaving users to choose their password themselves,
a client recently asked me to generate passwords automatically when a
new account is created.
The following function is flexible: You can choose the desired length and strength for the password.

01.function generatePassword($length=9, $strength=0) {
02.    $vowels = 'aeuy';
03.    $consonants = 'bdghjmnpqrstvz';
04.    if ($strength >= 1) {
05.        $consonants .= 'BDGHJLMNPQRSTVWXZ';
06.    }
07.    if ($strength >= 2) {
08.        $vowels .= "AEUY";
09.    }
10.    if ($strength >= 4) {
11.        $consonants .= '23456789';
12.    }
13.    if ($strength >= 8 ) {
14.        $vowels .= '@#$%';
15.    }
16. 
17.    $password = '';
18.    $alt = time() % 2;
19.    for ($i = 0; $i < $length; $i++) {
20.        if ($alt == 1) {
21.            $password .= $consonants[(rand() % strlen($consonants))];
22.            $alt = 0;
23.        } else {
24.            $password .= $vowels[(rand() % strlen($vowels))];
25.            $alt = 1;
26.        }
27.    }
28.    return $password;
29.}

Source: http://www.phpsnippets.info/generate-a-password-in-php

Compress multiple CSS files

If
you’re using different CSS files on your site, they might take quite
long to load. Using PHP, you can compress them into a single file with
no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.

01.header('Content-type: text/css');
02.ob_start("compress");
03.function compress($buffer) {
04.  /* remove comments */
05.  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
06.  /* remove tabs, spaces, newlines, etc. */
07.  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
08.  return $buffer;
09.}
10. 
11./* your css files */
12.include('master.css');
13.include('typography.css');
14.include('grid.css');
15.include('print.css');
16.include('handheld.css');
17. 
18.ob_end_flush();

Source: http://www.phpsnippets.info/compress-css-files-using-php

Get short urls for Twitter

Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.

1.function getTinyUrl($url) {
2.    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
3.}

Source: http://www.phpsnippets.info/convert-url-to-tinyurl

Calculate age using date of birth

Pass
a birth date to this function, and it will return the age of the
person; very useful when building communities or social media sites.

01.function age($date){
02.    $year_diff = '';
03.    $time = strtotime($date);
04.    if(FALSE === $time){
05.        return '';
06.    }
07. 
08.    $date = date('Y-m-d', $time);
09.    list($year,$month,$day) = explode("-",$date);
10.    $year_diff = date("Y") – $year;
11.    $month_diff = date("m") – $month;
12.    $day_diff = date("d") – $day;
13.    if ($day_diff < 0 || $month_diff < 0) $year_diff–;
14. 
15.    return $year_diff;
16.}

Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth

Calculate execution time

For
debugging purposes, it is a good thing to be able to calculate the
execution time of a script. This is exactly what this piece of code can
do.

01.//Create a variable for start time
02.$time_start = microtime(true);
03. 
04.// Place your PHP/HTML/JavaScript/CSS/Etc. Here
05. 
06.//Create a variable for end time
07.$time_end = microtime(true);
08.//Subtract the two times to get seconds
09.$time = $time_end - $time_start;
10. 
11.echo 'Script took '.$time.' seconds to execute';

Source: http://phpsnips.com/snippet.php?id=26

Maintenance mode with PHP

When
updating your site, it is generally a good thing to temporarily
redirect your users to a “Maintenance” page so they will not see any
critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with PHP:

01.function maintenance($mode = FALSE){
02.    if($mode){
03.        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
04.            header("Location: http://example.com/maintenance.php");
05.            exit;
06.        }
07.    }else{
08.        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
09.            header("Location: http://example.com/");
10.            exit;
11.        }
12.    }
13.}

Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php

Prevent js and css files from being cached

By
default, external files such as javascript and css are cached by the
browser. If you want to prevent this from caching, simply use this easy
tip:

1.<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;

The result will look like this:

1.<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css" /&glt;

Source: http://davidwalsh.name/prevent-cache

Add (th, st, nd, rd, th) to the end of a number

Another useful snippet which will automatically add st, nd, rd or th after a number.

01.function make_ranked($rank) {
02.    $last = substr( $rank, -1 );
03.    $seclast = substr( $rank, -2, -1 );
04.    if( $last > 3 || $last == 0 ) $ext = 'th';
05.    else if( $last == 3 ) $ext = 'rd';
06.    else if( $last == 2 ) $ext = 'nd';
07.    else $ext = 'st';
08. 
09.    if( $last == 1 && $seclast == 1) $ext = 'th';
10.    if( $last == 2 && $seclast == 1) $ext = 'th';
11.    if( $last == 3 && $seclast == 1) $ext = 'th';
12. 
13.    return $rank.$ext;
14.}

Source: http://phpsnips.com/snippet.php?id=37

Scr.im: Email Address Shortener

If you share your email address on a
forum or other public website, spammers can easily find it with bots
that scour the Web. Sure, you could write your email address like this:
john (dot) doe (at) company (dot) com, but that’s a pain,
and it doesn’t look very nice. And it’s only a matter of time before
bots can easily translate addresses written that way.


Screenshot


Scr.im
lets you use a shortened URL to give out your email address safely and
securely in forums. Just enter your email address on Scr.im, and it
gives you a link to a page with your email address, with security to
prevent bots from viewing it. (cc)

Display Most Popular Posts in WordPress

Place below code where you want to display your Most Popular Posts:

<h2>Popular Posts</h2>
<ul>

<?php $result = $wpdb->get_results("SELECT
comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count
DESC LIMIT 0 , 5");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>

<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>

Just change the 5 in line 3 to change the number of displayed popular posts. That’s it.

Tuesday, August 3, 2010

Prevent Spam by Blocking IP Addresses

Sometimes there comes a person or bot which constantly spams your blog. To block that person or that bot you can use following hack. You can simply block his IP and he will be never able to visit your site again.

Note: Do take backup of your .htaccess file before you try this.
Place below code in your .htaccess file:

<Limit GET POST PUT>
order allow,deny
allow from all
deny from 123.456.789
</LIMIT>

Replace 123.456.789 with the IP address you want to block.

Popular Posts