Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Guidelines for Mobile Web Development


Good thing about mobile web development is that as a developer or a designer, you won’t have to make an extra effort to learn something out of the blue as far as technology is concerned, in order to develop a mobile website design. All you need to have is a whole new perspective regarding designing of the mobile website. Today, in this article I am aiming to sum up the most important guidelines for mobile web development in a simpler way. So here goes:


1. Initiate with Analytics:
It is extremely important to analyze a certain points regarding your mobile users’. To start off with, review the stats of your OS. This will help you in analyzing the important and most visited web pages of your website. You will also get to know the country/city you are driving the most traffic from. Apart from analyzing the top pages visited by users’, make sure you check the keywords being used in order to get an access to your site. These analytics will help you a lot in your mobile development and will definitely bring positive results.


2. Visitors profiling:
Mobile users are bound to have different needs altogether in comparison with desktop users. While developing and designing your mobile website, make sure you put yourself in the mobile user’s shoes. If your target audience is teenager, they will always be on the go so your website should be easy enough to use while driving, shopping or any other activity. Analyzing audience profile is indeed helpful in mobile web development.


3. Minimize the usage of images: 
In general, images take a lot of time to load because of their large sizes. As a developer and designer, you must keep in mind that mobile users are often using slow internet connections and their connections cannot handle download of heavy images. So, this is one good reason to avoid usage of images.

Each image will require a new HTTP connection and because of the latency it has, it will further slow down the loading of the page.
 
Sizing of the images for all kinds of devices can be very difficult due to the different resolutions. You are inviting a whole new lot of effort by including a lot of imagery in your mobile website.
 
Still, if you really desire to use images in your website, make sure you use CSS Sprite because it helps in time reduction of loading.


4. Do not rely on JavaScript:
Different mobiles will support different browsers and if you are developing a website to accommodate all of the browsers, you should not rely on JavaScript because mobile browsers are not very good with supporting JavaScript. Apart from this, mini browsers such as opera mini, also provide poor support to JavaScript resulting into a poor outcome. This issue is expected to get resolved in coming years thanks to Apple, Android and Blackberry devices.

While you are developing/designing a mobile website, make sure you avoid fly-outs and drop-downs in your website. This is a good thing but only for desktop websites since a user is able to move the cursor over any tab to view the drop down.  It would be a good idea if you do not use this thing at all.


5. Optimizing Download Speed:
As mentioned earlier, JavaScript is not a reliable thing and if you want to increase the downloading speed of your website minify the JavaScript and CSS and it will automatically improve the downloading speed of your website. Also, minifying JavaScript and CSS should not be a difficult task so there should be no excuses for doing this.


6. Horizontal and Vertical Layouts:
These days we see a lot of mobile websites supporting both horizontal and vertical layouts for the websites.  Yes, they work well for iPhone and Android devices but this is not practical for all Smartphone’s. While developing your website, you should go for a single column form. This will allow your users to scroll and that too in a single direction. By default, the single direction should be vertical because this is what is natural and a user expects this as well. If any images are being used, they too should support vertical scrolling. Opting for both vertical and horizontal scrolling is not a good idea.


7. An option to visit your regular website:
Mobile website is bound to have very limited information and in case a user requires more information, you can always provide a link of your regular website on the main page of your mobile web site.


8. Website Speed:
While developing your website, this is the most important thing to consider. Your site’s speed should be good enough to deliver website’s content quickly. If you want to achieve this, apart from avoiding JavaScript you need to avoid usage of flash as well. The most important guideline for mobile web development is to focus more on functionality and speed.




How Ajax Works

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the “Submit” button to send/get the information, wait for the server to respond, and then a new page will load with the results.

Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

With an HTTP request, a web page can make a request to, and get a response from a web server, without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

This picture is a simplified introduction about how Ajax works:










The user sends a request that executes an action and the action’s response is showed into a layer, identify by an ID, without reload the full page. For example a layer with this id:

<div id=”ajaxResponse”></div>

In the next steps we will see how to create an XMLHttpRequest and receive response from the server.

1. Create XMLhttpRequest
Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest.

To create this object, and deal with different browsers, we are going to use a “try and catch” statement.

function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}

2. Sending request to the server
To send off a request to the server, we use the open() method and the send() method.

The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server.

xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);


3. Writing server side script
The responseText will store the data returned from the server. Here we want to send back the current time. The code in “time.asp” looks like this:

<%
response.expires=-1
response.write(time)
%>

4. Consuming the response
Now we need to consume the response received and display it to the user.

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);
}

5. Complete the code
Now we must decide when the AJAX function should be executed. We will let the function run “behind the scenes” when the user types something in the username text field. The complete code looks like this:

<html>
<body>

<script type=”text/javascript”>
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);
}
</script>
<form name=”myForm”>
Name: <input type=”text”
onkeyup=”ajaxFunction();” name=”username” />
Time: <input type=”text” name=”time” />
</form>
</body>
</html>





Some Missing Features in WordPress

The popular publishing platform, WordPress, released its latest major version: WordPress 3.0 (dubbed "Thelonious"). This iteration of WordPress introduces plenty of convenient new features such as drag-and-drop interfaces for building navigation menus (for those not comfortable modifying their theme files), the ability to deploy multiple sites under one installation (by the inclusion of WordPress MU) and a system for making custom content types other than posts and pages.

However, some new features appear to be superfluous. Why have a built-in link shortener (yet not include social media web service integration that benefit from link shortening)? Why release a new default theme every year? Is it really worth the increase in the code base’s bulk to give end-users an interface for designing custom headers?

With all of that in mind, let’s go over some of what I believe are missing features in WordPress.

1. Web Caching
Every time a visitor views a web page in a WordPress-powered site, the system performs multiple server-side processes and database queries to generate that page for the visitor. This affects the speed in which a web page can be rendered and — for people running the publishing platform on an underpowered web server — can cause major down times and slowdowns.

One of the best ways to improve page performance is through web caching files on the web server — storing static versions of each web page so that the system doesn’t have to perform redundant work whenever a page is requested.

This feature should be an optional feature that WordPress site administrators can enable, with option settings on how long to keep the cached files that they can tweak according to their site’s updating frequency and traffic load.

2. Displaying Related Posts
Findability can be greatly improved if related content is displayed on a post. Right now, theme developers can take advantage of the get_category/get_categories for pulling out the posts’ category and wp_get_post_tags for the post’s tags, however, what’s more difficult is displaying related posts.

There are ways to try and display related posts, such as picking, say, 5 random posts from the same category/categories or posts tagged with the same words. However, the accuracy of how related the queried posts will be to the current post is, a lot of times, poor.

There should be more "signals" to determine the relevancy of one post to another, such as seeing if the title of posts have the same words, how many tags are the same on both posts, and if the current post links to another post.

3. Social Media Integration for Popular Web Services
An essential feature of content-centered sites is the ability for its users to share published content. Blogs that don’t have social media buttons and sharing options using email are uncommon.

I think it’s relevant to include native integration for at least the popular web services like Digg, Twitter, StumbleUpon and Facebook so that end-users don’t have to rely on and maintain third-party plugins.

Social media integration is so commonplace that the "twitter" plugin tag is a popular tag amongst more general keyword tags such as "Post", "widget", "image", and "sidebar."

4. Site Statistics
The capacity to learn about what content works and what doesn’t is key to being able to produce content that people view the most. The tool that’s central to this understanding of our content is website analytics.

The Automattic team, founders of WordPress and WordPress.com, has developed a statistics plugin that’s among the top WordPress plugins installed — it gets over 30,000 downloads per week.

The plugin shows administrators top referrers (where visitors are coming from), popular posts, site traffic statistics, and a pretty line graph that visualizes site traffic trends.

