Archive

Archive for the ‘securenext’ Category

Facebook introduces video on Instagram

June 22, 2013 5 comments

BaltNEW YORK: Facebook is adding video to its popular photo-sharing app Instagram, following in the heels of Twitter’s growing video-sharing app, Vine.

Instagram co-founder Kevin Systrom said on Thursday that users will be able to record and share 15-second clips by tapping a video icon in the app. They can also apply filters to videos to add contrast, make them black and white or different hues.

“This is the same Instagram we all know and love but it moves,” he said at an event held at Facebook’s Menlo Park, California, headquarters.

Vine, which launched in January, has 13 million users and lets people create and share 6-second video clips. Instagram has 100 million users, up from 20 million when Facebook bought the company more than a year ago. If users like it, Facebook’s move could propel mobile video sharing into the mainstream.

To use the video feature, Instagram users can tap on the same camera icon they use to snap photos. A new video camera icon will appear on the right side. Tap it and a screen with a red video button will let you record clips of sunsets, kids running in parks or co-workers staring at their computer screens.

The app will record as long as your finger is on the red button or for 15 seconds, whichever comes first. Not unlike Vine, taking your finger off the button will stop the recording, allowing you to shoot the scene from a different angle or record something else altogether. Once you have 15 seconds of footage, you can play it from the beginning and post it on Instagram to share with others.

Given Vine’s popularity, “it is perhaps more surprising that Facebook has not introduced video for Instagram sooner. There is no doubt Twitter will move quickly to up the ante on Vine and this could undercut Facebook’s efforts with video on Instagram,” said Eden Zoller, principal consumer analyst at Ovum, a technology research firm.

Unzip a Zip File in php

<!--?php

    function unzip($location,$newLocation){
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$icount($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?>
//Use the code as following:
<!--?php
include 'functions.php';
if(unzip('zipedfiles/selvabalaji.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?>

10 More Useful WordPress Code Snippets For Your Blog

July 6, 2012 1 comment

WordPress is the best open source sofware which is completely free to use.The advantage of being open source for a software is that developers can see its codes an write plugins to make it more functional.And also developers add or change small piece of codes especially in functions.php file to unleash the power of your favorite blogging engine.

In today’s post we are again sharing wordpress code snippets.I think you will find a useful wordpress code snippet for your wordpress blog.

You may also take a look at our past wordpress theme collections;

htaccess Gzip Compression

Add the following code in your .htaccess file.Gzip will drastically reduce HTTP response time.

# BEGIN GZIP

AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript

# END GZIP

Instructions:
Just add this to your .htaccess file. Gzip will drastically reduce HTTP response time.

How to Remove the Width and Height Attributes From WP Image Uploader

add_filter( ‘post_thumbnail_html’, ‘remove_width_attribute’, 10 );
add_filter( ‘image_send_to_editor’, ‘remove_width_attribute’, 10 );

function remove_width_attribute( $html ) {
$html = preg_replace( ‘/(width|height)=\”\d*\”\s/’, “”, $html );
return $html;
}

If you upload images via the WordPress image uploader and insert it into your post, it will include the image width and height attribute in the html tag. Here’s what it will look like.

In most cases, this is absolutely alright. However, if you are using a responsive theme or are dealing with responsive web design, the “width” and “height” attribute will be a major roadblock that you need to get rid of.

Here’s how you can do it.

1. Open your theme’s functions.php file.

2. Copy and paste the following code:
add_filter( ‘post_thumbnail_html’, ‘remove_width_attribute’, 10 );
add_filter( ‘image_send_to_editor’, ‘remove_width_attribute’, 10 );

function remove_width_attribute( $html ) {
$html = preg_replace( ‘/(width|height)=\”\d*\”\s/’, “”, $html );
return $html;
}

3. Save the changes.

That’s it. Next time when you insert image into the post via the WP image uploader, the width and height attribute will no longer be there.

How to Change the Font in HTML Editor In WordPress 3.3

add_action( ‘admin_head-post.php’, ‘wpdb_fix_html_editor_font’ );
add_action( ‘admin_head-post-new.php’, ‘wpdb_fix_html_editor_font’ );

function wpdb_fix_html_editor_font() { ?>

<!–?php }

Add/remove Contact Info Fields

To add or remove fields from this section, just add the following to your functions.php.

Login with Username or Email Address

Adding this snippet to the functions.php of your wordpress theme will let users login using an email address or a username. The second snippet will change the text on the login page from “username” to “username / email” but feel free to change the login text to anything you would like.

function login_with_email_address($username) {
$user = get_user_by(’email’,$username);
if(!empty($user->user_login))
$username = $user->user_login;
return $username;
}
add_action(‘wp_authenticate’,’login_with_email_address’);
function change_username_wps_text($text){
if(in_array($GLOBALS[‘pagenow’], array(‘wp-login.php’))){
if ($text == ‘Username’){$text = ‘Username / Email’;}
}
return $text;
}
add_filter( ‘gettext’, ‘change_username_wps_text’ );

Add PayPal Donate Button

Add this snippet to the functions.php to add ‘Donate’ Button on your WordPress Website

// paypal donate button
function cwc_donate_shortcode( $atts ) {
extract(shortcode_atts(array(
‘text’ => ‘Make a donation’,
‘account’ => ‘REPLACE ME’,
‘for’ => ”,
), $atts));
global $post;
if (!$for) $for = str_replace(” “,”+”,$post->post_title);
return ‘‘.$text.’‘;
}
add_shortcode(‘donate’, ‘cwc_donate_shortcode’);

India soon to be the biggest source of PHP developers?

English: India. Area controlled by India in da...

The number of Indian PHP developers has been growing at a large pace in the last few years, when compared to other countries. A few years ago, India was just one of the top ten countries with more PHP developers. Now India is number 2 and is almost surpassing United States, which is still number 1.

While it is difficult to take such broad conclusions seriously based on member statistics of a single community, PHPClasses does have a large user base and can arguably be considered representative. Any article tagged India and software these days attract the usual crap about how Indian developers are the worst and how everybody who outsources to India never does it again. So I was surprised when some of the usually ‘silent’ majority of the client base who continue outsourcing development to India came out to defend their decision.

I did come away with a very interesting statistic; Indian developers have won most awards this year for their contribution against sizable competition. Most Indian developers I meet have difficulty understanding the concept of giving back to the community, so it’s always refreshing to see a number of people doing exactly that.

Import Yahoo contact to website / download CSV

June 28, 2012 1 comment

Image representing OAuth as depicted in CrunchBase

Written in PHP and using cURL, this script imports the names and email addresses from your yahoo account (yahoo id and password needed to login to yahoo from the script and retreive the address book).

<!–?php–>
ob_start();
session_start();
require ‘globals.php’;
require ‘oauth_helper.php’;
require ‘yahoo_function.php’;

// Callback can either be ‘oob’ or a url whose domain must match
// the domain that you entered when registering your application

$callback='<your call back URL>’;

if($_REQUEST[‘oauth_verifier’] != ”) {
$request_token = $_REQUEST[‘oauth_token’];
$oauth_verifier = $_REQUEST[‘oauth_verifier’];
$request_token_secret = $_SESSION[‘request_token_secret’];

$accessToken = get_access_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,$request_token, $request_token_secret,$oauth_verifier, false, true, true);

$access_token = urldecode($accessToken[3][‘oauth_token’]);
$access_token_secret = urldecode($accessToken[3][‘oauth_token_secret’]);
$guid = $accessToken[3][‘xoauth_yahoo_guid’];

$callcont = callcontact(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $guid, $access_token, $access_token_secret, false, true);
print ‘Total Email COntact :’ .$callcont[‘contacts’][‘total’];
print ‘<br/><br/>’;

print ‘asda’.($callcont[‘contacts’][‘total’]);
for($i=0; $i<=$callcont[‘contacts’][‘total’];$i++) {
print ‘<br/><br/>’;
print $callcont[‘contacts’][‘contact’][$i][‘fields’][0][‘value’];
print ‘<br/><br/>’;
}

}else{

$retarr = get_request_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,$callback, false, true, true);

if (! empty($retarr)){
$request_token = $retarr[3][‘oauth_token’];
$request_token_secret = $retarr[3][‘oauth_token_secret’];
$request_url = urldecode($retarr[3][‘xoauth_request_auth_url’]);
$_SESSION[‘request_token_secret’] = $request_token_secret;
header(“location:https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=&#8221;.$request_token);
}
exit(0);
}
?>

Yahoo_function.php

<?php

function get_request_token($consumer_key, $consumer_secret, $callback, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=false)
{
$retarr = array(); // return value
$response = array();

$url = ‘https://api.login.yahoo.com/oauth/v2/get_request_token&#8217;;
$params[‘oauth_version’] = ‘1.0’;
$params[‘oauth_nonce’] = mt_rand();
$params[‘oauth_timestamp’] = time();
$params[‘oauth_consumer_key’] = $consumer_key;
$params[‘oauth_callback’] = $callback;

// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params[‘oauth_signature_method’] = ‘HMAC-SHA1‘;
$params[‘oauth_signature’] =
oauth_compute_hmac_sig($usePost? ‘POST‘ : ‘GET’, $url, $params,
$consumer_secret, null);
} else {
$params[‘oauth_signature_method’] = ‘PLAINTEXT‘;
$params[‘oauth_signature’] =
oauth_compute_plaintext_sig($consumer_secret, null);
}

// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {

$query_parameter_string = oauth_http_build_query($params, FALSE);

$header = build_oauth_header($params, “yahooapis.com”);
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}

// POST or GET the request
if ($usePost) {
$request_url = $url;
logit(“getreqtok:INFO:request_url:$request_url”);
logit(“getreqtok:INFO:post_body:$query_parameter_string”);
$headers[] = ‘Content-Type: application/x-www-form-urlencoded‘;
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
(‘?’ . $query_parameter_string) : ” );

logit(“getreqtok:INFO:request_url:$request_url”);

$response = do_get($request_url, 443, $headers);

}

// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit(“getreqtok:INFO:response_body_parsed:”);

}
$retarr = $response;
$retarr[] = $body_parsed;
}

