PHP – Securing your Web Application : File Access

If only you and people you trust can log in to your web server, you don’t need to worry about file permissions for files used by or created by your PHP programs. However, most websites are hosted on ISP’s machines, and there’s a risk that non trusted people can read files that your PHP program creates. There are a number of techniques that you can use to deal with file permissions issues.

Restrict Filesystem Access to a Specific Directory You can set the open_basedir option to restrict access from your PHP scripts to a specific directory. If open_basedir is set in your php.ini, PHP limits filesystem and I/O functions so that they can operate only within that directory or any of its subdirectories. For example:

open_basedir = /some/path

With this configuration in effect, the following function calls succeed:

unlink("/some/path/unwanted.exe");

include("/some/path/less/travelled.inc");

But these generate runtime errors:

$fp = fopen("/some/other/file.exe", 'r');

$dp = opendir("/some/path/../other/file.exe");

Of course, one web server can run many applications, and each application typically stores files in its own directory. You can configure open_basedir on a per-virtual host basis in your httpd.conf file like this:

<VirtualHost 1.2.3.4>
ServerName domainA.com
DocumentRoot /web/sites/domainA
php_admin_value open_basedir /web/sites/domainA
</VirtualHost>

Similarly, you can configure it per directory or per URL in httpd.conf:

# by directory

<Directory /home/httpd/html/app1>
php_admin_value open_basedir /home/httpd/html/app1
</Directory>

# by URL

<Location /app2>
php_admin_value open_basedir /home/httpd/html/app2
</Location>

The open_basedir directory can be set only in the httpd.conf file, not in .htaccess files, and you must use php_admin_value to set it.

Get It Right the First Time

Do not create a file and then change its permissions. This creates a race condition, where a lucky user can open the file once it’s created but before it’s locked down. Instead, use the umask() function to strip off unnecessary permissions. For example:

umask(077); // disable ---rwxrwx

$fh = fopen("/tmp/myfile", 'w');

By default, the fopen() function attempts to create a file with permission 0666 (rw-rwrw-). Calling umask() first disables the group and other bits, leaving only 0600 (rw-------). Now, when fopen() is called, the file is created with those permissions.

Don’t Use Files

Because all scripts running on a machine run as the same user, a file that one script creates can be read by another, regardless of which user wrote the script. All a script needs to know to read a file is the name of that file.

There is no way to change this, so the best solution is to not use files to store data that should be protected; the most secure place to store data is in a database.

A complex workaround is to run a separate Apache daemon for each user. If you add a reverse proxy such as haproxy in front of the pool of Apache instances, you may be able to serve 100+ users on a single machine. Few sites do this, however, because the complexity and cost are much greater than those for the typical situation, where one Apache daemon can serve web pages for thousands of users.

Session Files

With PHP’s built-in session support, session information is stored in files. Each file is named /tmp/sess_id, where id is the name of the session and is owned by the web server user ID, usually nobody.

Because all PHP scripts run as the same user through the web server, this means that any PHP script hosted on a server can read any session files for any other PHP site. In situations where your PHP code is stored on an ISP’s server that is shared with other users’ PHP scripts, variables you store in your sessions are visible to other PHP scripts.

Even worse, other users on the server can create files in the session directory /tmp. There’s nothing preventing a user from creating a fake session file that has any variables and values he wants in it. The user can then have the browser send your script a cookie containing the name of the faked session, and your script will happily load the variables stored in the fake session file.

One workaround is to ask your service provider to configure their server to place your session files in your own directory. Typically, this means that your VirtualHost block in the Apache httpd.conf file will contain:

php_value session.save_path /some/path

If you have .htaccess capabilities on your server and Apache is configured to let you override options, you can make the change yourself.

Concealing PHP Libraries

Many a hacker has learned of weaknesses by downloading include files or data that are stored alongside HTML and PHP files in the web server’s document root. To prevent this from happening to you, all you need to do is store code libraries and data outside the server’s document root.

