Archives

All posts by Anil Kumar Vishwakarma

Setup a Failed Order Notification goes to Customer Billing Email for WooCommerce

Published June 21, 2017 by Anil Kumar Vishwakarma

There are various reasons why an Order Failed. The most widely recognised reason is a blunder in the payment processor. This could be a one time thing or possibly a glitch with the payment processor. Regardless it is great to catch up with the client. It would be an immense disgrace on the off-chance that you didn’t do anything as the client was at that point in the checkout/purchasing process and didn’t get the chance to finish their request.

SETTING UP A FAILED ORDER EMAIL NOTIFICATION

There is no user interface for this available in WooCommerce so I’m posting a code snippet you can use. With this code snippet the functionality will be added directly to your site without the use of a plugin. It will automatically send simple email notification with a short message to the Customer Billing email notifying him/her that there has been a failed order.

 

<?php
/**
* Add a failed order email notification
*/
function sp_failed_order_email_notification( $order_id ) {
$order = wc_get_order( $order_id );
$to = $order->billing_email;
$subject = A order failed, action required;
$message = sprintf( __( %1$s went to the `failed` order status. This may require action to follow up., text-domain ), <a class=”link” href=” . admin_url( post.php?post= . $order_id . &action=edit ). “> . sprintf( __( Order #%s, woocommerce), $order->get_order_number() ) . </a> );
$headers[] = From: Me Myself <me@example.net>;
$headers[] = Cc: Some Name <name@email.com>; // Possible CC
$headers[] = Content-Type: text/html;;
$headers[] = charset=UTF-8;
wp_mail( $to, $subject, $message, $headers );
}
add_action( woocommerce_order_status_failed, sp_failed_order_email_notification );

file_exists

Published June 12, 2017 by Anil Kumar Vishwakarma

file_existsChecks whether a file or directory exists

Testing whether a file exists


<?php
$filename 
'/path/to/foo.txt';

if (file_exists($filename)) {
echo 
“The file $filename exists”;
} else {
echo 
“The file $filename does not exist”;
}
?>

Laravel Setup

Published May 29, 2017 by Anil Kumar Vishwakarma

Server Requirements

The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the Laravel Homestead virtual machine, so it’s highly recommended that you use Homestead as your local Laravel development environment.

However, if you are not using Homestead, you will need to make sure your server meets the following requirements:

  • PHP >= 5.6.4
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Installing Laravel

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

Via Laravel Installer

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system.

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel’s dependencies already installed:

laravel new blog

Via Composer Create-Project

Alternatively, you may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project --prefer-dist laravel/laravel blog

Local Development Server

If you have PHP installed locally and you would like to use PHP’s built-in development server to serve your application, you may use the serve Artisan command. This command will start a development server at http://localhost:8000:

php artisan serve

cURL Requests with PHP

Published February 6, 2017 by Anil Kumar Vishwakarma

Introduction

cURL allows transfer of data across a wide variety of protocols, and is a very powerful system. It’s widely used as a way to send data across websites, including things like API interaction and oAuth. cURL is unrestricted in what it can do, from the basic HTTP request, to the more complex FTP upload or interaction with an authentication enclosed HTTPS site. We’ll be looking at the simple difference between sending a GET and POST request and dealing with the returned response, as well as highlighting some useful parameters.

Basics

Before we can do anything with a cURL request, we need to first instantiate an instance of cURL – we can do this by calling the function curl_init();, which returns a cURL resource. This function takes one parameter which is the URL that you want to send the request to, however, in our case, we’ll hold off doing that for now and set it an alternatively way later.

Settings

Once we’ve got a cURL resource, we can begin to assign some settings, below is a list of some of the core ones that I set

  • CURLOPT_RETURNTRANSFER – Return the response as a string instead of outputting it to the screen
  • CURLOPT_CONNECTTIMEOUT – Number of seconds to spend attempting to connect
  • CURLOPT_TIMEOUT – Number of seconds to allow cURL to execute
  • CURLOPT_USERAGENT – Useragent string to use for request
  • CURLOPT_URL – URL to send request to
  • CURLOPT_POST – Send request as POST
  • CURLOPT_POSTFIELDS – Array of data to POST in request

We can set a setting by using the curl_setopt() method, which takes three parameters, the cURL resource, the setting and the value. So, to set the URL that we’re sending the request to as http://testcURL.com:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://testcURL.com');

As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:

$curl = curl_init('http://testcURL.com');

It is possible to set multiple settings at one time by passing through an array of settings and values to the function curl_setopt_array():

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com'
));

Sending request

When all of the options are sent, and the request is ready to send, we can call the curl_exec() method which will execute the cURL request. This function can return three different things:

  • false – if there is an error executing the request
  • true – if the request executed without error and CURLOPT_RETURNTRANSFER is set to false
  • The result – if the request executed without error and CURLOPT_RETURNTRANSFER is set to true

Using the previous example, where we are wanting to get the result back, we would use the following:

$result = curl_exec($curl);

With $result now containing the response from the page – which might be JSON, a string or a full blown site’s HTML.

Close Request

When you’ve sent a request and got the result back, you should look to close the cURL request so that you can free up some system resources, this is as simple as calling the curl_close() method which as with all other functions takes the resource as its parameter.

GET Request

A GET request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET requests. If you want to send parameters along in the request you simply append them to the URL as a query string such as http://testcURL.com/?item1=value&item2=value2.

So for example to send a GET request to the above URL and return the result we would use:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

POST Request

The sole difference between the POST and GET request syntax is the addition of one setting, two if you want to send some data. We’ll be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS

So for example switching the above GET request to be a POST request, we would use the following code:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

There you have a POST request that will work the same as our GET request above and return the response back to the script so that you can use it as you want.

Errors

As much as we all hate errors, you really need to take care to account for any eventuality with cURL as ultimately you will not have control over the site(s) that you are sending your request to, you cannot guarantee that the response will be in the format that you want, or that the site will even be available.

There are a few functions that you can use to handle errors and these are:

  • curl_error() – returns a string error message, will be blank '' if the request doesn’t fail.
  • curl_errno() – which will return the cURL error number which you can then look up on this page listing error codes.

An example usage would be:

if(!curl_exec($curl)){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}

You might want to look at using the setting CURLOPT_FAILONERROR as true if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.

curl_exec($theEnd);

cURL is a behemoth, and has many many possibilities. Some sites might only serve pages to some user agents, and when working with APIs, some might request you send a specfici user agent, this is something to be aware of. If you want to have a play with some cURL requests, why not have a go at playing with oAuth with Instagram.

HOW WORDPRESS SITES GET HACKED (AND WHAT TO DO ABOUT THAT)

Published January 20, 2017 by Anil Kumar Vishwakarma

Why Would Anyone Want To Hack Your WordPress Site?

wp-hacked

Especially owners of smaller websites often think themselves an unlikely target for hackers.

After all, why would anyone care about your tiny blog? What could hackers possibly must gain from compromising it?

However, when it comes to being hacked, traffic size, or popularity are not the deciding factors.

Most Hacking Attacks Are Automated

One of the main reasons hackers don’t differentiate between the sites of different sizes is that attacks are largely done automatically.

If you think someone typed your site address into a browser bar and had a good snoop around til they found something, you’d be dead wrong. This type of approach potential completely uneconomic from a hacker’s point of view.

Instead, just like search engines, hackers use bots to crawl the net. However, instead indexing content, their bots ascertain known vulnerabilities. Automating the process allows hackers to attack many sites at once and thus increase their odds of success dramatically. Economies of scale at its best.

Thus, if your site gets hacked, it’s probably because it show on the radar of an automated script, not because someone consciously decided to target you.

What’s In It for Them?

Still, the question remains: Why would anyone put in that effort? What do they take to the air of it?

Naturally, if you are running a web shop that processes a lot of financial information like affinity card numbers, that prospective a sensible target for hackers.

However, if your site does not contain any government secrets or other people’s banking info, why would they be interested in your site?

Well, even in those cases, hacking your site could benefit individuals with bad intentions in different ways:

  • Drive-by-downloads — Hackers can use your site to infect your visitors’ computers with malware like back doors, key trackers, ransomware, viruses, or other malicious software in order to capture information they can use for their own gain.
  • Redirections — Sometimes hackers will redirect visitors from your site to other websites that generate affiliate income for them.
  • System resources — Another possibility is that they take over your server and use the hardware for sending out spam emails, performing denial of service or brute force attacks and more. Of course, this will easily get your server — and your site — put on a blacklist or jack up your hosting cost if it is based on usage.

As you can see, your site is interesting to hackers no matter of its size or popularity. Therefore, every website owner is a potential victim.

How Do WordPress Websites Get Hacked?

Now that we know why people try to hack WordPress websites, let’s look at the most common ways they succeed in doing so.

According to an infographic by WP Template, these are the most common points of entry into WordPress websites:

  • 41% get hacked through vulnerabilities in their hosting platform
  • 29% by means of an insecure theme
  • 22% via a vulnerable plugin
  • 8% because of weak passwords

As you can see, the first access is most often the hosting provider.

That doesn’t necessarily mean your site has been targeted directly. It is also possible that another site in a shared hosting environment got hacked and took the others down in the process.

What’s alarming is that more than half of all successful hacks make the cut WordPress themes and plugins. This part, therefore, deserves special attention and we will question it in further detail below.

The rest of the sites sicken insufficient password protection, making them vulnerable to vigor attacks.

While eight percent doesn’t simulate a lot, be aware that we are question hundreds of thousands of websites here. Even therefore a small percentage of them has weak login information, that number still comes till thousands of vulnerable sites.

Alright, as we know what makes WordPress vulnerable, what can we do about it?

How To Keep Your Site Safe

WordPress security is all about proactivity. You know what they say, an ounce of prevention is worth a pound of cure, especially on the web.

Based on the information above, here are some of the most effective ways to keep your WordPress website from being hacked.

Choose A High-Quality Hosting Provider

One thing that should be clear from the statistics is that the quality of your hosting provider has a large guide the security of your site.

Therefore, choosing a reputable provider that puts a premium on security should be on the top of your list of equal keep your site from being hacked.

Besides supporting the latest versions of PHP and MySQL, that means they should at least perform regular scans for malware and daily backups.

(The latter really saved my bacon once, I can only stress this point!)

For us as WordPress users, it’s also a good idea to accompany a hosting provider that is read running sites based on the platform and offers a WordPress-optimized environment further knowledgeable staff.

You can find a test of leading WordPress hosting companies here.

Also, if you can, stay away from pure shared hosting solutions to avoid “bad neighbor” problems such as the one mentioned above.

Perform Regular Backups

Even though the steps mentioned on this list will seriously harden your site’s security, there is no 100 percent guarantee it won’t get hacked anyway.

That’s not because WordPress is by default insecure (far from it) but because anything connected to the Internet is always somewhat at risk, after all how small the level of threat might be.

Therefore, while it’s good to hope profitable, it’s also important to foresee the worst and for website owners, that means backing up on a regular basis.

If you already have a quality host, they should make out this part for you and also keep your site’s copy in a safe location.

For everyone else and those who want expected extra sure, implementing a reliable backup solution is a must and you have many to pick from:

Pick one and set it up now. I’ll wait. No seriously, go do it now.

Fortify Your Login

Besides the hosting environment, weak passwords and login information are also responsible for a good number of hacks.

This is especially true for brute force attacks in which hackers run a script that inputs random passwords and usernames until one fits.

As stupid as this sounds, it works! Look at last year’s worst passwords and you will understand why.

As a first line of defense, adhere to the following best practices for WordPress login information:

  • Frequently change your passwords (seriously, put a reminder in your calendar now)
  • Avoid using the admin username (which used to be the default in older WordPress versions and is therefore often targeted first)
  • Create a strong password (either via an external service or the password strength meter included in WordPress)
  • Oblige other users to do the same with Force Strong Passwords
  • Store passwords in a secure place like LastPass

Apart from that, you can further up your login security with the following methods:

  • Limit login attempts — Plugins like Login LockDown and Login Security Solution enable you to constrain the number of login attempts from a single IP address within a certain amount of time. Perfect for keeping brute force attacks at bay.
  • Employ two-step authentication — Adds a second layer of security that can only be passed by means of your cell phone, social network account or else. Options include Duo Two-Factor Authentication, OpenID, and Clef.
  • Hide your login page — Moving wp-admin and wp-login to non-standard addresses makes it harder for hackers to attack them. You can do so via Rename wp-login.php, HideLogin+ or Lockdown WP Admin.

WordPress login protected? Then let’s move on to other things.

Add SALTs To wp-config.php

WordPress security keys were introduced in WordPress 2.6.

They are random lines of characters that are used to encrypt information stored in user cookies, making them harder to crack and use against your site.

The keys go into your wp-config.php file where it says this:

Replace them with code from the WordPress SALT generator, it will end up looking something like that:

(don’t use these, generate your own!)

Set A Unique Table Prefix

You will know the WordPress table prefix from the 5-minute install.

install-wordpress-locally-wordpress-setup

By default, it is set to wp_, which is common knowledge also in hacker circles. For that reason, leaving it as is will make your site more vulnerable to SQL injections.

To further increase your security, it’s a good idea to change it to something random and impossible to guess like k5ns7ue03ia933_.

When you set up a new site, you can do this from the get-go. However, even with an existing site, it isn’t all that hard to change.

The easiest way to do so is using iThemes Security. The plugin can perform all necessary operations at the touch of button.

An alternative, yet more time consuming, way is to do it manually. In case you are unable to change the table prefix via plugin, use this guide to make the necessary changes.

Keep WordPress Up To Date

Updates do not only bring new WordPress features and code improvements but also address security issues of older versions.

That’s especially true for security updates whose only purpose is to fix this kind of thing.

According to WP WhiteSecurity, more than 70% of the top WordPress websites on the web showed some sort of vulnerability that was due to running an outdated version of WordPress.

For that and other reasons, it’s important that you keep up with the WordPress update cycle. It’s also why since WordPress 3.7, maintenance and security updates are being applied automatically.

It’s possible to enable automatic application for major releases as well, all it takes is to add the following line of code to wp-config.php:

However, with major updates, the chance is higher that they will break your site. For that reason, you might want to stay with the standard setting but make a commitment to apply updates as soon as they come out.

Hide the WordPress Version Number

Talking about staying up to date: By default, WordPress adds a meta tag to your site’s head section that shows off which version of the CMS you are running.

Especially if your site is not up to date (though you should know better by now), this will help hackers uncover known vulnerabilities.

Below is a useful piece of code that stops WordPress from doing so:

Just add it to your functions.php file and you are done with it.

Maintain WordPress Themes and Plugins

As we have seen above, more than half of successful hacking attempts happen through vulnerable WordPress plugins and themes.

While that sounds dramatic, it’s no reason to doubt the WordPress ecosystem as a whole.

Even the best, most well-maintained plugins out there can have a security problem. Mistakes happen and are in most cases fixed before they become a huge problem.

Yet, to minimize the risk to your site, here are a few guidelines how to deal with plugins and themes:

  1. Eliminate what you can — To reduce the possibility of a vulnerability, get rid of every plugin and theme on your site that is not absolutely necessary. Oftentimes, you will be surprised at how many are just lingering around without actually fulfilling any function. It can also seriously speed up your site.
  2. Update regularly — Just like WordPress core, the components that make the cut should be kept up to date. That also means if a plugin hasn’t been updated by its author for longer than a year, you are probably better off looking for an alternative that is being actively maintained.
  3. Check before installing — Avoid installing plugins and themes from untrustworthy sources, especially free ones. When you do add components to your site, run them through Theme Check, Plugin Check, and the database for plugin vulnerabilities first.

There are also ways to update themes and plugins automatically, however, just like with core updates, I recommend performing them manually in order to avoid breaking your site without you knowing it.

Other Tactics To Keep Your WordPress Site From Being Hacked

Lastly, here are a number of smaller steps you can take to increase your website’s security level.

1. Set Correct File Permissions

If the file permissions on your server aren’t set up right, third parties might have an easier time corrupting them. The permissions should be set as follows:

  • 755 or 750 for all directories
  • 644 or 640 for files
  • 600 for wp-config.php

For more information on this topic, check the WordPress Codex or this article. If you are unsure about this setting on your server, ask your host for help.

2. Disable The Plugin and Theme Editor

The internal WordPress editor enables users to make changes to files right from the backend.

While this can come in handy, it also means that if someone gets access to your site, they can use this feature to take it down in no time.

For that reason, it might be a good idea to turn the editor off and exclusively work on files via FTP.

This, again, is a matter of adding code to wp-config.php:

3. Turn Off PHP Reporting

If a plugin or theme causes an error, the message that gets displayed can contain information about your directories and file system that hackers might use to compromise your system.

So, while you are at it, add the following to your crafty wp-config.php file to disable them:

Think Your Site Has Been Compromised?

While there can be obvious signs that your site has been hacked, oftentimes you won’t notice at all.

If you have a suspicion that your website may be compromised or just want to make sure everything is in order, here are a few tools to check your site for malicious code and other issues:

If you find that your site has indeed been compromised, this detailed guide will help your recover it.

In Short: Be Proactive

Having your WordPress website hacked or compromised is a horror that few site owners want to experience or won’t soon forget if they already have.

Recovering from a full-blown successful hack takes a lot of energy, nerves and often money.

However, security issues are part of the reality of running a website and precaution is better than dealing with the aftermath.

Thankfully, WordPress itself is generally very safe. Most of the time the point of entry for hackers are the hosting environment, vulnerable plugins and themes as well as weak login information.

Following the advice the list above will help you address the most common issues and make your site a lot less vulnerable.

Many of the measures mentioned here are also part of all-in-one security solutions that you might want to check out:

If you do get hacked, it’s best to stay calm and work towards a solution than freaking out and doing something rash.

With a backup plan in place, you are well prepared to get back to normal and bounce back quickly.

Have you had an experience with a compromised site? How did you solve it? Let us know in the comments section below!