return $retarr;
}
function get_access_token($consumer_key, $consumer_secret, $request_token, $request_token_secret, $oauth_verifier, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();

$url = ‘https://api.login.yahoo.com/oauth/v2/get_token&#8217;;
$params[‘oauth_version’] = ‘1.0’;
$params[‘oauth_nonce’] = mt_rand();
$params[‘oauth_timestamp’] = time();
$params[‘oauth_consumer_key’] = $consumer_key;
$params[‘oauth_token’]= $request_token;
$params[‘oauth_verifier’] = $oauth_verifier;

// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params[‘oauth_signature_method’] = ‘HMAC-SHA1’;
$params[‘oauth_signature’] =
oauth_compute_hmac_sig($usePost? ‘POST’ : ‘GET’, $url, $params,
$consumer_secret, $request_token_secret);
} else {
$params[‘oauth_signature_method’] = ‘PLAINTEXT’;
$params[‘oauth_signature’] =
oauth_compute_plaintext_sig($consumer_secret, $request_token_secret);
}

// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, false);
$header = build_oauth_header($params, “yahooapis.com”);
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}

// POST or GET the request
if ($usePost) {
$request_url = $url;
logit(“getacctok:INFO:request_url:$request_url”);
logit(“getacctok:INFO:post_body:$query_parameter_string”);
$headers[] = ‘Content-Type: application/x-www-form-urlencoded’;
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
(‘?’ . $query_parameter_string) : ” );
logit(“getacctok:INFO:request_url:$request_url”);
$response = do_get($request_url, 443, $headers);
}

// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit(“getacctok:INFO:response_body_parsed:”);
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $retarr;
}
function callcontact($consumer_key, $consumer_secret, $guid, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();

$url = ‘http://social.yahooapis.com/v1/user/&#8217; . $guid . ‘/contacts’;

$params[‘format’] = ‘json’;
$params[‘view’] = ‘compact’;
$params[‘oauth_version’] = ‘1.0’;
$params[‘oauth_nonce’] = mt_rand();
$params[‘oauth_timestamp’] = time();
$params[‘oauth_consumer_key’] = $consumer_key;
$params[‘oauth_token’] = $access_token;

// compute hmac-sha1 signature and add it to the params list
$params[‘oauth_signature_method’] = ‘HMAC-SHA1’;
$params[‘oauth_signature’] =
oauth_compute_hmac_sig($usePost? ‘POST’ : ‘GET’, $url, $params,
$consumer_secret, $access_token_secret);

// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, “yahooapis.com”);
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}

// POST or GET the request
if ($usePost) {
$request_url = $url;
logit(“callcontact:INFO:request_url:$request_url”);
logit(“callcontact:INFO:post_body:$query_parameter_string”);
$headers[] = ‘Content-Type: application/x-www-form-urlencoded’;
$response = do_post($request_url, $query_parameter_string, 80, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
(‘?’ . $query_parameter_string) : ” );
logit(“callcontact:INFO:request_url:$request_url”);
$response = do_get($request_url, 80, $headers);
}

// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($body) {
logit(“callcontact:INFO:response:”);

json_pretty_print($body);

}
$retarr = $response;
}
$contactsRes = json_decode($retarr[2],true);
return $contactsRes;
}
?>

Facebook buys facial-recognition startup

Image representing Facebook as depicted in Cru...

Image via CrunchBase

Image representing Face.com as depicted in Cru...

Image via CrunchBase

Facebook Inc (FB.O) is paying $55 million to $60 million to buy Face.com, according to people familiar with the matter, acquiring the company that provides the facial-recognition technology used by the world’s largest social network to help users identify and tag photos.

The deal bolsters one of Facebook’s most popular features — the sharing and handling of photos — but the use of the startup’s

has spurred concerns about user privacy.

The No. 1 social network will pay cash and stock for Face.com, potentially paying as much as $60 million, two sources with knowledge of the deal said. Media reports in past weeks have pegged the transaction at $80 million to $100 million.

Neither Facebook nor Face.com disclosed terms of the deal, which is expected to close in coming weeks.

Facebook, which will acquire the technology and the employees of the 11-person Israeli company, said in a statement that the deal allows the company to bring a “long-time technology vendor in house.”

Face.com, which has raised nearly $5 million from investors including Russian Web search site Yandex (YNDX.O), launched its first product in 2009. The company makes standalone applications that consumers can use to help them identify photos of themselves and of their friends on Facebook, as well as providing the technology that Facebook has integrated into its service.

Facebook uses the technology to scan a user’s newly uploaded photos, compares faces in the snapshots with previous pictures, then tries to match faces and suggest name tags. When a match is found, Facebook alerts the person uploading the photos and invites them to “tag,” or identify, the person in the photo.

Responding to inquiries from U.S. and European privacy advocates, Facebook last year made it easier for users to opt out of its controversial facial-recognition technology for photographs posted on the website, an effort to address concerns that it had violated consumers’ privacy.

The deal is the latest in a string of acquisitions by Facebook in recent months, including the $1 billion acquisition of mobile photo-sharing service Instagram. U.S. antitrust regulators are undertaking an extended review of the Instagram deal, which Facebook expects to close by the end of the year.

Shares of Facebook, which continue to trade below the price at which they were offered during the initial public offering in May, closed Monday’s regular session up 4.7 percent at $31.41.

Mozilla launches Thimble, a new tool that makes creating a website simple

In 1997, making a website seemed like the simplest thing in the world. Of course, it wasn’t — there was all sorts of HTML code involved, and making a professional-looking site took almost as much work then as it does now. But there were tools available to make it seem easy — Tripod and Geocities had templates and tutorials, and Netscape Navigator had a decent WYSIWYG web creation tool built in.
Fast forward 15 years, and creating a website seems like an endeavor best left to the professionals. But Mozilla, carriers of the old Netscape crown, wants to change that perception with Thimble, a web-creation tool that promises to make the act of creating a website easier than ever.
Aside from a basic page creation tool, Thimble has a number of interesting tutorials built in to help teach you HTML, and by extension, how to create your own page. One of the tutorials, called Hack a Map, gets you started by showing you some pretty advanced code. But the tutorial isn’t about learning the advanced code, it’s about learning the basic errors that are causing the page at the left to show up incorrectly. Thimble will show you exactly where the website is broken — say, in showing you where a missing HTML tag should go. Even though you’re doing light work, you’re doing that work on a complicated page. The whole process feels far more enjoyable than your usual tutorial, as if you’re learning by doing something important. Even if that something important is a map filled with a Minecraft pig, CatBread, and a triple rainbow.
If you’re curious, you can check out Thimble over at the Mozilla website. And who knows, while playing around with pictures of cats, you might actually wind up learning something.

How to Make a Slick Ajax Contact Form with jQuery and PHP

June 16, 2012 1 comment

Contact forms can be useful way for visitors to contact the owner of a site. They’re easy to use, and since they don’t expose the site owner’s email address in the page, they cut down on spam too.

However, contact forms can also be cumbersome, especially as they’re usually on a separate page. The visitor has to visit the contact form page, fill in the details, view yet another response page, and then try to make their way back to the page they were originally reading.

Fortunately, Ajax gives us a way round this problem. By embedding the form in the page, and submitting the form data via Ajax, the user never has to leave the current page. It also provides a smoother experience for the user.

In this tutorial we’ll build a nice-looking, embedded Ajax contact form that the user can summon up by clicking a link in the page. Along the way, we’ll explore various topics, including:

  • HTML5 form fields
  • How to use fallback techniques to make the form function even if the browser has JavaScript turned off
  • Using CSS techniques to create attractive forms
  • Writing a secure form mailer using PHP
  • Animating page elements with jQuery, and, of course…
  • Using jQuery to make Ajax requests

Before you begin, check out the finished product by clicking the View Demo button above. This opens a new page with some dummy content, and a couple of “Send us an email” links. Click one of these links to display the form.

Step 1: Create the markup

Let’s start with the HTML for our page. This includes the form itself — we’ll hide it initially using JavaScript when the page loads — and also some dummy content and a couple of “Send us an email” links that will display the form when clicked:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!doctype html>
<html lang="en">
<head>
<title>A Slick Ajax Contact Form with jQuery and PHP</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<div id="content">
  <p style="padding-bottom: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">~ Send us an email ~</a></p>
  <!-- Content here -->
  <p style="padding-top: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">~ Send us an email ~</a></p>
 
</div>
<form id="contactForm" action="processForm.php" method="post">
  <h2>Send us an email...</h2>
  <ul>
    <li>
      <label for="senderName">Your Name</label>
      <input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="40" />
    </li>
    <li>
      <label for="senderEmail">Your Email Address</label>
      <input type="email" name="senderEmail" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="50" />
    </li>
    <li>
      <label for="message" style="padding-top: .5em;">Your Message</label>
      <textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
    </li>
  </ul>
  <div id="formButtons">
    <input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
    <input type="button" id="cancel" name="cancel" value="Cancel" />
  </div>
</form>
<div id="sendingMessage" class="statusMessage"><p>Sending your message. Please wait...</p></div>
<div id="successMessage" class="statusMessage"><p>Thanks for sending your message! We'll get back to you shortly.</p></div>
<div id="failureMessage" class="statusMessage"><p>There was a problem sending your message. Please try again.</p></div>
<div id="incompleteMessage" class="statusMessage"><p>Please complete all the fields in the form before sending.</p></div>
</body>
</html>

I’ve omitted the dummy content in the above code, since it’s not relevant to the tutorial.

The form sends its data to a processForm.php script that does the actual emailing. (We’ll write this PHP script in a moment.) By setting the form’s action attribute to "processForm.php", we ensure that the form is usable even with JavaScript disabled. Later, our JavaScript will read this action attribute so that it knows where to send the Ajax request.

The form itself uses some HTML5 form features such as placeholders, the email field type, and the required attribute to ensure that all the fields have been filled in. We’ll also add JavaScript validation for browsers that don’t yet support HTML5 validation.