For example, if the document root is /home/httpd/html, everything below that directory can be downloaded through a URL. It is a simple matter to put your library code, configuration files, logfiles, and other data outside that directory (e.g., in /usr/local/lib/myapp). This doesn’t prevent other users on the web server from accessing those files but it does prevent the files from being downloaded by remote users.

If you must store these auxiliary files in your document root, you should configure the web server to deny requests for those files. For example, this tells Apache to deny requests for any file with the .inc extension, a common extension for PHP include files:

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

A better and more preferred way to prevent downloading of PHP source files is to always use the .php extension.

If you store code libraries in a different directory from the PHP pages that use them, you’ll need to tell PHP where the libraries are. Either give a path to the code in each include() or require(), or change include_path in php.ini:

include_path = ".:/usr/local/php:/usr/local/lib/myapp";

Here is the list of of Article in this Series:

Please share the article if you like let your friends learn PHP Security. Please comment any suggestion or queries.

 

Thanks Kevin Tatroe, Peter MacIntyre and Rasmus Lerdorf. Special Thanks to O’Relly.

WordPress – Add Retina Image Support to Your Theme

Today, with increasing of high resolution devices, Client ask developer to add retina image support to their theme. Support Retina is to display high quality image on high resolution devices. This means we need to create high resolution images and to load right images based on screen resolutions.

There are some plugins available on WordPress for regular users to add retina display images. Searching a wordpress directory for plugin shows below 5 plugins on top

Each plugin show use different way to show retina images but internal all  includes two things, A detection script and a retina-ready image creation function. For developer who want to include the feature of displaying retina image to their theme, It very first step to select right JavaScript to detect the screen resolution and display the image.

Detect Screen Display

We need to display high quality image if user device is supporting it. The best way to detect a screen is using JavaScript.  I generally use a script called retina.js by Imulus. Its size is only 4kb and includes all the front-end functionality you need to detect a retina display and load the right image.

Copy retina.js file to your theme /js folder. It should be in right place to enqueue the script correctly.

Add following code to your functions.php file

add_action( 'wp_enqueue_scripts', 'retina_support_enqueue_scripts' );
/**
 * Enqueueing retina.js
 *
 * This function is attached to the 'wp_enqueue_scripts' action hook.
 */
function retina_support_enqueue_scripts() {
    wp_enqueue_script( 'retina_js', get_template_directory_uri() . '/js/retina.js', '', '', true );
}

Above code is enough to detect the screen display. Now we have to create function to create high quality image.

High Quality Image Creation

We need to add a function such that each time image is uploaded or added a high resolution image is created automatically and stored with @2x added to the filename. The detection JavaScript will search for @2x suffix in filename to load the retina-ready version of the image if required.

In order to make sure that a retina-ready image is created automatically whenever an image is uploaded, you need to hook into the appropriate WordPress filter. The correct one to use is wp_generate_attachment_metadata.

Add the following code in functions.php of your theme

add_filter( 'wp_generate_attachment_metadata', 'retina_support_attachment_meta', 10, 2 );
/**
 * Retina images
 *
 * This function is attached to the 'wp_generate_attachment_metadata' filter hook.
 */
function retina_support_attachment_meta( $metadata, $attachment_id ) {
    foreach ( $metadata as $key => $value ) {
        if ( is_array( $value ) ) {
            foreach ( $value as $image => $attr ) {
                if ( is_array( $attr ) )
                    retina_support_create_images( get_attached_file( $attachment_id ), $attr['width'], $attr['height'], true );
            }
        }
    }

    return $metadata;
}

The above function checks to see if the uploaded file is an image. If it is, then it processes it using the retina_support_create_images() function.

Create An Image

Now as we checked if image is added and its time to create high quality image.

This code will also be placed in functions.php

/**
 * Create retina-ready images
 *
 * Referenced via retina_support_attachment_meta().
 */