It’s time to adopt this plugin into WordPress.

5. Web Form Builder
HTML web forms are crucial to most modern sites: They’re the primary means of enabling communication and input from users. Comments, surveys, polls, contact forms, and content submissions are all large components of content-driven sites and they all need web forms.

Having a form builder interface, similar to the navigation and header builders that came with WordPress 3.0, can help users create custom web forms to increase interaction with site visitors.

6. Content Rating
The ability to rate content, including user comments, pages, and other content types is a good design pattern for increasing user participation. Content rating opens up a lot of possibilities, such as displaying a dynamic list of the most popular content based on user rating on the sidebar or the ability to sort archives based on popularity.

Content rating can also help the site owner identify content that users like so they can make more of it. Additionally, under the expertise of a theme developer, it can help with site maintenance, such as in the case of auto-deletion of spam comments if a comment is downvoted a lot or flagged as spam.






Become a Better PHP Developer

PHP is probably the most popular web development language right now. At least 20 million domains use PHP and it’s the language used on major sites such as Wikipedia and Facebook as well as in some of the world’s biggest open source projects like WordPress and Drupal.

In this article, I’ll share with you ten things I wish I was told when I was just getting started with PHP development, and I’m hoping you’ll be able to learn a thing or two if you’re just taking your first steps into this awesome web development language.







1. Use PHP Core Functions and Classes
If you’re trying to do something that seems fairly common, chances are, there’s already a PHP function or class that you can take advantage of. Always check out the PHP manual before creating your own functions. There’s no need to create a function to remove the white space at the beginning and at the end of a string when you can just use the trim() function. Why build an XML parser for RSS feeds when you can take advantage of PHP’s XML Parser functions (such as xml_parse_into_struct)?

2. Create a Configuration File
Instead of having your database connection settings scattered everywhere, why not just create one master file that contains its settings, and then include it in your PHP scripts? If you need to change details later on, you can do it in one file instead of several files. This is also very useful when you need to use other constants and functions throughout multiple scripts.




Using a config file is a popular web application pattern that makes your code more modular and easier to maintain.

3. Don’t Over-Comment Your Code:
Proper documentation of your code through comments in your scripts is definitely a good practice, but is it really necessary to comment every single line? Probably not. Comment the complicated parts of your source code so that when you revisit it later you’ll quickly remember what’s going, but don’t comment simple things such as your MySQL connection code. Good code is self-explanatory most of the time.
 
4. Keep Favorite Code Snippets Handy
You’ll be coding a lot of the same things throughout your PHP development career, and keeping code snippets always available will help you save a lot of time. There are several apps that can keep and sync your code snippet collection for you, so no matter where you are, you can always have your snippets available. Some apps you can use to corral your code snippets are Snippet, snippely, Code Collector, and Snipplr (web-based).

5. Use a Good Source Editor to Save You Time

Your editor is where you’ll spend the majority of your time, so you want to use something that helps you save time. Syntax highlighting is a must and definitely something you should be looking for as a software feature. Other bonuses include code hinting, code navigation and built-in debugging tools. All of these features can end up saving you massive amounts of time. An example of a source code editor/IDE for PHP is phpDesigner.

Take the time to get familiar with your source code editor’s features by reading the documentation and reading tutorials online. A bit of time investment in this arena can really streamline your coding workflow.

Check out this list of source code editors for developers as well as this list of free text editors for coders to discover popular code-editing applications.


6. Use a MySQL Administration Tool (Like phpMyAdmin)
I know some crazy hard-core developers who like working with MySQL (the popular Database Management System pairing for PHP) via command line, which, to me, is inefficient and just, well, crazy. It’s a good thing to know how to administer your MySQL database using mysqladmin, but afterwards, you should use a graphical user interface like phpMyAdmin to speed up database development and administration.