Step 2: Add the CSS

Screenshot of styled form

Now we’ll add the CSS to our HTML page in order to style the page and form. The bulk of the CSS positions the form and status messages in the centre of the window, and styles the form and form fields.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<style type="text/css">
/* Add some margin to the page and set a default font and colour */
body {
  margin: 30px;
  font-family: "Georgia", serif;
  line-height: 1.8em;
  color: #333;
}
/* Set the content dimensions */
#content {
  width: 800px;
  padding: 50px;
  margin: 0 auto;
  display: block;
  font-size: 1.2em;
}
#content h2 {
  line-height: 1.5em;
}
/* Add curved borders to various elements */
#contactForm, .statusMessage, input[type="submit"], input[type="button"] {
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px
  border-radius: 10px;
}
/* Style for the contact form and status messages */
#contactForm, .statusMessage {
  color: #666;
  background-color: #ebedf2;
  background: -webkit-gradient( linear, left bottom, left top, color-stop(0,#dfe1e5), color-stop(1, #ebedf2) );
  background: -moz-linear-gradient( center bottom, #dfe1e5 0%, #ebedf2 100% ); 
  border: 1px solid #aaa;
  -moz-box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  -webkit-box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  box-shadow: 0 0 1em rgba(0, 0, 0, .5);
  opacity: .95;
}
/* The form dimensions */
#contactForm {
  width: 40em;
  height: 33em;
  padding: 0 1.5em 1.5em 1.5em;
  margin: 0 auto;
}
/* Position the form in the middle of the window (if JavaScript is enabled) */
#contactForm.positioned {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin-top: auto;
  margin-bottom: auto;
}
/* Dimensions and position of the status messages */
.statusMessage {
  display: none;
  margin: auto;
  width: 30em;
  height: 2em;
  padding: 1.5em;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.statusMessage p {
  text-align: center;
  margin: 0;
  padding: 0;
}
/* The header at the top of the form */
#contactForm h2 {
  font-size: 2em;
  font-style: italic;
  letter-spacing: .05em;
  margin: 0 0 1em -.75em;
  padding: 1em;
  width: 19.5em
  color: #aeb6aa;
  background: #dfe0e5 url('images/stamp.jpg') no-repeat 15em -3em; /* http://morguefile.com/archive/display/606433 */
  border-bottom: 1px solid #aaa;
  -moz-border-radius: 10px 10px 0 0;
  -webkit-border-radius: 10px 10px 0 0
  border-radius: 10px 10px 0 0;
}
/* Give form elements consistent margin, padding and line height */
#contactForm ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
#contactForm ul li {
  margin: .9em 0 0 0;
  padding: 0;
}
#contactForm input, #contactForm label {
  line-height: 1em;
}
/* The field labels */
label {
  display: block;
  float: left;
  clear: left;
  text-align: right;
  width: 28%;
  padding: .4em 0 0 0;
  margin: .15em .5em 0 0;
  font-weight: bold;
}
/* The fields */
input, textarea {
  display: block;
  margin: 0;
  padding: .4em;
  width: 67%;
  font-family: "Georgia", serif;
  font-size: 1em;
  border: 1px solid #aaa;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;   
  border-radius: 5px;
  -moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  -webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
  background: #fff;
}
textarea {
  height: 13em;
  line-height: 1.5em;
  resize: none;
}
/* Place a border around focused fields, and hide the inner shadow */
#contactForm *:focus {
  border: 1px solid #66f;
  outline: none;
  box-shadow: none;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
}
/* Display correctly filled-in fields with a green background */
input:valid, textarea:valid {
  background: #dfd;
}
/* The Send and Cancel buttons */
input[type="submit"], input[type="button"] {
  float: right;
  margin: 2em 1em 0 1em;
  width: 10em;
  padding: .5em;
  border: 1px solid #666;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px
  border-radius: 10px;
  -moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  -webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  color: #fff;
  background: #0a0;
  font-size: 1em;
  line-height: 1em;
  font-weight: bold;
  opacity: .7;
  -webkit-appearance: none;
  -moz-transition: opacity .5s;
  -webkit-transition: opacity .5s;
  -o-transition: opacity .5s;
  transition: opacity .5s;
}
input[type="submit"]:hover,
input[type="submit"]:active,
input[type="button"]:hover,
input[type="button"]:active {
  cursor: pointer;
  opacity: 1;
}
input[type="submit"]:active, input[type="button"]:active {
  color: #333;
  background: #eee;
  -moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
  -webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
  box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
}
input[type="button"] {
  background: #f33;
}
/* Header/footer boxes */
.wideBox {
  clear: both;
  text-align: center;
  margin: 70px;
  padding: 10px;
  background: #ebedf2;
  border: 1px solid #333;
}
.wideBox h1 {
  font-weight: bold;
  margin: 20px;
  color: #666;
  font-size: 1.5em;
}
</style>
<!-- Some IE7 hacks and workarounds -->
<!--[if lt IE 8]>
<style>
/* IE7 needs the fields to be floated as well as the labels */
input, textarea {
  float: right;
}
#formButtons {
  clear: both;
}
/*
  IE7 needs an ickier approach to vertical/horizontal centring with fixed positioning.
  The negative margins are half the element's width/height.
*/
#contactForm.positioned, .statusMessage {
  left: 50%;
  top: 50%;
}
#contactForm.positioned {
  margin-left: -20em;
  margin-top: -16.5em;
}
.statusMessage {
  margin-left: -15em;
  margin-top: -1em;
}
</style>
<![endif]-->

Let’s look at some interesting sections of the CSS:

  1. Style for the contact form and status messages
    We give the form and status boxes a nice gentle top-to-bottom gradient using -webkit-gradient and -moz-linear-gradient, and we also add a drop shadow with box-shadow (and its vendor-specific variants). Finally, we give the form and message boxes an opacity of .95 (95%), which makes the page content just show through — a nice subtle effect.
  2. Position the form in the middle of the window (if JavaScript is enabled)
    Initially, we simply place the form inline after the page content. This is so that the form can be used for non-JavaScript-enabled browsers without getting in the way of the content. However, for JavaScript browsers, we want the form to appear in the centre of the window, over the top of the content.Our #contactForm.positioned rule does just that. It uses fixed positioning, sets the top, bottom, left and right values all to zero, and ensures that all 4 margins are set to auto. This centres the element both horizontally and vertically in most modern browsers. Later we’ll use our JavaScript to add the positionedclass to the form.We also position the status message boxes in the same way.
  3. The header at the top of the form
    Our form includes a nice “Send us an email…” header with an image of a postage stamp. Our #contactForm h2rule styles this header. We give the text a large italic style and space the letters out slightly. We also add margin and padding to create space around and inside the header. We use some negative left margin (-.75em) on the header to bypass the padding on the form, so that the header goes right to the left edge of the form. We also set the width of the header to 19.5em so that it exactly matches the width of the form.Why -.75em and 19.5em? Because ems cascade, and we’ve set our font size to 2em. So -.75em actually becomes -1.5em (the width of the form’s padding), and 19.5em becomes 39em (the width of the form, minus 1em for the h2‘s padding). Phew! Maybe I’ll use pixels next time… :)We also set the heading’s colour, give it a dark background, position the postage stamp image in the top right corner, add a thin bottom border, and add curved top corners.
  4. The fields
    We give the input and textarea fields an attractive font, a rounded border using border-radius, and a gentle inner shadow using box-shadow. We also float the field labels left so that they sit alongside the fields. When a field is focused (clicked on or moved to with the Tab key), we give it a blue border and remove the shadow. We also set outline: none to remove the blue outline added by some browsers. Finally, we use the :valid pseudo-class to give correctly completed fields a green background, for those browsers that support HTML5 form validation.
  5. The Send and Cancel buttons
    input[type="submit"] selects the Send Email button, while input[type="button"] selects the Cancel button. We float them right to position them side by side, and add some margin to give them space. We give them a fixed width, and some padding to make them a decent size. We add a rounded border and subtle drop shadow, and specify text and background colours. We also make the buttons slightly transparent (opacity: .7), and make them fully transparent when hovered over to highlight them. We use a CSS transition to fade the opacity slowly. Finally, when the buttons are clicked (:active) we move the shadow inside the buttons to give a “pressed” appearance, and give them a black-on-white colour scheme.

Step 3: Build the PHP form mailer

We’ve now created our form page, and styled the form. The next step is to build a short PHP script to actually send the email messages. This script will reside on the web server. When the user submits the form, the form’s data is sent to the PHP script, which then sends the email and returns a response indicating whether or not the email was sent successfully.

Here’s the PHP script — call it processForm.php, and save it in the same folder as the form page you created in Steps 1 and 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "john@example.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
// If all values exist, send the email
if ( $senderName && $senderEmail && $message ) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
  $headers = "From: " . $senderName . " <" . $senderEmail . ">";
  $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
} else {
?>
<html>
  <head>
    <title>Thanks!</title>
  </head>
  <body>
  <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
  <?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
  <p>Click your browser's Back button to return to the page.</p>
  </body>
</html>
<?php
}
?>

This script is fairly straightforward. Let’s break it down:

    1. Define some constants
      First we define some config options for the name and email address of the person who will receive the email message. (Change these to your own name and email address.) We also set a subject for the message.
    2. Read the form values
      Next we check for our 3 form fields, senderName, senderEmail and message, in the posted form data. For each field, we check if it exists. If it does then we pass its value through a regular expression to remove any potentially malicious characters that a spammer might try to use, and store the result in a variable. If it doesn’t exist then we set the variable to an empty value.
    3. If all values exist, send the email
      If the 3 field values all contain data then we send the email. First we construct the recipient string from the recipient name and email address. Then we add a "From:" header to the message using the name and email address that the visitor entered in the form. This is the “From:” value that the recipient will see in their email program. Finally, we use the PHP mail() function to send the email message, storing the return value in the variable $success. (mail() returns true if it managed to send the email, or false otherwise.)
    4. Return an appropriate response to the browser
      Once we’ve attempted to send the email, we send a “success” or “error” message back to the browser as appropriate. If the request URL contained an "ajax" parameter then we know the form was submitted via Ajax using our JavaScript code, so we simply return the value "success" or "error"to the JavaScript, which will then display an appropriate message to the user. However, if the form was submitted without using Ajax then the user must have JavaScript turned off in their browser. In this situation, we display a more helpful error message in the browser, with instructions to the user to use their Back button to return to the page.Our JavaScript will add the ajax parameter to the URL when it submits the form, as you’ll see in Step 6.