function retina_support_create_images( $file, $width, $height, $crop = false ) {
    if ( $width || $height ) {
        $resized_file = wp_get_image_editor( $file );
        if ( ! is_wp_error( $resized_file ) ) {
            $filename = $resized_file->generate_filename( $width . 'x' . $height . '@2x' );

            $resized_file->resize( $width * 2, $height * 2, $crop );
            $resized_file->save( $filename );

            $info = $resized_file->get_size();

            return array(
                'file' => wp_basename( $filename ),
                'width' => $info['width'],
                'height' => $info['height'],
            );
        }
    }
    return false;
}

By this function, new retina image will be created  with suffix @2x added to the name. Now detection script will work with these new image.

That’s all you need to do to make it work, but adding one extra function will help in reducing the usage of server bytes. This function is for deleting the image that we have created for retina display when original image is deleted.

Delete the Image

If is a good to delete the retina-image if original image is deleted.

Add following code to functions.php of your theme

add_filter( 'delete_attachment', 'delete_retina_support_images' );
/**
 * Delete retina-ready images
 *
 * This function is attached to the 'delete_attachment' filter hook.
 */
function delete_retina_support_images( $attachment_id ) {
    $meta = wp_get_attachment_metadata( $attachment_id );
    $upload_dir = wp_upload_dir();
    $path = pathinfo( $meta['file'] );
    foreach ( $meta as $key => $value ) {
        if ( 'sizes' === $key ) {
            foreach ( $value as $sizes => $size ) {
                $original_filename = $upload_dir['basedir'] . '/' . $path['dirname'] . '/' . $size['file'];
                $retina_filename = substr_replace( $original_filename, '@2x.', strrpos( $original_filename, '.' ), strlen( '.' ) );
                if ( file_exists( $retina_filename ) )
                    unlink( $retina_filename );
            }
        }
    }
}

In this tutorial we learn how to add support of displaying retina image in WordPress theme. This will help theme developer in adding retina support to their theme.

 

Thanks to wptuts+.

Faceted Search (Layered Search) on MySQL database with example.

Last few day I was searching for the layered search using MySQL. Layered Search is actually a Faceted Search. (Magento, a highly professional e-commerce platform on php name it Layered Search). Faceted Search can be done using two way MySQL/Any DB Application or using Apache Solr.

In this post I will show you how we can do Faceted search using MySQL database. You need a specific database schema, but it’s feasible. Here’s a simple example:

product Table

+----+------------+
| id | name       |
+----+------------+
|  1 | blue paint |
|  2 | red paint  |
+----+------------+

classification Table

+----+----------+
| id | name     |
+----+----------+
|  1 | color    |
|  2 | material |
|  3 | dept     |
+----+----------+

product_classification Table

+------------+-------------------+-------+
| product_id | classification_id | value |
+------------+-------------------+-------+
|          1 |                 1 | blue  |
|          1 |                 2 | latex |
|          1 |                 3 | paint |
|          1 |                 3 | home  |
|          2 |                 1 | red   |
|          2 |                 2 | latex |
|          2 |                 3 | paint |
|          2 |                 3 | home  |
+------------+-------------------+-------+

So, say someones search for paint, you’d do something like:

SELECT p.* FROM product p WHERE name LIKE '%paint%';

This would return both entries from the product table.

Once your search has executed, you can fetch the associated facets (filters) of your result using a query like this one:

SELECT c.id, c.name, pc.value FROM product p
   LEFT JOIN product_classification pc ON pc.product_id = p.id
   LEFT JOIN classification c ON c.id = pc.classification_id
WHERE p.name LIKE '%paint%'
GROUP BY c.id, pc.value
ORDER BY c.id;

This’ll give you something like:

+------+----------+-------+
| id   | name     | value |
+------+----------+-------+
|    1 | color    | blue  |
|    1 | color    | red   |
|    2 | material | latex |
|    3 | dept     | home  |
|    3 | dept     | paint |
+------+----------+-------+

So, in your result set, you know that there are products whose color are blue and red, that the only material it’s made from is latex, and that it can be found in departments home and paint.

