Posts Tagged 'PHP'

March 27, 2012

Tips and Tricks - How to Secure WordPress

As a hobby, I dabble in WordPress, so I thought I'd share a few security features I use to secure my WordPress blogs as soon as they're installed. Nothing in this blog will be earth-shattering, but because security is such a priority, I have no doubt that it will be useful to many of our customers. Often, the answer to the question, "How much security do I need on my site?" is simply, "More," so even if you have a solid foundation of security, you might learn a new trick or two that you can incorporate into your next (or current) WordPress site.

Move wp-config.php

The first thing I do is change the location of my wp-config.php. By default, it's installed in the WordPress parent directory. If the config file is in the parent directory, it can be viewed and accessed by Apache, so I move it out of web/root. Because you're changing the default location of a pretty significant file, you need to tell WordPress how to find it in wp-load.php. Let's say my WordPress runs out of /webroot on my host ... I'd need to make a change around Line 26:

if ( file_exists( ABSPATH . 'wp-config.php') ) {
 
        /** The config file resides in ABSPATH */
        require_once( ABSPATH . 'wp-config.php' );
 
} elseif ( file_exists( dirname(ABSPATH) . '/wp-config.php' ) && ! file_exists( dirname(ABSPATH) . '/wp-settings.php' ) ) {
 
        /** The config file resides one level above ABSPATH but is not part of another install*/
        require_once( dirname(ABSPATH) . '/wp-config.php' );

The code above is the default setup, and the code below is the version with my subtle update incorporated.

if ( file_exists( ABSPATH . 'wp-config.php') ) {
 
        /** The config file resides in ABSPATH */
        require_once( ABSPATH . '../wp-config.php' );
 
} elseif ( file_exists( dirname(ABSPATH) . '..//wp-config.php' ) && ! file_exists( dirname(ABSPATH) . '/wp-settings.php' ) ) {
 
        /** The config file resides one level above ABSPATH but is not part of another install*/
        require_once( dirname(ABSPATH) . '../wp-config.php' );

All we're doing is telling the application that the wp-config.php file is one directory higher. By making this simple change, you ensure that only the application can see your wp-config.php script.

Turn Down Access to /wp-admin

After I make that change, I want to turn down access to /wp-admin. I allow users to contribute on some of my blogs, but I don't want them to do so from /wp-admin; only users with admin rights should be able to access that panel. To limit access to /wp-admin, I recommend the plugin uCan Post. This plugin creates a page that allows users to write posts and submit them within your theme.

But won't a user just be able to navigate to http://site.com/wp-admin? Yes ... Until we add a simple function to our theme's functions.php file to limit that access. At the bottom of your functions.php file, add this:

############ Disable admin access for users ############

add_action('admin_init', 'no_more_dashboard');
function no_more_dashboard() {
  if (!current_user_can('manage_options') && $_SERVER['DOING_AJAX'] != '/wp-admin/admin-ajax.php') {
  wp_redirect(site_url()); exit;
  }
}
 
###########################################################

Log in as a non-admin user, and you'll get redirected to the blog's home page if you try to access the admin panel. Voila!

Start Securing the WordPress Database

Before you go any further, you need to look at WordPress database security. This is the most important piece in my opinion, and it's not just because I'm a DBA. WordPress never needs all permissions. The only permissions WordPress needs to function are ALTER, CREATE, CREATE TEMPORARY TABLES, DELETE, DROP, INDEX, INSERT, LOCK TABLES, SELECT and UPDATE.

If you run WordPress and MySQL on the same server the permissions grant would look something like:

GRANT ALTER, CREATE, CREATE TEMPORARY TABLES, DELETE, DROP, INDEX, INSERT, LOCK TABLES, SELECT, UPDATE ON <DATABASE>.* TO <USER>@'localhost' IDENTIFIED BY '<PASSWORD>';

If you have a separate database server, make sure the host of the webserver is allowed to connect to the database server:

GRANT ALTER, CREATE, CREATE TEMPORARY TABLES, DELETE, DROP, INDEX, INSERT, LOCK TABLES, SELECT, UPDATE ON <DATABASE>.* TO <USER>@'<ip of web server' IDENTIFIED BY '<PASSWORD>';

The password you use should be random, and you should not need to change this. DO NOT USE THE SAME PASSWORD AS YOUR ADMIN ACCOUNT.

By taking those quick steps, we're able to go a long way to securing a default WordPress installation. There are other plugins out there that are great tools to enhance your blog's security, and once you've got the fundamental security updates in place, you might want to check some of them out. Login LockDown is designed to stop brute force login attempts, and Secure WordPress has some great additional features.

What else do you do to secure your WordPress sites?

-Lee

August 23, 2011

SOAP API Application Development 101

Simple Object Access Protocol (SOAP) is built on server-to-server remote procedure calls over HTTP. The data is formatted as XML; this means secure, well formatted data will be sent and received from SoftLayer's API. This may take a little more time to set up than the REST API but it can be more scalable as you programmatically interface with it. SOAP's ability to tunnel through existing protocols such as HTTP and innate ability to work in an object-oriented structure make it an excellent choice for interaction with the SoftLayer API.

This post gets pretty technical and detailed, so it might not appeal to our entire audience. If you've always wondered how to get started with SOAP API development, this post might be a good jumping-off point.

Authentication
Before you start playing with the SoftLayer SOAP API, you will need to find your API authentication token. Go into your portal account, and click the "Manage API Access" link from the API page under the Support tab. At the bottom of the page you'll see a drop down menu for you to "Generate a new API access key" for a user. After you select a user and click the "Generate API Key" button, you will see your username and your API key. Copy this API key, as you'll need it to send commands to SoftLayer's API.

PHP
In PHP 5.0+ there are built in classes to deal with SOAP calls. This allows us to quickly create an object oriented, server side application for handling SOAP requests to SoftLayer's API. This tutorial is going to focus on PHP 5.1+ as the server side language for making SOAP function calls. If you haven’t already, you will need to install the soap client for php, here is a link with directions.

Model View Controller

Model-View-Controller or MVC is a software architecture commonly used in web development. This architecture simply provides separation between a data abstraction layer (model), the business logic (controller), and the resulting output and user interface (view). Below, I will describe each part of our MVC "hello world" web application and dissect the code so that you can understand each line.

To keep this entry a little smaller, the code snippits I reference will be posted on their own page: SOAP API Code Examples. Protip: Open the code snippit page in another window so you can seamlessly jump between this page and the code it's referencing.

Model
The first entry on the API Code Examples page is "The Call Class," a custom class for making basic SOAP calls to SoftLayer's API. This class represents our model: The SOAP API Call. When building a model, you need to think about what properties that model has, for instance, a model of a person might have the properties: first name, height, weight, etc. Once you have properties, you need to create methods that use those properties.

Methods are verbs; they describe what a model can do. Our "person" model might have the methods: run, walk, stand, etc. Models need to be self-sustaining, that means we need to be able to set and get a property from multiple places without them getting jumbled up, so each model will have a "set" and "get" method for each of its properties. A model is a template for an object, and when you store a model in a variable you are instantiating an instance of that model, and the variable is the instantiated object.

  • Properties and Permissions
    Our model has these properties: username, password (apiKey), service, method, initialization parameters, the service's WSDL, SoftLayer's type namespace, the SOAP API client object, options for instantiating that client, and a response value. The SOAP API client object is built into php 5.1+ (take a look at the “PHP” section above), as such, our model will instantiate a SOAP API object and use it to communicate to SoftLayer's SOAP API.

    Each of our methods and properties are declared with certain permissions (protected, private, or public), these set whether or not outside functions or extended classes can have access to these properties or methods. I "set" things using the "$this" variable, $this represents the immediate class that the method belongs to. I also use the arrow operator (->), which accesses a property or method (to the right of the arrow) that belongs to $this (or anything to the left of the arrow). I gave as many of the properties default values as I could, this way when we instantiate our model we have a fully fleshed out object without much work, this comes in handy if you are instantiating many different objects at once.

  • Methods
    I like to separate my methods into 4 different groups: Constructors, Actions, Sets, and Gets:
    • Sets and Gets
      Sets and Gets simply provide a place within the model to set and get properties of that model. This is a standard of object oriented programing and provides the model with a good bit of scalability. Rather than accessing the property itself, always refer to the function that gets or sets the property. This can prevent you from accidentally changing value of the property when you are trying to access it. Lines 99 to the end of our call are where the sets and gets are located.

    • Constructors
      Constructors are methods dedicated to setting options in the model, lines 23-62 of the call model are our constructors. The beauty of these three functions is that they can be copied into any model to perform the same function, just make sure you keep to the Zend coding standards.

      First, let’s take a look at the __construct method on line 24. This is a special magic php method that always runs immediately when the model is instantiated. We don’t want to actually process anything in this method because if we want to use the default object we will not be passing any options to it, and unnecessary processing will slow response times. We pass the options in an array called Setup, notice that I am using type hinting and default parameters when declaring the function, this way I don’t have to pass anything to model when instantiating. If values were passed in the $Setup variable (which must be an array), then we will run the “setOptions” method.

      Now take a look at the setOptions method on line 31. This method will search the model for a set method which matches the option passed in the $setup variable using the built in get_class_methods function. It then passes the value and name of that option to another magic method, the __set method.

      Finally, let’s take a look at the __set and __get methods on lines 45 and 54. These methods are used to create a kind of shorthand access to properties within the model, this is called overloading. Overloading allows the controller to access properties quicker and more efficiently.

    • Actions
      Actions are the traditional verbs that I mentioned earlier; they are the “run”, “walk”, “jump”, and “climb” of our person model. We have 2 actions in our model, the response action and the createHeaders action.

      The createHeaders action creates the SOAP headers that we will pass to the SoftLayer API; this is the most complicated method in the model. Understanding how SOAP is formed and how to get the correct output from php is the key to access SoftLayer’s API. On line 77, you will see an array called Headers, this will store the headers that we are about to make so that we can easily pass them along to the API Client.

      First we will need to create the initial headers to communicate with SoftLayer’s API. This is what they should look like:

      <authenticate xsi:type="slt:authenticate" xmlns:slt="http://api.service.softlayer.com/soap/v3/SLTypes/">
          <username xsi:type="xsd:string">MY_USERNAME</username>
          <apiKey xsi:type="xsd:string">MY_API_ACCESS_KEY</apiKey>
      </authenticate>
      <SoftLayer_API_METHODInitParameters xsi:type="v3:SoftLayer_API_METHODInitParameters" >
          <id xsi:type="xsd:int">INIT_PERAMETER</id>
      </SoftLayer_API_METHODInitParameters>

      In order to build this we will need a few saved properties from our instantiated object: our api username, api key, the service, initialization parameters, and the SoftLayer API type namespace. The api username and key will need to be set by the controller, or you can add in yours to the model to use as a default. I will store mine in a separate file and include it in the controller, but on a production server you might want to store this info in a database and create a "user" model.

      First, we instantiate SoapVar objects for each authentication node that we need. Then we store the SoapVar objects in an array and create a new SoapVar object for the "authenticate" node. The data for the "authenticate" node is the array, and the encoding is type SOAP_ENC_OBJECT. Understanding how to nest SoapVar objects is the key to creating well formed SOAP in PHP. Finally, we instantiate a new SoapHeader object and append that to the Headers array. The second header we create and add to the Headers array is for initialization parameters. These are needed to run certain methods within SoftLayer’s API; they essentially identify objects within your account. The final command in this method (__setSoapHeaders) is the magical PHP method that saves the headers into our SoapClient object. Now take a look at how I access the method; because I have stored the SoapClient object as a property of the current class I can use the arrow operator to access methods of that class through the $_client property of our class, or the getClient() method of our class which returns the client.

      The Response method is the action which actually contacts SoftLayer’s API and sends our SOAP request. Take a look at how I tell PHP that the string stored in our $_method property is actually a method of our $_client property by adding parenthesis to the end of the $Method variable on line 71.

View
The view is what the user interprets, this is where we present our information and create a basic layout for the web page. Take a look at "The View" section on SOAP API Code Examples. Here I create a basic webpage layout, display output information from the controller, and create a form for sending requests to the controller. Notice that the View is a mixture of HTML and PHP, so make sure to name it view.php that way the server knows to process the php before sending it to the client.

Controller
The controller separates user interaction from business logic. It accepts information from the user and formats it for the model. It also receives information from the model and sends it to the view. Take a look at "The Controller" section on SOAP API Code Examples. I accept variables posted from the view and store them in an array to send to the model on lines 6-11. I then instantiate the $Call object with the parameters specified in the $Setup array, and store the response from the Response method as $Result in line 17 for use by the view.

Have Fun!
Although this tutorial seems to cover many different things, this just opens up the basic utilities of SoftLayer's API. You should now have a working View to enter information and see what kind of data you will receive. The first service and method you should try is the SoftLayer_Account service and the getObject method. This will return your account information. Then try the SoftLayer_Account service and the getHardware method; it will return all of the information for all of your servers. Take the IDs from those servers and try out the SoftLayer_Hardware_Server service and the getObject method with that id as the Init property.

More examples to try: SoftLayer Account, SoftLayer DNS Domain, SoftLayer Hardware Server. Once you get the hang of it, try adding Object Masks and Result Limits to your model.

Have Fun!

-Kevin

February 14, 2011

The Black Cat

"Dogma." "Religion." What comes to mind when you hear these words? In the real world, you might think of Christianity, Islam, or Judaism. In the political world, you might think of Communism vs. Freedom. Closer to home, you might think of "red state" and "blue state."

Computers are deterministic, logical machines, yet they too have all the trappings of the world's major religions and dogmas. The desktop world is dominated by Microsoft and Apple to use the religion metaphor. All computing worlds could be broken down into "proprietary" and "open source" if we are talking about dogma.

Relevant to this discussion, the web development world has three major religions in those two dogmas: Microsoft's ASP.NET, the PHP world, and the Java world. My platform of choice has always been ASP.NET.

I am pretty solid in my reasons for preferring it over all others, and also pretty clear about the accidental reasons I found myself in this camp. Much how someone born into a particular religion is likely to freely adopt it at some point, I too ended up adopting ASP.NET for reasons that were nothing more than accidental.

I consider myself a 'citizen of the world' in more ways than one, and the opportunity to work at SoftLayer was an opportunity I couldn't turn down. I had to check my biases at the door, open my mind, and see how this side of the aisle does business. (And as if to remind me that a dogmatic shift has occurred in my professional life, Fox News continues to greet me every morning at the top of the stairs.)

To admit just some of my biases: How on earth did you build an enterprise-grade portal with a weakly typed language that doesn't require something as basic as a compiler? More importantly: Why? How does one work with such a thing? Some of you still use VI?? Seriously?

Fast forward about six months — just enough to say I am "proficient" in PHP and to have an exposure to the database side of things. The journey and rants are long and technical, but it should come as no surprise that I still prefer the Microsoft ecosystem over one based on PHP. I find it easier to work with, faster, and less error-prone than the alternative. The language is more structured, the tooling is better, and the framework better established and developer-oriented.

Humor me with this for a moment.

Assume for the sake of argument that my belief is correct — that Microsoft's offerings are indeed better than PHP's on every metric a developer can measure. If this is true, one might reasonably conclude that SoftLayer erred in its choice of development platform. Even though I will be the first to evangelize the virtues of the Microsoft ecosystem, I'll also be the first to say that this conclusion is wrong.

The conclusion is wrong because in asking the "Why?" in "Why SoftLayer chose the platform it did," I approached the question from the perspective of what's best for the developer. The question should have instead been phrased as: "What does SoftLayer's choice of platform say about our core values?"

It isn't exactly open source. Place the source code on any laptop, and you'll get the modern-day equivalent of summary execution: You will be fired.

It isn't developer convenience. It isn't needed. From what I've seen here, the developers have used their tools in a more extensive and architecturally correct way than I have in my time in the ASP.NET ecosystem.

The elusive answer can be summed up in one word: Independence. Fierce independence if you're into using superlatives.

While the Microsoft ecosystem may be the easiest on developers, it comes at price. Microsoft's ultimate responsibility is to the thousands of people that use its tools, so it has to steer its platforms in a way that fit the disparate needs of the many developers who rely on them. In relying on its own software, built on open-source offerings, SoftLayer can steer its platform in a way that benefits SoftLayer ... It has only its own needs to consider.

The soundness of this reality — and indeed, the necessity of being fully independent when one's core offering is the basic infrastructure that runs people's businesses should be obvious.

Very often we become overprotective of our dogmas, and fear that which we do not fully understand. To that end, I try to remember the words of an unlikely capitalist: "It doesn't matter if a cat is black or white, so long as it catches mice."

-George

January 12, 2011

'What\'s with These "Quote" Things?'

'We\'ve' . "all $een" . 'this' . $problem . 'before' . $and->it . ((1==1) ? 'seems' : 'dosen\'t seem') . sprintf('about time to %s things', 'clarify');

PHP string handling can be a tough concept to wrangle. Developers have many options: single / double quotes, concatenation and various string manipulation functions. The choices you make have a significant impact on the readability and performance of your script. Let's meet the line-up:

The Literal
Single quotes are used to define a string whose contents should be taken literally. What this means is that PHP will not attempt to expand any content contained between the ' '.

This is the way to tell your favorite Hypertext Preprocessor, "That little guy? Don't worry about that little guy."

In most cases this is the de-facto standard for strings. However, when a decent number of variables become involved it tends to become difficult to keep your quotes accounted for. When combining simple strings with variables and single quotes, the "." operator is needed between each variable/string. That "." is known as the concatenation operator.

Input:
$date = 'Yesterday';
$location = 'outside';
$item = array ( 'description' => 'lovely', 'name' => 'butterfly');
$content = $date . ' I went ' . $location . ' and caught a ' . $item['description'] . ' ' . $item['name'];

Output: Yesterday I went outside and caught a lovely butterfly

The Interpreted
Using double quotes will cause PHP to look a little closer into the string to find anywhere it can "read between the lines." Variables and escape characters will be expanded, so you can reference them inline without the need for concatenation. This can be useful when creating strings which include pre-defined variables.

Input:
$file = 'example.jpg'
$content = "<a href=\"http://www.example.com/$file\">$file</a>"

Output: <a href="http://www.example.com/example.jpg">example.jpg</a>

In previous versions of PHP there was a significant performance difference between the use of single v. double quotes. In later versions performance variations are negligible. The decision of one over the other should focus on feature and readability concerns.

The Thoughtful
Unlike single and double quotes, the sprintf function comes to the table with a few cards up its sleeve. When provided with a formatting "template" and arguments, sprintf will return a formatted string.

Input:
$order = array ( 'item' => 'RC Helicopters', 'status' => 'pending');
$content = sprintf('Your order of %s is currently %s', $order['item'], $order['status']);

Output: Your order of RC Helicopters is currently pending

When constructing a complex string such as XML documents, sprintf allows the developer to view the string with placeholders rather than a mish-mash of escaped quotes and variables. In addition sprintf is able to specify the type of variable, change padding/text alignment, and even change the order in which it displays the variables.

The debate over the most efficient method of string definition has raged for years and will likely continue ad infinitum. However, when the benchmarks show their performance as almost identical, it leaves you with one major question: What works the best for your implementation? Typically my scripts will contain all of the methods above, and often a combination of them.

print(sprintf('The %s important thing is that %s give them all a try and see for %s', 'most', 'you', 'yourself'));

-Phil

Subscribe to php