Posted in Curl, PHP

cURL Requests with PHP

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.

Posted in wordpress, Wordpress Security

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

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!

Posted in Custom Post Type, wordpress

Display Custom Post Type on Page Using Shortcode By their Title, Content, Featured image etc

Display Custom Post Type on Page Using Shortcode

for this First install this plugin https://wordpress.org/plugins/display-posts-shortcode/ After this add function as mention below code:


add_shortcode('query', 'shortcode_query');

function shortcode_query($atts, $content){
extract(shortcode_atts(array( // a few default values
‘posts_per_page’ => ’10’,
‘caller_get_posts’ => 1,
‘post__not_in’ => get_option(‘sticky_posts’),
), $atts));

global $post;

$posts = new WP_Query($atts);
$output = ”;
if ($posts->have_posts())
while ($posts->have_posts()):
$posts->the_post();

// these arguments will be available from inside $content
$parameters = array(
‘PERMALINK’ => get_permalink(),
‘TITLE’ => get_the_title(),
‘CONTENT’ => get_the_content(),
‘EXCERPT’ => get_the_excerpt(),
‘COMMENT_COUNT’ => $post->comment_count,
‘CATEGORIES’ => get_the_category_list(‘, ‘),
// add here more…
);

$finds = $replaces = array();
foreach($parameters as $find => $replace):
$finds[] = ‘{‘.$find.’}’;
$replaces[] = $replace;
endforeach;
$output .= str_replace($finds, $replaces, $content);

endwhile;
else
return; // no posts found

wp_reset_query();
return html_entity_decode($output);
}

After adding above Code in functions.php add new attribute into the shortcode : post_type
Shortcode Example is : [query post_type=job posts_per_page=-1]

Posted in wordpress

How to add a Menu to your WordPress Theme footer.php

Adding a Menu to the Footer

When I create a custom WordPress theme for my clients I like to create a footer menu as well. This is useful for adding links to contact, sitemap and back to top. Here are the steps to edit your own theme.

In this tutorial you are going to edit the functions.php, footer.php, and style.css files. If you modify theme files directly your customization will disappear when the theme updates. So create a child theme first.

Create a secondary menu area

Add the following code to the functions.php file for your twenty ten child theme

// This theme uses wp_nav_menu() in two locations.  
register_nav_menus( array(  
  'primary' => __( 'Primary Navigation', 'twentyten' ),  
  'secondary' => __('Secondary Navigation', 'twentyten')  
) );

Tell WordPress where the secondary menu should be used

Open your footer.php file and add the following code wherever you want the secondary menu to appear.

capture image

Style the menu

Open your css file and create a class bottomMenu and add your own styling. Here is an example.

.bottomMenu { display: block; width:960px;}
.bottomMenu ul { display:inline; float:right;}
.bottomMenu li { list-style-type: none; display: inline; font-size: 12px; }
.bottomMenu li a {
	color:#000;
	line-height:15px;
	text-decoration:none;
	font-weight:normal;
	border-right: thin solid #000;
	padding: 0 7px 0 3px;
}
.bottomMenu li a:hover { color:#ccc; text-decoration:underline;}
.bottomMenu li:last-child > a {border-right: none;} /* remove pipe from last item */

Create the Menu

  • Go to Appearance -> Menus and click the + to create a new menu
  • Name the menu e.g. “footer”
  • Add published pages such as contact, sitemap, privacy policy to the menu
  • Drag and drop menu items to order them
  • Save the menu
  • Set the Secondary Menu (you created this with the edit to the functions.php file) on the left side to use this newly created menu
Posted in wordpress

Mobile Device Trick

Use media queries to hide content on screens with smaller resolutions, or show content on screens with a higher resolution. Easy way to hide pictures or unnecessary blocks of content for mobile devices. Good addition to put in your media queries to lay content out differently.

@media screen and (max-width: 480px){ }

@media screen and (max-width: 568px){ }

@media screen and (max-width: 667px){ }

@media screen and (max-width: 736px){ }

@media screen and (max-width: 600px){ }

@media screen and (max-width: 768px){ }

 

Note : You can test your website friendly on all devices from here : www.responsinator.com

Posted in wordpress

Custom Post Type

Custom Post type creation by using existing theme Functions.php file

add_action( 'init', 'rv_invoice_cpt' );
function rv_invoice_cpt() {
 $labels = array(
 'name' => _x( 'Invoice', 'post type general name', 'engwp' ),
 'singular_name' => _x( 'Invoice', 'post type singular name', 'engwp' ),
 'menu_name' => _x( 'Invoices', 'admin menu', 'engwp' ),
 'name_admin_bar' => _x( 'Invoice', 'add new on admin bar', 'engwp' ),
 'add_new' => _x( 'Add New', 'Invoice', 'engwp' ),
 'add_new_item' => __( 'Add New Invoice', 'engwp' ),
 'new_item' => __( 'New Invoice', 'engwp' ),
 'edit_item' => __( 'Edit Invoice', 'engwp' ),
 'view_item' => __( 'View Invoice', 'engwp' ),
 'all_items' => __( 'All Invoices', 'engwp' ),
 'search_items' => __( 'Search Invoices', 'engwp' ),
 'parent_item_colon' => __( 'Parent Invoice:', 'engwp' ),
 'not_found' => __( 'No Invoices found.', 'engwp' ),
 'not_found_in_trash' => __( 'No Invoices found in Trash.', 'engwp' )
 );
 $args = array(
 'description' => __( 'Invoice', 'engwp' ),
 'labels' => $labels,
 'supports' => array( 'title' ),
 'hierarchical' => false,
 'public' => true,
 'publicly_queryable' => true,
 'query_var' => true,
 'rewrite' => array( 'slug' => 'invoice' ),
 'show_ui' => true,
 'menu_icon' => 'dashicons-media-spreadsheet',
 'show_in_menu' => true,
 'show_in_nav_menus' => false,
 'show_in_admin_bar' => true,
 // 'menu_position' => 5,
 'can_export' => true,
 'has_archive' => false,
 'exclude_from_search' => true,
 'capability_type' => 'post',
 );
 register_post_type( 'invoice', $args );
}