phpMyAdmin, in particular, is an excellent open source database viewer/manager that allows you to view your MySQL databases graphically so that you don’t have to waste time doing things via the command line. You can quickly build databases and their tables, export your databases into SQL files, run SQL queries, optimize tables, check for issues, create MySQL database users and set up their privileges quickly, and much more. There is a good chance your web host already has phpMyAdmin installed, and if not, it only takes minutes to install.

7. Use a PHP Framework
It took me a really long time to accept the fact that using a web application development/rapid application development framework would help me out. You have a small learning curve in the beginning, and there will be a lot of reading to do to learn how the API of the framework works, but you get amazing productivity and efficiency benefits later. Using a framework forces you to use better web development patterns that you might not be using right now.

Using a PHP framework pays off big time when you have to share your code with others later on or when you have to work together with someone; it gives you a standardized platform for building web applications. I learned the importance of this the hard way when I had to start hiring other developers.

Some popular PHP frameworks are CakePHP, CodeIgniter, symfony, and Zend.

8. Connect with Other PHP Developers
You don’t know it all. And even if you think you do, there are thousands of others out there that know how to do something better than you do. Join a PHP community like PHPDeveloper and interact with others. By connecting with other developers, you’ll learn better ways of doing the things you’re currently doing.






How to add Videos in HTML5

HTML5 has entered our lives for good and it is changing the way we are embedding media on our web pages. Two of the new greatest features are the <video> elements. No more do we have to resort to Flash to serve videos to our visitors. The new solutions HTML5 has to offer are really tempting but enough with the introductory words. Let’s see what <video> do.


<video>
As with the <audio> element, the syntax is the same with the <video> element.

<video controls>
    <source src="video-file.mp4" type="video/mp4"/>
    <source src="video-file.ogv" type="video/ogg"/>
<p>Fallback message - Your browser does not support the video element.</p>
</video>

Again, we have to use multiple sources and different file types and encodings of the same video file to support all the compatible browsers. You can read more about file types and browser support on the W3Schools HTML5 Video page.


height/width
The autoplay, loop and preload attributes of the audio element work the same way in the video element too. Apart from those, we have some other video specific attributes such as the height and width. They work the same way they do for the img element.

<video controls height="480" width="640">
    <source src="video-file.mp4" type="video/mp4"/>
    <source src="video-file.ogv" type="video/ogg"/>
<p>Fallback message - Your browser does not support the video element.</p>
</video>


poster
When our video is not playing, we can use the poster attribute to link to a thumbnail image to display instead of just displaying the first frame of the video.

<video controls poster="video-thumbnail.jpg">
    <source src="video-file.mp4" type="video/mp4"/>
    <source src="video-file.ogv" type="video/ogg"/>
<p>Fallback message - Your browser does not support the video element.</p>
</video>

fallback
Browser support is good considering this is a new feature but of course there are older browsers that we need to take care of. To do so there is only one good and efficient solution, to use a Flash as a fallback. A great plugin to help with browser support for both the audio and video elements is html5media.

How to add Audios in HTML5

HTML5 has entered our lives for good and it is changing the way we are embedding media on our web pages. Two of the new greatest features are the <audio> elements. No more do we have to resort to Flash to serve audio to our visitors. The new solutions HTML5 has to offer are really tempting but enough with the introductory words. Let’s see what <audio> do.






<audio>
The tag’s name by itself says it all. With the new <audio> element we can quickly and easily add audio to our webpages. In its simplest form, it works pretty much the same as the <img> element so we just need to use the src attribute to link to our audio file.

<audio src="audio-file.mp3">
</audio>

It is really that simple. We can even add a fallback message or another fallback solution (Flash player) in case the visitor’s browser doesn’t support the new audio element.

<audio src="audio-file.mp3">
    <p>Fallback message - Your browser does not support the audio element.</p>
</audio>


autoplay
With difference the most annoying option. Who amongst us hasn’t stumbled upon a web page that started playing music and you were looking for that one tab that had to close? If we want to be that annoying we can use the autoplay option on our audio element. Please use with caution.