Once a user select a facet, just modify the original search query:

SELECT p.* FROM product p
   LEFT JOIN product_classification pc ON pc.product_id = p.id
WHERE 
   p.name LIKE '%paint%' AND (
      (pc.classification_id = 1 AND pc.value = 'blue') OR
      (pc.classification_id = 3 AND pc.value = 'home')
   )
GROUP BY p.id
HAVING COUNT(p.id) = 2;

So, here the user is searching for keyword paint, and includes two facets: facet blue for color, andhome for department. This’ll give you:

+----+------------+
| id | name       |
+----+------------+
|  1 | blue paint |
+----+------------+

So, in conclusion. Although it’s available out-of-the-box in Solr, it’s possible to implement it in SQL fairly easily.

 

Thanks stackoverflow.com

Install Apache Solr on Windows with Wamp

Apache Solr is useful for Searching, Indexing, Faceted Search, Dynamic clustering. You can see full feature of Apache Solr Here. It is based on Apache Lucene Search Library and extends it. Here I will show you how to install Apache Solr on Windows and integrating it with WAMP Server. (Integration with WAMP is not mandatory if you are not using it)

The easiest way to install Apache Solr on Windows is to use Solr installer from BitNami. This can be found here http://bitnami.com/stack/solr. Download the installer and run it with administrative rights. Try to keep the installation path simple something like “c:/solr/” will be appropriate.

It will also install an Apache Server so if you don’t have WAMP or Apache already installed than its super easy, just go with the flow. If you already have WAMP installed than make this Apache listen on some available port  other than 80 (where WAMP ‘s Apache is listening).

Once the setup is complete Solr will be available for use in port selected during setup (see no big deal). Now if you have WAMP and you don’t want to have two Apache services running do the following steps.

  • Enable proxy_module and proxy_http_module via WAMP menu or directly from Apache conf file.
  • Open httpd.conf file and add following line at the end of the file
    Include "c:/solr/apache-solr/conf/solr.conf"

    Note that the path here should be correctly pointing to the solr.conf file. Use the path where you installed the Solr.

  • Now restart the WAMP Apache via WAMP menu. If it starts correctly than its cool, otherwise check if you have correctly enabled the said modules, and path to solr config file.
  • Now check http://localhost/solr/ this should show the dashboard for solr.
  • Remember the extra Apache service we need to disable it so it does not start automatically as we don’t need it. So goto Control Panel > Administrative Tools > Services , double click “solrApache” service and change its “Startup Type” to “Manual”. Now it will not start once your system is restarted.

 

 

Thanks to sphinxconsultant.com

Opencart – Category Carousel of Product

Category Product Carousel – Opencart is new Opencart extension module by TheDigiLife. Category Product Carousel – Opencart is very useful in displaying products of particular category in carousel. This Opencart module is easy to use as it looks like core Opencart module. This module not update any core files.

Category Product Carousel – Opencart supports multilanguage. You can visit this plugin on Opencart marketplace here. This module uses jQuery Carousel which comes bundled with Opencart installation so no extra file is added.

Category Product Carousel – Opencart is light weight module. Installation instruction are as follow.

  1. Download the zip file, extract somewhere on your computer. 
  2. From extracted file, upload the the files/folder under “upload” folder to server using FTP, in root folder (where admin,catalog,system folder are available) of Opencart installation 
  3. Go to admin area of you Opencart website and Click on Extension > Modules
  4. Install Category Product Carousel
  5. Edit Category Product Carousel
  6. At last add module on you desired page.

Below are the screenshots

admin-area-configuration

category-carousel-example

logoimage

You can download Category Product Carousel – Opencart Here

Opencart – Shopping cart in Pop Up and Buy Now Button

Recently we released new Opencart plugin named “Product Buy Now button and Cart in Popup – Opencart – VQMOD“. This is useful extension of Opencart for replacing the “Add to cart” button with “Buy Now” button. Clicking on Buy Now button opens shopping cart in popup. Popup shopping cart is fully functioned. User can change quantity, remove any product, Apply coupon code, etc. in popup itself.