Step 4: Include the jQuery library and set the delay

Our form is actually functional now. You can open the page in a browser, click the “Send us an email” link to jump to the form, fill in the fields, and submit the form to send the message.

However, we’re now going to enhance our form using JavaScript to make the experience nicer for the user.

We’ll use jQuery to do most of the heavy lifting, so the first step is to include the jQuery library in the page’s head element:

1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Here we’ve linked directly to the jQuery library on Google’s CDN, but you can download the library and host it on your own server if you prefer.

We’ll also add a global config variable, messageDelay, to control how long the message boxes appear on the screen. This value is in milliseconds. Feel free to change it to a shorter or longer time:

1
2
3
<script type="text/javascript">
var messageDelay = 2000;  // How long to display status messages (in milliseconds)

Step 5: Write the init() function

The first stage of our form-enhancing JavaScript is the init() function. This sets up the form so that it can be shown and hidden on demand, and also modifies the form so that it will be submitted using our JavaScript, rather than sent natively by the browser.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Init the form once the document is ready
$( init );
// Initialize the form
function init() {
  // Hide the form initially.
  // Make submitForm() the form’s submit handler.
  // Position the form so it sits in the centre of the browser window.
  $('#contactForm').hide().submit( submitForm ).addClass( 'positioned' );
  // When the "Send us an email" link is clicked:
  // 1. Fade the content out
  // 2. Display the form
  // 3. Move focus to the first field
  // 4. Prevent the link being followed
  $('a[href="#contactForm"]').click( function() {
    $('#content').fadeTo( 'slow', .2 );
    $('#contactForm').fadeIn( 'slow', function() {
      $('#senderName').focus();
    } )
    return false;
  } );
  
  // When the "Cancel" button is clicked, close the form
  $('#cancel').click( function() {
    $('#contactForm').fadeOut();
    $('#content').fadeTo( 'slow', 1 );
  } ); 
  // When the "Escape" key is pressed, close the form
  $('#contactForm').keydown( function( event ) {
    if ( event.which == 27 ) {
      $('#contactForm').fadeOut();
      $('#content').fadeTo( 'slow', 1 );
    }
  } );
}

Let’s look at each chunk of the above code:

        1. Init the form once the document is ready
          We use the jQuery object, $, to trigger our init() function once the DOM is ready.
        2. Hide the form, set the submit handler, and position the form
          The first thing we do inside the init() function itself is make some changes to our form, #contactForm.First we hide it from the page using the jQuery hide() method. Then we set its submit event handler to our submitForm() function (which we’ll write in a moment). This ensures that, when the user submits the form, submitForm() is called instead of the native browser form submission kicking in. Finally, we add the positioned CSS class to the form to reposition it in the centre of the browser window.
        3. Make the “Send us an email” links open the form
          Next we bind an anonymous event handler function to the “Send us an email” links’ click events. This function fades out the page content so it’s only just visible in the background; fades the contact form in; and sets the focus on the “Your Name” field, ready for the user to start filling in the form. Finally, the function returns false to prevent the links from being followed.
        4. When the “Cancel” button is clicked, close the form
          Now we bind another anonymous function to the “Cancel” button’s click event, so that the user can close the form by clicking the button. The function simply fades the form out, and fades the page content back in.
        5. When the “Escape” key is pressed, close the form
          Similarly we bind a function to the contact form’s keydown event, so that we can read any key the user presses when they’re viewing the form. In this function, we check if the user has pressed the “Escape” key (character code: 27). If they have then we close the form by fading it out, and fading the content in.

Step 6: Write the submitForm() function

Screenshot of form buttons

We’ve now set up our form so that, rather than being submitted in the usual fashion, it will trigger the submitForm() function when the user submits it. This function needs to do some validation and, if all is well, submit the form data to the PHP script via Ajax.

Here’s the function in full:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Submit the form via Ajax
function submitForm() {
  var contactForm = $(this);
  // Are all the fields filled in?
  if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {
    // No; display a warning message and return to the form
    $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
    contactForm.fadeOut().delay(messageDelay).fadeIn();
  } else {
    // Yes; submit the form to the PHP script via Ajax
    $('#sendingMessage').fadeIn();
    contactForm.fadeOut();
    $.ajax( {
      url: contactForm.attr( 'action' ) + "?ajax=true",
      type: contactForm.attr( 'method' ),
      data: contactForm.serialize(),
      success: submitFinished
    } );
  }
  // Prevent the default form submission occurring
  return false;
}

Here’s how the function works:

        1. Store the contact form in a variable
          Since we’ll be using it a lot throughout the function, we start off by storing the contact form element in a contactForm variable. This element is available to our function as the this variable, since the function is the event handler for the element’s submit event. We wrap the element in a jQuery object to make it easier to work with.
        2. Check all the fields are filled in
          Now we check that each field’s value is not empty by using the jQuery val() method on each field.
        3. Display a warning if the form isn’t completed
          If 1 or more of the fields are empty, we fade out the form, then fade in the #incompleteMessage div, which contains the “Please complete all the fields…” message. We keep the message there for the time specified by the messageDelay variable, then fade it out again. Once it’s faded out, we fade the form back in so that the user can complete it.
        4. Submit the form if it is completed
          Now we get to the meat of the JavaScript. If the form is completed then we first fade out the form, and fade in the “Sending your message…” box. Now we call the jQuery ajax()method to submit the form via Ajax to the PHP script. We pass the following arguments to the method:

          url
          The URL to send the form to. We grab this from the form’s action attribute, and append an ajax=true parameter to the query string so that our PHP script knows the form was sent via Ajax, rather than via the usual method.
          type
          The type of request to make ("POST" or "GET"). We grab this from the form’s method attribute, which in this case is set to "POST".
          data
          The data to send with the request. For this, we call the jQuery serialize() method on the contact form object. This method takes all the field names and values in the form and encodes the data in a query string. We then pass this string to the ajax() method so it can send the data to the PHP script.
          success
          This is a callback function that will be called once the Ajax request has finished and the browser has received the response from the server. We set this to our submitFinished() function, which we’ll write in a moment.
        5. Prevent the default form submission occurring
          Finally, our event handler returns false to prevent the form being submitted in the usual way.

Step 7: Write the submitFinished() function

Screenshot of success message