<audio src="audio-file.mp3" autoplay>
</audio>

Notice that autoplay is a boolean attribute, so no need to type autoplay=”true”.


loop
Another pretty self-explanatory boolean attribute. The audio file loops for ever.

<audio src="audio-file.mp3" loop>
</audio>


preload
Preload allows the browser to start buffering our audio file without having the visitor hit the play button first. That way, when the visitor hits tha play button, he can enjoy a smooth playback without loading times. Again, we have to be cautious when we use preload because might not want to buffer data that the visitor might not use.

So preload can take three values, “auto”, “none” and “metadata”. We are extremely interested only about the first too though.

<audio src="audio-file.mp3" preload="auto">
</audio>

Keep in mind that Safari by default has the preload to “auto” so if we want to disable it, we have to use preload=”none”


controls
With the use of controls, we enable the visitor to use the native controls each browser provides for the playback of the audio file. Of course we are able to use our own control buttons with a bit of Javascript but that is a subject for another article.

<audio src="audio-file.mp3" controls>
</audio>


filetypes
Unfortunately, not everything is as easy as it looks. The problem with audio (and video) filetypes is that the HTML5 specs do not restrict the browsers to support certain filetypes so each browser supports his own filetypes and encodings for his own reasons. What we have to do is, look ahead and provide the same audio file in different filetypes and encodings for it to be compatible with each browser that supports the audio element. More on audio filetypes and encodings on the W3Schools HTML5 Audio page.

To add multiple sources we will use the <source> tag.

<audio controls>
     <source src="audio-file.ogg" type="audio/ogg" />
      <source src="audio-file.mp3" type="audio/mpeg" />
</audio>

With those two filetypes we have covered all the compatible browsers. Let’s move on to <video> now.

PHP & MySQL Base Visitors Counter

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.

$visitor_ip = GetHostByName($REMOTE_ADDR);

Next step we need the browser type of our visitor and we will use this function:

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 class="pages">' . $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…!

HTML Best Practices You Should Follow

Most of the web pages you encounter is presented to you via HTML, the world wide web’s markup language.
Following are best practices that will lead to clean and correct markup:



1. Always Declare a Doctype
The doctype declaration should be the first thing in your HTML documents. The doctype declaration tells the browser about the XHTML standards you will be using and helps it read and render your markup correctly.

2. Use Meaningful Title Tags
The <title> tag helps make a web page more meaningful and search-engine friendly. For example, the text inside the <title> tag appears in Google’s search engine results page, as well as in the user’s web browser bar and tabs.

3. Use Descriptive Meta Tags
Meta tags make your web page more meaningful for user agents like search engine spiders. The description meta attribute describes the basic purpose of your web page (a summary of what the web page contains). For each web page, you should place a consise and relevant summary inside the meta description tag.

4. Use Divs to Divide Your Layout into Major Sections
Consider dividing your web page into major sections as the first step in constructing a website design. Doing so from the start promotes clean and well-indented code. It will also help you avoid confusion and excess use of divs, especially if you are writing complex and lengthy markup.

5. Close Your Tags
Closing all your tags is a W3C specification. Some browsers may still render your pages correctly (under Quirks mode), but not closing your tags is invalid under standards.

7. Use Lower Case Markup
It is an industry-standard practice to keep your markup lower-cased. Capitalizing your markup will work and will probably not affect how your web pages are rendered, but it does affect code readability.

8. Use Alt Attributes with Images
Using a meaningful alt attribute with <img> elements is a must for writing valid and semantic code.


9. Write Consistently Formatted Code
A cleanly written and well-indented code base shows your professionalism, as well as your consideration for the other people that might need to work on your code.
Write properly indented clean markup from the start; it will increase your work’s readability.

More Like This

Related Posts Plugin for WordPress, Blogger...

AddThis