Product Buy Now button and Cart in Popup – Opencart – VQMOD extension of Opencart makes your site User friendly and easy access to shopping cart. Shopping cart popup is displayed using Colorbox jQuery plugin popup. Colorbox jQuery comes bundled with Opencart installation so no extra file include.

This Opencart plugin is developed using vQmod so no core files will be changed. Installation is very easy.

This Opencart extension support multilanguage.

Here is the screenshot of extension.

You can download the plugin Here

OpenCart – Options Mouse Hover ToolTip Help

Recently new Opencart extension launched on Opencart market place. It is Options Mouse Hover ToolTip Help. Plugin is really cool and useful in showing ToopTip Text for product option in Opencart.

Opencart is E- Commerce / Shopping Cart  Open Source solution. Its stands on second place when comparing to similar solution like Magento, PrestShop etc.  OpenCart is really useful for medium businesses. It is a feature rich open source shopping cart solution.

Opencart is missing feature to add help text for Available Options for products. This plugin help administrator to add text from admin and show it to Customer for more information on Options.

This plugin can also be useful in showing some options Notes, disclaimer or simple information. Extension interface is really easy.

Also it supports “vqmod” so that no core file will be updated. You can find more information on vqmod here.

Visit the extension page on opencart market place. Click Here

Here are some screenshot of plugins.

Admin Multiple Value Tooltip

Admin Single Value Tooltip

Customer / Front end View

 

WordPress Essential Plugins – Every Website Required

Plugins are tools to extend the functionality of WordPressWordPress Plugins allow easy modification, customization, and enhancement to a WordPress blog. Instead of changing the core programming of WordPress, you can add functionality with WordPress Plugins.

What is WordPress Plugins?

Here is a basic definition: A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

SEO Related WordPress Essential Plugins

SEO is something which every site requires to make their business increase. SEO is a technique which helps search engines find and rank your site higher than the millions of other sites in response to a search query. SEO thus helps you get traffic from search engines.

WordPress SEO by Yoast

Improve your WordPress SEO: Write better content and have a fully optimized WordPress site using the WordPress SEO plugin by Yoast. WordPress SEO is the most complete and advanced WordPress SEO plugin that exists today. It incorporates everything from a snippet preview and page analysis functionality that helps you optimize your pages content, images titles, meta descriptions and more to XML sitemaps. This plugin helps you to optimize your page content, image titles, meta descriptions, comes with tons of other features like Robots Meta configuration, breadcrumbs, permalink cleanup, canonical link element support, and optimized post titles.

 All in One SEO Pack

All in one SEO WordPress PluginWordPress SEO plugin to automatically optimize your WordPress blog for Search Engines. Another free WordPress seo plugins which can be used to Optimizes your WordPress blog for Search Engines (Search Engine Optimization).

Comes with features to support google analytics,custom post types, Advanced Canonical URLs, Built-in API so other plugins/themes can access and extend functionality.

Google XML Sitemaps

This plugin will generate a special XML sitemap which will help search engines to better index your blog. Google XML Sitemaps plugin generates XML sitemaps for your WordPress website, so that it becomes easy for search engine crawlers like Google and Bing, to index your site better. It notifies all the major search engines when you create new content, helping your site be more thoroughly indexed.

SEO Friendly Images

SEO Friendly Images automatically adds alt and title attributes to all your images improving traffic from search engines. SEO friendly Images automatically adds alt and title attributes to your images. If your images inside post or page content don’t have alt or title attribute then this plugins adds them according to your plugins settings so images inside your content becomes seo optimized.

Broken Link Checker

This plugin will check your posts, comments and other content for broken links and missing images, and notify you if any are found. This plugin is very helpful to find all the broken links on your website. This plugin Monitors links in your posts, pages, comments, the blogroll, and custom fields (optional). Detects links that don’t work, missing images and redirects. Notifies you either via the Dashboard or by email.