The last function we need to write is submitFinished(), which is called once the Ajax response from the PHP script has been received by the browser. This function needs to check the response and display a success or error message as appropriate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Handle the Ajax response
function submitFinished( response ) {
  response = $.trim( response );
  $('#sendingMessage').fadeOut();
  if ( response == "success" ) {
    // Form submitted successfully:
    // 1. Display the success message
    // 2. Clear the form fields
    // 3. Fade the content back in
    $('#successMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#senderName').val( "" );
    $('#senderEmail').val( "" );
    $('#message').val( "" );
    $('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
  } else {
    // Form submission failed: Display the failure message,
    // then redisplay the form
    $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#contactForm').delay(messageDelay+500).fadeIn();
  }
}
</script>

The function works as follows:

        1. Get the response
          jQuery passes the response from the PHP script as an argument to the submitFinished() function. We take this string and pass it through the jQuery trim() method to remove any whitespace.
        2. Fade out the “sending” message
          Next we fade out the “Sending your message…” box by calling the jQuery fadeOut() method.
        3. If email was sent successfully, display a success message
          If the response variable holds the string "success", as returned by our PHP script, then we know that the email was successfully queued for delivery. So we fade in the success message, hold it for a couple of seconds, then fade it out. We also reset the form fields to empty values, in case the user wants to send another message. Finally, once the success message has faded out, we fade the page content back in.
        4. If there was a problem, display a failure message
          If the PHP script returned anything other than "success" then we know there was a problem with the submission, so we display the failure message stored in the #failureMessage div, then fade the form back in so that the user can correct any problems with the form.

And that’s the end of our JavaScript!

Summary

We’ve now built our slick Ajax contact form. Not only does it look good, but it’s easy to use, and the visitor can send an email without ever having to leave the page they are reading. Nice!

How to Count Visitors Using PHP & MySQL

June 16, 2012 3 comments

This example tutorial will show how to count visitors by using PHP and MySLQ, you can count all visitor visited your website by ip, hour, minute, date, month, year, page, browser, referrer and it is stored in MySQL. So you can get detail information about your visitors.

Tracking our website’s visitors is a very important step if you’re serious enough about analyzing your traffic and optimizing your pages to get the most of your visitors. There are many reasons why you should think of implementic tracking scripts (it’s crucial to know where your traffic is coming from and where it goes, wha people search, how long they stay etc.), you could increase sales, you could optimize your pages to increase page hits, you could make lots of changes to increase your Adsense profits and the list goes on and on.

Bellow is tutorial how to count visitors using php and MySQL, follow with this step :

First step you need create visitors_table. Copy code bellow and pasted it Query SQL, you will get a table “visitors_table’.

CREATE TABLE `visitors_table` (
`ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`visitor_ip` VARCHAR( 32 ) NULL ,
`visitor_browser` VARCHAR( 255 ) NULL ,
`visitor_hour` SMALLINT( 2 ) NOT NULL DEFAULT '00',
`visitor_minute` SMALLINT( 2 ) NOT NULL DEFAULT '00',
`visitor_date` TIMESTAMP( 32 ) NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`visitor_day` SMALLINT( 2 ) NOT NULL ,
`visitor_month` SMALLINT( 2 ) NOT NULL ,
`visitor_year` SMALLINT( 4 ) NOT NULL ,
`visitor_refferer` VARCHAR( 255 ) NULL ,
`visitor_page` VARCHAR( 255 ) NULL
) TYPE = MYISAM ;

Ok. We have our database ready for storing our visitors info We will need to setup a script which will store the visitor’s info in our database so let’s start writing it. We need the ip address of our visitor so we will get it using the following method.

function getBrowserType () {
if (!empty($_SERVER['HTTP_USER_AGENT']))
{
   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
}
else if (!empty($HTTP_SERVER_VARS['HTTP_USER_AGENT']))
{
   $HTTP_USER_AGENT = $HTTP_SERVER_VARS['HTTP_USER_AGENT'];
}
else if (!isset($HTTP_USER_AGENT))
{
   $HTTP_USER_AGENT = '';
}
if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[2];
   $browser_agent = 'opera';
}
else if (ereg('MSIE ([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'ie';
}
else if (ereg('OmniWeb/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'omniweb';
}
else if (ereg('Netscape([0-9]{1})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'netscape';
}
else if (ereg('Mozilla/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'mozilla';
}
else if (ereg('Konqueror/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'konqueror';
}
else
{
   $browser_version = 0;
   $browser_agent = 'other';
}
return $browser_agent;
}

Here is browser types code:
$visitor_browser = getBrowserType();
Now we need to define hour, minute, day, month and year of visitors:

$visitor_hour = date("h");
$visitor_minute = date("i");
$visitor_day = date("d");
$visitor_month = date("m");
$visitor_year = date("y");

And next we need to find out who is sending us visitors so we can thank them.

$visitor_refferer = gethostbyname($HTTP_REFERER);

So to get the full url of our page we will use this function:

function selfURL() {
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2));
}

Now we have our page, we will store it on a variable:

$visited_page = selfURL();

We need to create a new page which will be used to connect to the database.

It is visitors_connections.php. Copy this code and save it:

$hostname_visitors = "host";
$database_visitors = "database";
$username_visitors = "username";
$password_visitors = "password";

$visitors = mysql_connect($hostname_visitors, $username_visitors,
 $password_visitors) or rigger_error(mysql_error(),E_USER_ERROR);

function getBrowserType () {
if (!empty($_SERVER['HTTP_USER_AGENT']))
{
   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
}
else if (!empty($HTTP_SERVER_VARS['HTTP_USER_AGENT']))
{
   $HTTP_USER_AGENT = $HTTP_SERVER_VARS['HTTP_USER_AGENT'];
}
else if (!isset($HTTP_USER_AGENT))
{
   $HTTP_USER_AGENT = '';
}
if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[2];
   $browser_agent = 'opera';
}
else if (ereg('MSIE ([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'ie';
}
else if (ereg('OmniWeb/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'omniweb';
}
else if (ereg('Netscape([0-9]{1})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'netscape';
}
else if (ereg('Mozilla/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'mozilla';
}
else if (ereg('Konqueror/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT, $log_version))
{
   $browser_version = $log_version[1];
   $browser_agent = 'konqueror';
}
else
{
   $browser_version = 0;
   $browser_agent = 'other';
}
return $browser_agent;
}

function selfURL() {
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}

function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }

function paginate($start,$limit,$total,$filePath,$otherParams) {
    global $lang;

    $allPages = ceil($total/$limit);

    $currentPage = floor($start/$limit) + 1;

    $pagination = "";
    if ($allPages>10) {
        $maxPages = ($allPages>9) ? 9 : $allPages;

        if ($allPages>9) {
            if ($currentPage>=1&&$currentPage<=$allPages) {
                $pagination .= ($currentPage>4) ? " ... " : " ";

                $minPages = ($currentPage>4) ? $currentPage : 5;
                $maxPages = ($currentPage<$allPages-4) ? $currentPage : $allPages - 4;

                for($i=$minPages-4; $i<$maxPages+5; $i++) {
                    $pagination .= ($i == $currentPage) ? "<a href=\"#\"
                    class=\"current\">".$i."</a> " : "<a href=\"".$filePath."?
                    start=".(($i-1)*$limit).$otherParams."\">".$i."</a> ";
                }
                $pagination .= ($currentPage<$allPages-4) ? " ... " : " ";
            } else {
                $pagination .= " ... ";
            }
        }
    } else {
        for($i=1; $i<$allPages+1; $i++) {
        $pagination .= ($i==$currentPage) ? "<a href=\"#\" class=\"current\">".$i."</a> "
        : "<a href=\"".$filePath."?start=".(($i-1)*$limit).$otherParams."\">".$i."</a> ";
        }
    }

    if ($currentPage>1) $pagination = "<a href=\"".$filePath."?
    start=0".$otherParams."\">FIRST</a> <a href=\"".$filePath."?
    start=".(($currentPage-2)*$limit).$otherParams."\"><</a> ".$pagination;
    if ($currentPage<$allPages) $pagination .= "<a href=\"".$filePath."?
    start=".($currentPage*$limit).$otherParams."\">></a> <a href=\"".$filePath."?
    start=".(($allPages-1)*$limit).$otherParams."\">LAST</a>";

    echo '<div>' . $pagination . '</div>';
}

Now we have all the details information for store in MySQL,  So we need to write them into our database. We will create a new file called “visitor_tracking.php” and include it in every page that we want to track:

require_once('visitors_connections.php');//the file with connection code and functions
//get the required data

$visitor_ip = GetHostByName($REMOTE_ADDR);
$visitor_browser = getBrowserType();
$visitor_hour = date("h");
$visitor_minute = date("i");
$visitor_day = date("d");
$visitor_month = date("m");
$visitor_year = date("Y");
$visitor_refferer = GetHostByName($HTTP_REFERER);
$visited_page = selfURL();

//write the required data to database
mysql_select_db($database_visitors, $visitors);
$sql = "INSERT INTO visitors_table (visitor_ip, visitor_browser, visitor_hour,
 visitor_minute, visitor_date, visitor_day, visitor_month, visitor_year,
 visitor_refferer, visitor_page) VALUES ('$visitor_ip', '$visitor_browser',
 '$visitor_hour', '$visitor_minute', '$visitor_date', '$visitor_day', '$visitor_month',
 '$visitor_year', '$visitor_refferer', '$visitor_page')";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);

To display information detail about visitors, we need to create a new page called “display_visits.php”

Go to create new page PHP and then copy code bellow and save it.

require_once('visitors_connections.php');//the file with connection code and functions

if ($_GET['start'] == "") $start = 0;
else $start = $_GET['start'];
$limit = 15;

$additionalQuery = "SQL_CALC_FOUND_ROWS ";

mysql_select_db($database_visitors, $visitors);
$query_visitors = "(SELECT ".$additionalQuery." * FROM visitors_table WHERE";

if ($_POST['day']!="") {
$query_visitors .= " visitor_day = '".$_POST['day']."'";
} else {
$query_visitors .= " visitor_day = ".date("d")."";

if ($_POST['month']!="") {
$query_visitors .= " AND visitor_month = '".$_POST['month']."'";
} else {
$query_visitors .= " AND visitor_month = ".date("m")."";
}

if ($_POST['year']!="") {
$query_visitors .= " AND visitor_year = '".$_POST['year']."'";
} else {
$query_visitors .= " AND visitor_year = ".date("Y")."";
}}
$query_visitors .= " LIMIT $start,$limit)";
$insert_visitors = mysql_query($query_visitors, $visitors) or die(mysql_error());
$row_visitors = mysql_fetch_assoc($insert_visitors);
$totalRows_visitors = mysql_num_rows($insert_visitors);

$nbItems = mysql_result(mysql_query("Select FOUND_ROWS() AS nbr"),0,"nbr");
if ($nbItems>($start+$limit)) $final = $start+$limit;
else $final = $nbItems;

echo '<table style="width:100%; border:1px dashed #CCC" cellpadding="3">
      <form id="form1" name="form1" method="post" action="display_visits.php">
       <tr>
        <td>day
        <select name="day" id="day">
          <option value="" selected="selected"></option>
          <option value="01">01</option>
          <option value="02">02</option>
          <option value="03">03</option>
          <option value="04">04</option>
          <option value="05">05</option>
          <option value="06">06</option>
          <option value="07">07</option>
          <option value="08">08</option>
          <option value="09">09</option>
          <option value="10">10</option>
          <option value="11">11</option>
          <option value="12">12</option>
          <option value="13">13</option>
          <option value="14">14</option>
          <option value="15">15</option>
          <option value="16">16</option>
          <option value="17">17</option>
          <option value="18">18</option>
          <option value="19">19</option>
          <option value="20">20</option>
          <option value="21">21</option>
          <option value="22">22</option>
          <option value="23">23</option>
          <option value="24">24</option>
          <option value="25">25</option>
          <option value="26">26</option>
          <option value="27">27</option>
          <option value="28">28</option>
          <option value="29">29</option>
          <option value="30">30</option>
          <option value="31">31</option>
        </select></td>
        <td>Month
        <select name="month" id="month">
          <option value="" selected="selected"></option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
          <option value="7">7</option>
          <option value="8">8</option>
          <option value="9">9</option>
          <option value="10">10</option>
          <option value="11">11</option>
          <option value="12">12</option>
        </select></td>
        <td>Year
        <select name="year" id="year">
          <option value="" selected="selected"></option>
          <option value="2007">2007</option>
        </select></td>
        <td><input type="submit" name="Submit" value="Submit" /></td>
        <td></td>
       </tr>';

echo '<tr>
        <td style="width:15%;border-bottom:1px solid #CCC">IP</td>
        <td style="width:15%;border-bottom:1px solid #CCC">Browser</td>
        <td style="width:15%;border-bottom:1px solid #CCC">Time</td>
        <td style="width:30%;border-bottom:1px solid #CCC">Refferer</td>
        <td style="width:25%;border-bottom:1px solid #CCC">Page</td>
       </tr>';

do {

echo '<tr onmouseout="this.style.backgroundColor=\'\'"
      onmouseover="this.style.backgroundColor=\'#EAFFEA\'">
        <td>'.$row_visitors['visitor_ip'].'</td>
        <td>'.$row_visitors['visitor_browser'].'</td>
        <td>'.$row_visitors['visitor_hour'].':'.$row_visitors['visitor_minute'].'</td>
        <td>'.$row_visitors['visitor_refferer'].'</td>
        <td>'.$row_visitors['visitor_page'].'</td>
       </tr>';
} while ($row_visitors = mysql_fetch_assoc($insert_visitors));
paginate($start,$limit,$nbItems,"display_visits.php","");

There’s only one small step to do and we’re ready to see some results. We need to include the following line in every page that we need to track results for:

include('visitor_tracking.php');

To see the results please call page “display_visits.php” in your browser. Ok now I’m testing it, it works fine, I hope you will find it useful somewhere in your website. Good Luck…!

Display Contents of Different File Formats Word/Excel/Powerpoint/PDF/RTF as HTML

HTML 4.01 vs HTML 5 illustrated

HTML 4.01 vs HTML 5 illustrated (Photo credit: Glutnix)

This is a typical problem which I also raised on Stack Overflow (http://stackoverflow.com/questions/11061929/php-extract-text-from-different-file-formats-word-excel-powerpoint-pdf-rtf#comment14475398_11061929), but there seemed no single resource around the web to solve this particular problem, so since I have solved it I thought it would make sense to provide an approach and a solution, it can be refined better with time

Problem: We have a web application that allows different users to upload different files to share with others, the file types are limited. However just before downloading a file, the user needs to see a preview of the file contents, which is where it becomes tricky since each  file type is different.

Approach:

1. Identify the extension of each file

2. Display the text or HMTL from each file using the appropriate library for the file type, since there is no unified library

The base class is https://gist.github.com/2941076 which requires the path to the file and the extension (since the extension is already stored in the database I do not try to extract it from the file)

The libraries used for the different types of files are the key to the solution:

1. MS Word Documents – LiveDocx Service within Zend Framework (http://www.phplivedocx.org/2009/08/13/convert-docx-doc-rtf-to-html-in-php/) the steps are:

– Create a Mail Merge Document using the word document as a template

– Connect to the LiveDocx service (here you need SOAP and SSL enabled on your local LAMP installation)

– Save the generated document, and render it as HTML

2. MS Excel – PHPExcel from Codeplex so simple its scary (http://phpexcel.codeplex.com)

– Create a PHP Excel class to read the file

– Create an HTML writer to render the HTML

– Save the HTML to a file and read its contents

3. PDF text extract – http://pastebin.com/hRviHKp1 

– Create an instance of the PDF2Text class holding a reference to the PDF file

– Decode the PDF which extracts the text out of the file

d) Powerpoint – Work in Progress to be added later

More as I work in the power point extractions

Explore the REST API

April 12, 2012 1 comment

I have had the pleasure of working with the WordPress.com REST API over the past few weeks and am very excited to start “dogfooding” this resource everywhere I can.

One cool feature is that all the endpoints are self-documenting. In fact, the documentation for the REST API is built by the API itself! With this information we were able to build a console to help debug and explore the various resources that are now available through the new API. So let me introduce you to the new REST console for WordPress.com.

A word of caution: the console is only available when you are logged into WordPress.com and is hooked up to the live system, so be careful with your POST requests!

At its simplest you can supply the method, path, query, and body for the resource you wish to examine (it’s pre-populated with /me). Press “Submit” to see the response status for your request and an expandable JSON object that you can explore. All links listed under meta are active, so click one to make another request.

To get a better idea of what kind of parameters a request can take, select it under the “Reference” section. It will then provide an interface with some contextual help to let you know which path, query, and body parameters it accepts, what each of those parameters are for, and a field for you to provide the value.

Driving Traffic To Your Website

April 10, 2012 1 comment

eMarketing and SEO (Search Engine Optimization)

People need to know who you are, and the products and services that you provide. This is accomplished in four strategic areas:

  1. SEO (Search Engine Optimization)
  2. Online advertising
  3. Links from other websites or Blogs
  4. Social Networks

SEO (Search Engine Optimization) is a way of adding strategic content to your webpages. These are keywords or phrases that pertain to your products or services. They may also be relevant to any value content that you provide, such as “how to guides”, video, white papers, etc. We’ll cover these later when we discuss capturing leads.

SEO is a process, not a one time job. It needs to be monitored and changed as needed. The goal is to raise your search engine rankings.

SEO is also about good coding, tags, and metadata. These elements are not seen, but are used by search engines to return SERP’s (Search Engine Result Pages) to Internet searches. This is what we call “organic” drivers, or a kind of “free advertising”. Basically relevant content and code for internet searches.

Incoming links from other websites are also very important, and rated highly among search engines. We will show you how to obtain more incoming links from larger websites.

Online advertising is crucial to the success of any eMarketing strategy. This is paid advertising with the major or local search engines such as Google, Yahoo, MSN, AOL, etc. Many large companies have full departments dedicated to creating and tracking online advertising campaigns. Online advertising is much more than creating an ad and letting it go. You can waste a lot of money if you don’t properly define your campaign, test it, and than track results. This requires constant monitoring and adjustment to maximize your investment and results.

A Sturm Media online advertising campaign consists of:

  • Analysis of competition online advertising
  • Development of keywords and phrases
  • Creation of a landing pages with “Call to Action” (CTA)
  • Ad copy for three test ads
  • Automated lead capture and follow-up

Advertising can also be negotiated with other large websites that have extremely high traffic counts, or media buys for banner placement on groups of web pages or high traffic blogs. This is usually more expensive and done as a phase two or three implementation, after several successful search engine campaigns.

Links from other websites or blogs are not only important for SEO and search engine ranking, but as a direct connection to your website. A question we get often is how can we get more links to our website? The answer to the question is simple, but the implementation is not. Content, content, content… content is king and everyone wants it. Once you have compelling value content, you will see links from other websites and blogs increase.

Sturm Media has a proprietary blog creation tool that aggregates data in any targeted vertical. We can create blogs that augment advertising campaigns, and provide additional incoming links. The blogs are completely independent, and as such can provide company reviews and resource guides that promote our clients. This is our competition killer, and since we developed the methodology, we are the preeminent source for this type of online marketing.

Social Networking is popular and growing at exponential rates. Websites like Facebook, Linkedin, YouTube, Twitter, and many more are a way to reach hundreds of thousands of potential customers. Often, our clients think that they don’t have the time or the bandwidth for this type of marketing. We can show ways of implementing social networking into your plan that will take very little time. Social networking is a vital component of any strategic eMarketing plan.

How to analyze your Blog Traffic using WordPress Stats API

April 9, 2012 3 comments

Wordpress Template Hierarchy. עברית: היררכית ה...

Analyzing my blog traffic is one of my favorite past times. Seeing traffic surge and strangers using my posts gives me gratification. Initially, my analysis was fairly low tech – checking WordPress stats page periodically. After doing it a few times, I realized I could do more methodically – and I can use the statistics to do some rudimentary data mining.

As you know, I have a WordPress.com blog. WordPress exposes the statistics in two ways : As a flash chart in the dashboard and as API service.
Viewing Blog Stats – Low Tech Way

If you want to take a look at your blog’s stats today , then you can do it in the dashboard. Assuming you are logged into your WordPress login, go to your blog. You will see WordPress toolbar at the top of the page. Click “My Dashboard“. It will show a chart of total daily visits for the past 15 days. If you want more details, hover your mouse over “My Account” and select “Stats”.

This page shows a wealth of information about your blog but it is limited to 2 days – today and yesterday. There are atleast 6 important statistics in that page.
WordPress Stats Sections

a) Views Per Day
This is probably the statistic you are most interested in. This plots the total number of visits each day for the last 30 days. This also has multiple tabs which allows you to aggregate the statistics information. For example you can view the total weekly and monthly visits . This gives a basic view about how your blog is faring.

b) Referrers
Referrers are basically web pages from which visitors reached your blog. There are different types of referrers : pingbacks, related posts, explicit linking etc. If a certain website is driving lot of visitors to your blog , it is time to notice ! Referrers allows you to get that insight. This panel shows the top 10 referrers. You can click on the “Referrers” link to get the full listing.

c) Top Posts and Pages
This shows the top 10 posts for the given day. One interesting thing is that they track home page separately. Also if you have different pages (eg About), then visits to these pages are also tracked. Again, if you want to see the number of visits to each page, you can click on the title link.

One interesting thing is that each of the posts/pages in this section also has an addition chart icon near them. Clicking on them gives the stats for that particular post alone. The new page shows a chart detailing how many visits occurred to that page in the last few weeks. Most interestingly , they also show the average visits per day for the last few weeks and months. This gives a glimpse into the lasting popularity of your post.

d) Search Engine Terms
I am not very clear what this exactly means – The instruction says “These are terms people used to find your blog.” . I am not sure if this corresponds to search terms typed in search engines or in WordPress search boxes etc . Anyway, this panel gives information about the search terms that fetch visits to your blog.

e) Clicks
Clicks panel shows the list of links in your blog that your visitors clicked. In a way , you can consider it as an inverse of referrers. In this case, you act as a referrer for some other blog. This post gives some hints about the type of visitors to your blog.

f) Aggregate Statistics
There is also another panel that shows some aggregate stats. This shows the total number of views to your blog so far , number of blogs and posts , email subscribers etc.
A Better Way

Using WordPress Stats page to get your data is fairly low tech. This gives some data which can only give you an instinct of how things go. But it will not give you any deeper insights. For doing more data mining, you need data – lots of data. Fortunately, WordPress makes available a stats API which you can query to get regular data. In the rest of the post , we will talk about the API and how to use the data that you get out of it.
Using WordPress Stats API

The primary url which provides the stats is http://stats.wordpress.com/csv.php . You can click on it to see the required parameters. There are 4 important parameters to this API.

a) api_key : api_key is a mandatory parameter and ensures that only owner queries the website. There are three ways to get this information. This key is emailed to you at the time you created your blog. Or you can access it at My Dashboard -> Users -> Personal Settings. This will show your api key. For the truly lazy click this url .

b) blog_id : This is a number which uniquely identifies your blog. Either blog_id or blog_uri is mandatory. I generally prefer blog_id. Finding blog_id is a bit tricky. Go to the blog stats page (My Account -> Stats). Click on the title link of “Top Posts and Pages”. This will open a new page which shows the statistics for last 7 days. If you look at the page’s url, it will have a parameter called blog. The value of this parameter is the blog_id . Atleast for my blog , it is a 8 digit number.

c) blog_uri : If you do not want to take all the trouble of getting blog_id , use blog_uri. This is nothing but the url of your blog (http://blah.wordpress.com).

d) table : This field identifies the exact statistic you want. One of views, postviews, referrers, searchterms, clicks. Each of these correspond to the sections of WordPress stats discussed above. If table is not specified , views is selected as the default table.

You can get more details from the stats API page given above.
Sample Python Scripts to fetch WordPress Stats

I have written a few scripts which fetch each of the WordPress stats. One of them run every hour and gets the total number of views so far for the whole blog. The other scripts runs once a day and fetch the total clicks, search terms, referrer and top posts for that day. All of these store the data as a csv file which lends itself to analysis.

If you are interested in the scripts , the links to them are :

1. getBlogDaysStats.py : Fetches the total views for the whole blog at the current time. For best results run every hour.
2. getBlogReferrers.py : Fetches all the referrers to your blog.
3. getBlogPostViews.py : Fetches the number of views for individual blog posts and pages.
4. getBlogSearchTerms.py : Fetches all the search terms used to find your blog today.
5. getBlogClicks.py : Fetches the urls that people who visited your blog clicked.
How to Collect WordPress Statistics

The first step is of course to collect data periodically. I use cron to run the scripts. My crontab file looks like this :

11 * * * * /usr/bin/python scriptpath/getBlogDaysStats.py
12 0 * * * /usr/bin/python scriptpath/getBlogClicks.py
14 0 * * * /usr/bin/python scriptpath/getBlogPostViews.py
15 0 * * * /usr/bin/python scriptpath/getBlogReferrers.py
16 0 * * * /usr/bin/python scriptpath/getBlogSearchTerms.py

Basically, I run the getBlogDaysStats every hour and other scripts every day. I also run the rest of scripts at early morning so that it fetches the previous day’s data.
How to Use WordPress Statistics

If you run the scripts for few days, you will have lot of data. The amount of analysis you can make is limited only by your creativity. In this section, I will tell some of the ways I use the stats instead of giving an explicit how-to.

1. Views per day : It is collected by getBlogDaysStats.py. The most basic stuff is to chart them. This will give a glimpse of your trend – If it is static or climbing, then good news. If it is falling down it is something to worry about. I must also mention that have a more or less a plateau in your chart happens often. For eg in my blog, the charts follow a pattern – It increases for quite some time , then stays at the same level for a long time and then increases again. Also , worrying about individual day’s statistics is not a good idea. Try to aggregate them into weekly and monthly values as they give a less noisy view of your blog traffic.

Another common thing to do is to analyze per hour traffic. This can be easily derived from the output of the script. Basically, if m is the number of views at time a and n is the number of views at time b , then you received n-m views in b-a hours. I usually calculate it for every hour. This gives a *basic* idea of peak time for your blog – You can also infer your primary audience , although the interpretation is ambiguous. As an example , I get most of my traffic at night – especially between 1 AM – 9 AM. Morning time traffic is pretty weak and it picks up again in the evening. Interpreting this is hard as my blog covers a lot of topics – but if your blog is more focused you learn a lot about your visitors.

2. Referrers : This is a very useful statistic if you do some marketing for your blog. For best results, you may want to use just the domain of the url instead of the whole url for analysis. Using it you can figure out which sites drive traffic to your blog. If it is another blog, then it is a good idea to cultivate some friendship with that blog’s owner. For eg, for my blog , I found that digg drives more traffic that reddit. Also facebook drives some traffic to my blog – so I use WordPress’s facebook publicize feature. I also find that I get some traffic due to WordPress’s related posts feature which means that I must use good use of categories and tags. Your mileage may vary but I hope the basic idea is clear.

3. Individual Post Views : This is probably the most useful set of statistics. Basically , it allows you to analyze the traffic of individual posts over a period of time. I have a file which associates a blog post with extra information : For eg it stores the categories, tags, original creation date, all modification dates etc. (If you are curious , I store the information in JSON format). Once you have this information lot of analysis is possible.

a. You can figure out your audience type. If for a post, you have lot of audience in the first week and almost no audience from then on – then most likely your audience is driven by subscription. If it keeps having a regular traffic, then probably it has some useful stuff and traffic is constantly driven to it by search engines. For eg, my Biweekly links belong to the first scenario : When I publish one, lot of people visit it and then after a few days it gets practically no visits. In the other case, my post of Mean Shift gets a steady stream of views every week. If you want to sustain a good viewership, you may want to write more posts which can attract long term views.

b. If you use categories and tags wisely, you can tally the number of views per each category. This will give you an idea of the blog posts which users prefer. I noticed that my audience seems to like my Linux / Data Mining posts than other categories. So it is a good idea to write more of those posts.

c. You can kind of see a pareto effect in your blog posts. For eg, my top 10 blogs account for atleast 70% of my blog traffic. So if I could identify them correctly, I can write lesser posts but still maintain my blog traffic 😉

You can do lot more than these simple analysis but this is just a start.

4. Search Terms : This is another neat statistic. You can use it to figure out the primary way in which users access your blog. For eg, the ratio of total blog post view for a day and number of search terms for the day is quite interesting. If the ratio is high, then most of the people find your blog using search engines. In a way , this a potential transient audience whom you can convert to regular audience. If the ratio is small , then your blog gets views by referrers and regular viewers. This will assure you a steady audience , but it is slightly hard to get new people “find” your blog.

This statistic also tells you which keywords the viewers use to find my blog. You can gleam lot of interesting things from this. For eg, almost all of my search terms are 3-5 words long and usually very specific. This either means that the user is an expert and has crafted specific query. It may also mean that user rewrote the query and my blog was not found in the general query. I also use the terms to figure out if the user would have been satisfied with my blog. For eg, I know that a user searching “install matlab to 64-bit” will be satisfied while some one who searches “k means determine k” will not be. You can do either of two things : augment your blog post to add information that users are searching , or point users to resources that satisfies their query. For eg, I found lot of people reached my blog searching for how to find k. I found geomblog had couple of good posts on it and updated my blog to link to these posts. Some times, I may add a FAQ if same search query comes multiple times and if my page contains the information but is obscure. Eg : lot of people reached my blog searching for Empathy’s chat log location. My post of Empathy had it but not in a prominent fashion. So I added a FAQ which points the answer immediately.

5. Clicks : This statistic is tangentially useful in finding out which links the user clicks. One way I use it is to gauge the “tech” level of my reader who visits my blog using search engines. I usually link to Wikipedia articles for common terms. If the user clicks on these basic terms often ,then it might mean that I write articles at a level higher that the typical user and I have to explain it better. For eg , in my post of K-Means , this was the reason I explain supervised and unsupervised learning at the start even though most people learning k-means already know it.
Other Resources for Blog Traffic

There are other locations that give some useful information about your traffic. Some of them are :

a. Google Web Master Site : This is arguably one of the most comprehensive information about your blog post’s performance in Google. You can see it a Google Webmaster Page -> Your site on web -> Search queries. It has information like impressions, click throughs, average position etc. You can download all of them in a csv file too ! Literally a gold mine for data lovers.
b. Feedburner : Even though, WordPress has a feed, I switched to FeedBurner. One of the main reason was that it gave me a csv file detailing the number of views by my subscribers.
c. Quantcast : Useful for aggregate information. It has multiple charts that detail the number of views, unique visitors etc. The Quantcast data might not be accurate as it is usually estimated – but it gives a broad gauge of your blog. It also has some statistic which says how many of your visitors are addicts , how many are pass throughs etc. Quite useful !
d. Alexa : Similar to Quantcast . I primarily use my Alexa Rank for motivation to improve my blog ranking.
Pivot Tables

I primarily use Python prompt to play with data. If you are not comfortable with programmatic tweaking, use spreadsheets to do these analysis. If you have Windows, you can do lot of powerful analysis by importing the statistics obtained by the scripts into Microsoft Excel. Excel has a neat feature called Pivot tables. It is also an advanced topic that I will not discuss here. You can do some fantastic analysis using pivots. They also give you the ability to view the same data from multiple perspectives.

In this post, I have barely scratched the surface – You can do lot of amazing analysis using WordPress Stats API . I will talk about more complex analysis in a later post. Have fun with the data !

Mobypicture Photo post with API method php

March 27, 2012 4 comments
Image representing Mobypicture as depicted in ...

Image via CrunchBase

include(/*‘api.php’);
$mp = new Mobypicture;
$result = $mp->postMediaUrl(‘imagename,’username‘, ‘password‘);
$result = $mp->postMedia();
print_r($result);

 

====================================================
API .php
===============================================================
<?php

/**
* A Mobypicture API class
*
* @author Andreas Creten/madewithlove
* @version 1
**/
class Mobypicture {
/**
* The MobyPicture API key
**/
static $api_key = ‘zkFcHG1hpSqL4Xb2’;

/**
* The MobyPicture API Location
**/
static $api_location = ‘https://api.mobypicture.com/&#8217;;

/**
* Upload media to MobyPicture
*
* @param string $image The image to be uploaded
* @param string $username The username of the uploader
* @param string $password The p
* @param string $description
* @param array $tags  Tags for the image
* @param string $location
* @param array $hashtags
* @param array $services
* @return mixed
* @author Andreas Creten
**/
public function postMedia($image, $username, $password, $title = null, $description = null, $tags = array(), $location = null, $hashtags = array(), $services = array()) {
// Call the postMedia method on thw MobyPicture API
$response = $this->api_call(‘postMedia’, array(
‘i’ => $image,
‘u’ => $username,
‘p’ => $password,
‘t’ => $title,
‘d’ => $description,
‘tags’ => implode(‘,’, $tags),
‘latlong’ => $location,
‘ht’=> implode(‘,’, $hashtags),
‘s’ => implode(‘,’, $services)
));

// Parse the response of the MobyPicture API
if($response->result) {
print_r();
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return $response;
}
else {
// This needs more detailed error messages
return false;
}
}
}

/**
* Upload media to MobyPicture
*
* @param string $image The image to be uploaded
* @param string $username The username of the uploader
* @param string $password The password of the uploader
* @param array $tags Tags for the image
* @return mixed
* @author Andreas Creten
**/
public function postMediaUrl($image, $username, $password) {

// Call the postMedia method on thw MobyPicture API
$response = $this->api_call(‘postMediaUrl’, array(
‘i’ => $image,
‘u’ => $username,
‘p’ => $password
//’tags’ => implode(‘,’, $tags)
));

print_r($tags);
exit;
// Parse the response of the MobyPicture API
if($response->result) {

if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return $response;
}
else {
// This needs more detailed error messages
return false;
}
}
}

/**
* Get the thumbnail url for an image on MobyPicture
*
* @param string $tinyurl The tinyurl or tinyurl code for of picture
* @param string $size The size of the needed thumbnail (thumbnail, small or medium)
* @return mixed
* @author Andreas Creten
* @todo
**/
public function getThumb($tinyurl, $size = ‘thumbnail’) {
// Try to remove the crap out of the tiny url
$tinyurl_code = $this->tinyurl_to_tinyurl_code($tinyurl);

// Call the getThumbUrl method on thw MobyPicture API
$response = $this->api_call(‘getThumbUrl’, array(
‘t’ => $tinyurl,
‘s’ => $size
));

// Parse the response of the MobyPicture API
if($response->result) {
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return $response;
}
else {
// This needs more detailed error messages
return false;
}
}
}

/**
* Get the thumbnail url for an image on MobyPicture
*
* @param string $tinyurl The tinyurl or tinyurl code for of picture
* @param string $size The size of the needed thumbnail (thumbnail, small or medium)
* @return mixed
* @author Andreas Creten
**/
public function getThumbUrl($tinyurl, $size = ‘thumbnail’) {
// Try to remove the crap out of the tiny url
$tinyurl_code = $this->tinyurl_to_tinyurl_code($tinyurl);

// Call the getThumbUrl method on thw MobyPicture API
$response = $this->api_call(‘getThumbUrl’, array(
‘t’ => $tinyurl,
‘s’ => $size
));

// Parse the response of the MobyPicture API
if($response->result) {
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return $response;
}
else {
// This needs more detailed error messages
return false;
}
}
}

/**
* Get the info of an image on MobyPicture
*
* @param string $tinyurl The tinyurl or tinyurl code for of picture
* @return mixed
* @author Andreas Creten
**/
public function getMediaInfo($tinyurl) {
// Try to remove the crap out of the tiny url
$tinyurl_code = $this->tinyurl_to_tinyurl_code($tinyurl);

// Call the getThumbUrl method on thw MobyPicture API
$response = $this->api_call(‘getMediaInfo’, array(
‘t’ => $tinyurl
));

// Parse the response of the MobyPicture API
if($response->result) {
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return $response;
}
else {
// This needs more detailed error messages
return false;
}
}
}

/**
* Check an account on MobyPicture
*
* @param string $username
* @param string $pin The password of the user
* @return mixed
* @author Andreas Creten
**/
public function checkCredentials($username, $pin) {
// Call the createUser method on the MobyPicture API
$response = $this->api_call(‘checkCredentials’, array(
‘u’ => $username,
‘p’ => $pin
));

// Parse the response of the MobyPicture API
if($response->result) {
//log_r($response);
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return true;
}
else {

return $response;
}
}
}

/**
* Post a comment on MobyPicture
*
* @param string $username Username (can be a Twitter username)
* @param string $pin PIN or password
* @param string $name Name (not used in case an username has been supplied)
* @param string $email Email (not used in case an username has been supplied)
* @param string $tinyurl The tinyurl or tinyurl code for of picture
* @param string $message
* @param string $tweet Tweets this comment on Twitter if possible with the supplied credentials
* @return mixed
* @author Andreas Creten
**/
public function postComment($username, $pin, $name, $email, $tinyurl, $message, $tweet = 0) {
// Try to remove the crap out of the tiny url
$tinyurl_code = $this->tinyurl_to_tinyurl_code($tinyurl);

// Call the createUser method on thw MobyPicture API
$response = $this->api_call(‘postComment’, array(
‘u’ => $username,
‘p’ => $pin,
‘name’ => $name,
’email’ => $email,
‘tinyurl_code’ => $tinyurl_code,
‘message’ => $message,
‘tweet’ => $tweet
));

// Parse the response of the MobyPicture API
if($response->result) {
//log_r($response);
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return true;
}
else {

return $response;
}
}
}

/**
* Create a new account on MobyPicture
*
* @param string $tinyurl The tinyurl or tinyurl code for of picture
* @return mixed
* @author Andreas Creten
**/
public function getComments($tinyurl) {
// Try to remove the crap out of the tiny url
$tinyurl_code = $this->tinyurl_to_tinyurl_code($tinyurl);

// Call the createUser method on thw MobyPicture API
$response = $this->api_call(‘getComments’, array(
‘tinyurl_code’ => $tinyurl_code
));

// Parse the response of the MobyPicture API
if($response->result) {
//log_r($response);
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return true;
}
else {

return $response;
}
}
}

/**
* Create a new account on MobyPicture
*
* @param string $username
* @param string $pin The password for the new user
* @param string $email
* @param string $firstname
* @param string $lastname
* @param string $country
* @param string $keepposted
* @param string $agreeterms
* @return mixed
* @author Andreas Creten
**/
public function createUser($username, $pin, $email, $firstname, $lastname, $country, $keepposted, $agreeterms) {
// Call the createUser method on thw MobyPicture API
$response = $this->api_call(‘createUser’, array(
‘username’ => $username,
‘pin’ => $pin,
’email’ => $email,
‘firstname’ => $firstname,
‘lastname’ => $lastname,
‘countryid’ => $country,
‘keepposted’ => $keepposted,
‘agreeterms’ => $agreeterms
));

// Parse the response of the MobyPicture API
if($response->result) {
//log_r($response);
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return true;
}
else {

return $response;
}
}
}

/**
* Search posts on MobyPicture
*
* @param string $terms Specifies for which words to search
* @param string $items_per_page Amount of posts to show on each page (default: 10)
* @param string $current_page The current page (default: 1)
* @param string $fields  Specifies in what fields to search (‘title’, ‘description’ or ‘both’, default: both)
* @param array $tags Look for one or more tags
* @param string $username Only return postings from the specified username
* @param string $sort_by Sort the results based on this field
* @param string $order Specifies in which direction sorting should be done
* @param string $country Only return postings from the specified country (ISO3166 code2)
* @param string $city Only return postings from the specified city
* @return mixed
* @author Andreas Creten
**/
public function searchPosts($terms, $items_per_page = 10, $current_page = 1, $fields = ‘both’, $tags = array(), $username = null, $sort_by = null, $order = null, $country = null, $city = null) {
// Call the createUser method on thw MobyPicture API
$response = $this->api_call(‘searchPosts’, array(
‘searchTerms’ => $terms,
‘searchItemsPerPage’ => $items_per_page,
‘searchPage’ => $current_page,
‘searchIn’ => $fields,
‘searchUsername’ => $lastname,
‘searchTags’ => implode(‘,’, $tags),
‘searchSortBy’ => $sort_by,
‘searchOrder’ => $order,
‘searchGeoCity’ => $city,
‘searchGeoCountry’ => $country
));

// Parse the response of the MobyPicture API
if($response->result) {
//log_r($response);
if(isset($response->result[‘code’]) && $response->result[‘code’] == 0) {
return true;
}
else {

return $response;
}
}
}

/**
* Do a call to the MobyPicture API
*
* @param string $method The method to be called
* @param array $arguments The arguments for this call
* @return SimpleXMLObject The MobyPicture response
* @author Andreas Creten
**/
private function api_call($method, $arguments) {

// Check which type of method it is (postMedia requers another type of handling)
if($method == ‘postMedia’) {
// Initialize the curl session
$ch = curl_init();

// Set the target url
curl_setopt($ch, CURLOPT_URL, self::$api_location);

// Enable post
curl_setopt($ch, CURLOPT_POST, 1);

// Enable return transfer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Create the arguments array
$arguments = array_merge($arguments, array(
‘k’      => self::$api_key,
‘action’ => $method,
‘format’ => ‘xml’
));

// Load the image file
$arguments[‘i’] = ‘@’.$arguments[‘i’] ;

// Add the arguments to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);

// Execute the curl request
$result = curl_exec($ch);

// Close curl
curl_close($ch);

print_r($result);

// Return the response as an SimpleXML object
return simplexml_load_string($result);
}
else {
// Compose the target URL
$url = sprintf(self::$api_location.’?action=%s&k=%s&format=xml&%s’, $method, self::$api_key, http_build_query($arguments));

// Return the response as an SimpleXML object
return simplexml_load_file($url);
}
}

/**
* Transform a Mobypicture tinyurl into a tinyurl_code
*
* @param string $tinyurl The tinyurl for the picture
* @return string The tinyurl code for the picture
* @author Andreas Creten
**/
private function tinyurl_to_tinyurl_code($tinyurl) {
// Try to remove the crap out of the tiny url
$tinyurl = str_replace(‘http://mobypicture.com/?&#8217;, ”, $tinyurl);
$tinyurl = str_replace(‘http://www.mobypicture.com/?&#8217;, ”, $tinyurl);
$tinyurl = str_replace(‘http://moby.to/&#8217;, ”, $tinyurl);

return $tinyurl;
}
}

?>