WordPress Essential Any-Spam and Security Plugins

Every Website require to stop spamming. Stopping bot generated comments. Many Plugins are available to stop span. Here I have listed some good plugin available in WordPress.

Akismet

akismetAkismet filters out your comment and track-back spam for you, so you can focus on more important things. Akismet is the best wordpress anti spam plugin to protect your website from web spam. Akismet plugin filters comments and trackback spam. It runs on autopilot and provides 24-hour protection. Akismet is the best automated spam killer that actually gets better as it learns.

SI CAPTCHA Anti-Spam

SI CAPTCHA Anti-SpamAdds CAPTCHA anti-spam methods to WordPress on the forms for comments, registration, lost password, login, or all. For WP, WPMU, and BuddyPress. SI CAPTCHA Anti-Spam plugin prevents spam from automated bots by adding a CAPTCHA in comment, registration, login and lost password forms. So your websites comment,login and registration forms becomes more secure from spams.

WP-reCAPTCHA

WP-reCAPTCHAIntegrates reCAPTCHA anti-spam methods with WordPress including comment, registration, and email spam protection. reCAPTCHA is popular and widely accepted CAPTCHA systems on many websites. WP-reCaptcha plugin integrates reCAPTCHA anti-spam methods in WordPress as comment, registration forms and email protection.

Login LockDown

Login LockDown records the IP address and timestamp of every failed login attempt. If more than a certain number of attempts are detected within a short period of time from the same IP range, then the login function is disabled for all requests from that range. This helps to prevent brute force password discovery.

Better WP Security

Better WP Security

The easiest, most effective way to secure WordPress. Improve the security of any WordPress site in seconds. This plugin can Remove the meta “Generator” tag, Change the urls for WordPress dashboard including login, admin, and more, Completely turn off the ability to login for a given time period (away mode), Remove theme, plugin, and core update notifications from users who do not have permission to update them, Remove Windows Live Write header information, Remove RSD header information, Rename “admin” account, Change the ID on the user with ID 1, Change the WordPress database table prefix, Change wp-content path, Removes login error messages and Display a random version number to non administrative users anywhere version is used.

Essential Polls and Comments WordPress plugins

 

CommentLuv

Reward your readers by automatically placing a link to their last blog post at the end of their comment. Encourage a community and discover new posts. CommentLuv Pro has even more amazing features that can bring even more traffic and comments to your blog by giving you the ability to fight spam, add keywords, integrate twitterlink, add a top commentators widget, social enticements and by having it installed on your site, you get advanced backlink features on EVERY CommentLuv blog when you comment (there are 10’s of thousands of CommentLuv blogs).

Facebook Comments For WordPress

Allows your visitors to comment on posts using their Facebook profile. Supports custom styles, notifications, combined comment counts, recent comments. This plugin integrates the Facebook commenting system (new, old or both) right into your website. If a reader is logged into Facebook while viewing any comment-enabled page or post, they’ll be able to leave a comment using their Facebook profile.

Disqus Comment System

Disqus Comment SystemDisqus, pronounced “discuss”, is a service and tool for web comments and discussions. Disqus makes commenting easier and more interactive, while connecting websites and commenters across a thriving discussion community.  The Disqus for WordPress plugin seamlessly integrates using the Disqus API and by syncing with WordPress comments.

Subscribe To Comments

Subscribe to Comments allows commenters on an entry to subscribe to e-mail notifications for subsequent comments. The plugin includes a full-featured subscription manager that your commenters can use to unsubscribe to certain posts, block all notifications, or even change their notification e-mail address!

WP-Polls

Adds an AJAX poll system to your WordPress blog. You can also easily add a poll into your WordPress’s blog post/page. WP-Polls is extremely customizable via templates and css styles and there are tons of options for you to choose to ensure that WP-Polls runs the way you wanted. It now supports multiple selection of answers.

Essential Social WordPress Plugin

AddThis

AddthisAddThis Share Buttons help drive traffic to your site by helping visitors share, bookmark and email your content to over 330 services. Get more traffic back to your site by installing the AddThis WordPress plugin.With AddThis, your users can promote your content by sharing to over 330 of the most popular social networking and bookmarking sites (like Facebook, Twitter, Pinterest, Google+ and LinkedIn).

ShareThis: Share Buttons and Sharing Analytics

ShareThis Share Buttons and Sharing AnalyticsQuick & easy sharing service that allows your users to share content – features Open Graph Sharing, Hovering Bar and CopyNShare! Increase social activity on your site with the ShareThis and ShareNow widgets. With access to 120 social channels (including Facebook, Twitter, Like, +1, Email and more), The ShareThis widget is a quick and easy sharing solution for your site to keep your audience engaged in your content and increase traffic to your site. You can also customize your widget for seamless integration to your site. You have the option to use small or large buttons, add counters and place the widget in a clear location for your users to share.

Sociable

Sociable plugin adds a bar of icons of different social networking and bookmarking sites that you can choose for your articles. Using sociable plugin visitors of your website can easily share posts from your website on their social bookmarking accounts.

Essential Stats and Tracking Plugins

WassUp Real Time Analytics

WassUp Real Time AnalyticsAnalyze your visitors traffic with real-time statistics, a lot of chronological information, charts, a sidebar widget. WassUp is a WordPress plugin to track your visitors in real-time. It has a very readable and fancy admin console to keep track of your visitors that gives you a detailed view into almost everything your users are doing on your site. It is very useful for SEO or statistics maniacs.

WP-UserOnline

Enable you to display how many users are online on your WordPress blog with detailed statistics. This plugin enables you to display how many users are online on your WordPress site, with detailed statistics of where they are and who they are (Members/Guests/Search Bots).

Count per Day

Count per DayVisit Counter, shows reads and visitors per page, visitors today, yesterday, last week, last months and other statistics. This plugin count reads and visitors, shows reads per page, shows visitors today, yesterday, last week, last months and other statistics on dashboard, shows country of your visitors, you can show these statistics on frontend per widget or shortcodes too.

Jetpack by WordPress.com

Jetpack by WordPress.comJetpack is a WordPress plugin that supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com. This plugin can Simple, concise stats with no additional load on your server. Previously provided byWordPress.com StatsEmail subscriptions for your blog’s posts and your post’s comments, Social networking enabled comment system, Likes, allowing your readers to show their appreciation of your posts, Monitor and manage your site’s activity with, Notifications in your Toolbar and on WordPress.com, Simple, Akismet-backed contact forms.

Google Analytics for WordPress

Google Analytics for WordPressTrack your WordPress site easily and with lots of metadata: views per author & category, automatic tracking of outbound clicks and pageviews. Simple installation through integration with Google Analytics API: authenticate, select the site you want to track and you’re done. This plugin uses the asynchronous Google Analytics tracking code, the fastest and most reliable tracking code Google Analytics offers. This plugin have option to manually place the tracking code in another location.

Other Essential Plugin for WordPress

Contact Form 7

Contact Form 7Contact Form 7 can manage multiple contact forms, plus you can customize the form and the mail contents flexibly with simple markup. The form supports Ajax-powered submitting, CAPTCHA, Akismet spam filtering and so on.

 

WordPress PopUp

WordPress PopUp allows you to display a fancy popup (powered as a popover!) to visitors sitewide or per blog, a *very* effective way of advertising a mailing list, sp. Good plugin to add popup ads or banners inside popup on your website. Comes with option to restrict popup from any particular page or posts.

Nrelate

nrelateNrelate display related content in a cool flyout box. nrelate is not just another related posts plugin. Patent-pending technology continuously analyzes your website content and displays other related posts from your website. This ultimately leads to higher page-views for your site, and a better user experience for your visitors.

 

Bulk Email Script in PHP and MySQL Database

In this post, I will show you how we can send an email to multiple receivers using simple PHP script. This script also shows how we can send bulk if we have server limitation on number of emails can be sent in period of time.  Many web hosting provider do not support bulk emails so I have set this script to come out of this limitation.

This Bulk Email script can send HTML email. You can also use this script to send promotional and marketing emails.

In this tutorial we will create three files. First file is HTML content of email, second file is the actual code which sends emails to multiple address one at a time and third file is allowing receivers to unsubscribe from email list.

sample.html

<p>Hello there</p>
<p>This is sample email file</p>
<br>
<p>Thanks,</p>
<p>Administrator</p>

sendmail.php

<?php

$con = mysql_connect("localhost","dbuser","dbpass"); // replace dbuser, dbpass with your db user and password
mysql_select_db("dbname", $con); // replace dbname with your database name
/*
To use this script database table must have three fields named sno, email and sub_status
*/
$query = "select sno, email from dbtable where sub_status = 'SUBSCRIBED'";
$result = mysql_query($query, $con);
$emails = array();
$sno = array();
while($row=mysql_fetch_assoc($result)){
	$sno[] = $row['sno']; // this will be used to unsubscribe the user
	$emails[]=$row['email']; // email id of user
}
/* you can also get email id data from CSV using below code */
//$file =  file_get_contents("travel_database.csv"); 
//$emails = explode(",",$file);

/* count.txt is used to store current email sent number/count */
$count =  file_get_contents("count.txt");
for($i=$count;$i<count($emails);$i++)
{
	$to  = $emails[$i];

	// subject
	$subject = 'Set Your Title Here';

	// message
	$message = file_get_contents("sample.html"); // this will get the HTML sample template sample.html
	$message .= '<p><a href="http://yourdomain.com/path-to-folder/unsubscribe.php?id='.$sno[$i].'&username='.$emails[$i].'">Please click here to unsubscribe.</a></p>
	</body>
	</html>';
	// To send HTML mail, the Content-type header must be set
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

	// Additional headers
	//$headers .= "To: $to" . "\r\n";
	$headers .= 'From: Name <info@yourdomain.com>' . "\r\n";
	//$headers .= 'Cc: sendcc@yourdomain.com' . "\r\n";
	//$headers .= 'Bcc: sendbcc@yourdomain.com' . "\r\n";

	// Mail it
	if(mail($to, $subject, $message, $headers)) {
		$file = fopen("mailsentlist.txt","a+"); // add email id to mailsentlist.txt to track the email sent
		fwrite($file, $to.",\r\n");
		fclose($file);
	}
	else
	{
		$file = fopen("notmailsentlist.txt","a+"); // add email to notmailsentlist.txt here which have sending email error
		fwrite($file, $to.",\r\n");
		fclose($file);
	}

	if(($i-$count)>=200) // this will send 200 mails from database per execution
	{	
		$filec = fopen("count.txt",'w'); // store current count to count.txt
		fwrite($filec, $i);
		fclose($filec);
		break;
	}
}//for end
$filec = fopen("count.txt",'w'); // store fine count to count.txt this will be used as a start point of next execution
fwrite($filec, $i);
fclose($filec);

Replace “http://yourdomain.com/path-to-folder/” with your path to unsubscribe.php

You can set the cron job on sendmail.php on particular time frame. For example if you hosting provider support only 100 mail per hour than you can set cron job par hour and update the value here

if(($i-$count)>=100) // update this in code of sendmail.php

unsubscribe.php

<?php
$con = mysql_connect("localhost","dbuser","dbpass");
mysql_select_db("dbname", $con);

$sno = (integer)$_GET['id'];
$email = mysql_real_escape_string($_GET['username']);

$query = "update tablename set sub_status = 'UNSUBSCRIBED' where sno = $sno and email = '$email'";
mysql_query($query);
echo "You have Successfully unsubscribed. Thank you for using the service.";

 

Comment here if you have any queries.