Tag: kranthi

Limiting The Visibility Of WordPress Posts Via Usernames


  

Controlling who is able to view a post is a simple task once the system is established. Limiting access to certain users has several applications, such as enabling a design studio to distribute artwork to its various clients, or enabling a small school to arrange for homework to be posted online using a cheap and easy solution.

lpvuau-splash1

The easiest method to get this system working is to make the recipients of the information “subscribers� (since they need not be able to post) and the distributors of information “authors� (since they should only be able to edit their own posts). This system eliminates several headaches for the webmaster by managing who has access to particular posts. The username would be used to identify who is allowed to view certain posts, since it is unique and, for the most part, constant.

The Basics

What Will You Need?

  • WordPress 3.1 or later
  • Members of various roles
  • The ability to modify your theme’s files
  • Basic knowledge of PHP and MySQL

What Is a Username?

In general, a username is a means by which to identify and verify a user. It is not the only way to identify a user, but remembering a username is easier for the person logging in than having to remember a random user ID. A username can be made unique to an individual, unlike a person’s name or email address (family members may share the same name, or even the same email address). This ease of use and uniqueness is why usernames are used on most websites that require people to sign up in order to access the website or certain of its features.

To WordPress, a username is means of identifying a user. Paired with a password, a username enables someone to access their profile and, depending on their permissions within WordPress, to access to the administrative pages of the website. A username can be used for many functions in the operation and management of a website, such as karma, prestige, user roles and expulsion.

A WordPress username is unique and impossible for the average user to change. Thus, the system is a potentially reliable means of identifying individuals. This reliability is important for a system in which a post must be visible to only a few people. The permissions of a post should not alter merely because someone has changed their name or email address.

Screenshot of a WordPress single user page
The user page in a WordPress installation. Note that “Usernames cannot be changed.�

Setting Up The Back End

In order for an author to be able to set permissions for visibility, a method of selecting users must be set up on the post editing page. We could accomplish this by one of several methods, one of the easiest and most efficient of which is to create a meta box (or widget) in the post editing page that allows the author to add custom information, as required by a theme or plugin. This information enables us to tell the theme which members should have viewing rights to particular posts.

A Basic Custom Meta Box

Justin Tadlock’s article “How to Create Custom Post Meta Boxes in WordPress� explains how to create meta boxes, and we’ll reuse that code here.

Let’s assume we’re dealing with a website for a music school named “Smashing Magazine’s Fancy Flautists.â€� We will use the name smashing_flautist_access in the code for the back end to distinguish it from other custom functions. Justin’s code is a great starting point for this project, but it needs a little customization for our purpose. Place the following code in your theme’s functions.php, and modify the various labels according to your project.

/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );

/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {

	/* Add meta boxes on the 'add_meta_boxes' hook. */
	add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );

	/* Save post meta on the 'save_post' hook. */
	add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
}

/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {

	add_meta_box(
		'smashing-flautist-access',			// Unique ID
		esc_html__( 'Post Viewing Permission', 'smashing_flautist' ),		// Title
		'smashing_flautist_access_meta_box',		// Callback function
		'post',					// Admin page (or post type)
		'normal',					// Context
		'default'					// Priority
	);
}

/* Display the post meta box. */
function smashing_flautist_access_meta_box( $object, $box ) { ?>

	<?php wp_nonce_field( basename( __FILE__ ), 'smashing_flautist_access_nonce' ); ?>

	<p>
		<label for="smashing-flautist-access"><?php _e( "Enter the username of the subscriber that you want to view this content.", 'smashing_flautist' ); ?></label>
		<br />
		<input class="widefat" type="text" name="smashing-flautist-access" id="smashing-flautist-access" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_flautist_access', true ) ); ?>" size="30" />
	</p>
<?php }

With Justin’s code, modified for this project, we should have a custom meta box that looks like this:

Screenshot of a basic meta box
A basic meta box positioned below the post editing box.

Adding Ease to the Selection

This box can be used as is, and the author would simply input the members who they want to allow to view a post. This would work well if each author had very few usernames to remember; but if the author has long list of usernames to choose from, then a list of members would have to be displayed, and there would have to be a system that allows the authors to choose members from the list. Add the following code to the area just below the original box, just after the closing paragraph tag, to display a list of users with their names, along with radio buttons to grant one of the users access to the current post.

<table class="smashing-flautist-access">
<tr align="left">
<th>Username</th>
<th>    </th>
<th>Visiblity</th>
<th>    </th>
<th>Name</th>
</tr>
<?php
global $post;
	$users = get_users('role=subscriber');
	foreach ($users as $user) {
			$user_info = get_userdata( $user->ID );
			if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
			echo "<tr>";
			echo "<td>$user->user_login</td><td>    </td>";
			echo "<td align=\"center\"><input type=\"radio\" name=\"smashing-flautist-access\" id=\"smashing-flautist-access\" value=\"$user->user_login\" " . $ifchecked ."/></td><td>    </td>";
			echo "<td>$user_info->last_name, $user_info->first_name</td><td>    </td>";
			echo "</tr>";
			unset($ifchecked);

	} ?></table>

If everything goes well, you should end up with a box underneath the post editor that looks similar to the image below. The form containing the radio buttons gets a list of users that are listed as subscribers and makes the selection of the student with viewing permissions easy, all without the post’s author having to remember any usernames.

Screenshot of a meta box with user information
A meta box that contains a method to select the particular name and information of each user.

Saving the List

Now that we have generated a list that makes it easy for the authors to pick which members they want to be able to view particular posts, we have to create a system to add the list to WordPress’ MySQL database so that we can retrieve it later. We also need a way to tell WordPress to update this list of usernames in case the author decides later to add or remove someone from a particular post’s list of authorized viewers. The code provided by Justin does excellent work; place his code below in your theme’s functions.php, just after the function that sets up the custom meta box.

/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );

/* Save the meta box's post metadata. */
function smashing_flautist_access_save_meta( $post_id, $post ) {

	/* Make all $wpdb references within this function refer to this variable */
	global $wpdb;

	/* Verify the nonce before proceeding. */
	if ( !isset( $_POST['smashing_flautist_access_nonce'] ) || !wp_verify_nonce( $_POST['smashing_flautist_access_nonce'], basename( __FILE__ ) ) )
		return $post_id;

	/* Get the post type object. */
	$post_type = get_post_type_object( $post->post_type );

	/* Check if the current user has permission to edit the post. */
	if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
		return $post_id;

	/* Get the posted data and sanitize it for use as an HTML class. */
	$new_meta_value = ( isset( $_POST['smashing-flautist-access'] ) ? sanitize_html_class( $_POST['smashing-flautist-access'] ) : '' );

	/* Get the meta key. */
	$meta_key = 'smashing_flautist_access';

	/* Get the meta value of the custom field key. */
	$meta_value = get_post_meta( $post_id, $meta_key, true );

	/* If a new meta value was added and there was no previous value, add it. */
	if ( $new_meta_value && '' == $meta_value )
		{
		add_post_meta( $post_id, $meta_key, $new_meta_value, true );
		$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
		}
	/* If the new meta value does not match the old value, update it. */
	elseif ( $new_meta_value && $new_meta_value != $meta_value )
		{
		update_post_meta( $post_id, $meta_key, $new_meta_value );
		$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
		}
	/* If there is no new meta value but an old value exists, delete it. */
	elseif ( '' == $new_meta_value && $meta_value )
		{
		delete_post_meta( $post_id, $meta_key, $meta_value );
		$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'public' WHERE ID = ".$post_id." AND post_type ='post'"));
		}
}

The three MySQL queries are in place to prevent unauthorized users from viewing protected posts and to hide the posts from the RSS feeds. The first query runs only when new data populates the previously empty custom field, while the second query runs only when the data in the custom field has changed. The third query runs only if the custom field is emptied, and it sets the post’s visibility back to “Public.� All three are protected from SQL injection attacks by using $wpdb->prepare() to validate the data entered into the username form field.

If you don’t like that WordPress precedes the post’s title with the word “Private,â€� then add the following code to your theme’s functions.php file. This custom function is called when your theme would display a post’s title; it finds any instance of the words “Protectedâ€� or “Privateâ€� at the beginning of the title and removes them. In the core of WordPress’ programming, the function get_the_title() adds those words if a post’s visibility is restricted and the person viewing is not an administrator. What the following code does is send a message to the action that get_the_title() hooks into, telling it to remove the terms “Protected: â€� and “Private: â€� from the title. So, you can set a post’s title to begin with either term, and the title will not be altered; this code only affects WordPress’ ability to add to your title.

function smashing_title_trim($title) {
	$title = attribute_escape($title);
	$needles = array(__('Protected: '),__('Private: '));
	$title = str_replace($needles,'',$title);
	return $title;
}
add_filter('protected_title_format','smashing_title_trim');
add_filter('private_title_format','smashing_title_trim');

To allow users at the subscriber level to see private posts, you have to give them that capability. As it happens, some of the code we’ll be using later frees us from having to worry about users at the subscriber level seeing the posts of others.

$subRole = get_role( 'subscriber' );
$subRole->add_cap( 'read_private_posts' );

You can also grant users at the subscriber level permission to view private pages, in case you want a dedicated page of information that subscribers should know.

$subRole->add_cap( 'read_private_pages' );

Setting Up The Front End

Now that we have a way to add members to the list of people who can view a particular post, we have to modify our theme to use this data, and to actually control the visibility of each post based on this list. First, we need a way to get the username of the person who can view a post. Secondly, we would compare the username of the member with viewing permissions to the user who is currently logged in. Finally, we would make the theme display either the post in the loop or an error message (or perhaps nothing at all).

Place this code just after The Loop starts. It goes in single.php, category.php and index.php if you will be displaying posts on the home page.

<?php
/* Get the post's acceptable viewer. */
		$flautist_access = get_post_meta($post->ID, 'smashing_flautist_access', true );
/* Get the post's current viewer, if he or she is logged in. */
		if(is_user_logged_in()) {$current_flautist = $current_user->user_login;}
/* See if the acceptable viewer and the current viewer are the same */
		if($flautist_access == $current_flautist || current_user_can('author') || current_user_can('editor') || current_user_can('administrator'))
			{echo ''; ?>

Place this code just before the loop ends. Here is where you can show an error message telling the user that they may not view this post. Or you could leave this code as is to make it appear as though the current visitor is not missing anything.

<?php } else { echo ''; } ?>

This is what a hidden post looks like to the public or to a user who is not logged in. They would see what appears to be an error message and are redirected away from the post.

What the public sees when trying to view a protected post
If a person is not logged in and tries to view a restricted post, they would get an error message.

What an unauthorized user sees when trying to view a protected post
If a user is logged in but not allowed to view a restricted post, they would see either nothing or an error message specific to members.

What an authorized user sees when trying to view a protected post
If a member is logged in and authorized to view a protected post, then they would see the post itself.

Conclusion

Being able to control who can view individual posts is a useful feature with a wide variety of applications. Third-party software can natively do this, but WordPress is widely supported and documented, which means that any security holes that might allow unauthorized users to view restricted posts would be shut in a future update. Plus, it allows you to run an actual blog next to posts with limited visibility. This system could be used by administrators to distribute personalized content, by professionals to send files to clients, or by bloggers to restrict the visibility of certain posts to certain members.

Enabling an author to control who can view their posts can help them tailor the blog’s content to the needs or tastes of certain users. Ultimately, you will have to factor in the purpose and content of your website when deciding whether to use this method. It’s not for everyone, but it suit the needs of owners of small websites who want to deliver certain content to certain people.

Resources

(al)


© Chris Ellison for Smashing Magazine, 2012.


The UX Research Plan That Stakeholders Love


  

UX practitioners, both consultants and in house, sometimes conduct research. Be it usability testing or user research with a generative goal, research requires planning. To make sure product managers, developers, marketers and executives (let’s call them stakeholders) act on UX research results, planning must be crystal clear, collaborative, fast and digestible. Long plans or no plans don’t work for people. You must be able to boil a UX research plan down to one page. If you can’t or won’t, then you won’t get buy-in for the research and its results.

This article addresses one key aspect of planning UX research: the one-page plan document. Before we get to that, we’ll briefly discuss the benefits of research planning and identify the audience of a research planning document.

Blueprint Heart
(Image: Patrick Hoesly)

A word about stakeholders. A stakeholder in the UX world is a code name for the people who UX practitioners work with. These are our clients, whether internal or external to our organization. These are people who need to believe in what we do, act on research results, and fund and sponsor future research. We all have a stake in product development. They have a stake in UX research.

The Benefits Of Research Planning

Very generally speaking, UX research can answer two types of questions:

  1. What’s useful?
    What do people need? Who is the target audience?
  2. What’s usable?
    Does the design work for people, and how it can be improved?

Dozens of research methodologies could be implemented to answer these and more specific questions, and it is up to designers, researchers and their teams to decide what works best for them and when is the right time to answer their questions.

Here are the benefits of planning UX research:

  • Get a better feel of stakeholders.
    A written plan helps you identify what works and doesn’t work for people, and what questions they are trying to answer.
  • Engage stakeholders.
    A study plan ensures they are properly involved with the study and its results. If there’s no written plan, then there’s a greater chance that stakeholders won’t feel engaged.
  • Writing things down helps you.
    When you put things in writing, they look very different than how you imagined them when they were just thoughts in your head. Always have a written study plan, even if you don’t share it with anyone else.

Now, let’s quickly identify the target audience for the research planning document.

Who Are You Planning For? Who Are The Stakeholders?

As with every product or service, the best offering comes from carefully identifying the target audience, their needs and their wants. Different UX research stakeholders are interested in different aspects of a research plan:

  • Product managers and software engineers are mostly interested in the study’s goal, research questions and schedule. In some cases, they are also interested in the criteria for participants. These stakeholders are usually interested in goals and questions because these determine the content of the study and its focus. They are interested in the schedule to make sure it enables them to make timely design, business and development decisions. Criteria for participants interest them when the product targets a very specific demographic and they want to make sure participants are representative of that demographic.
  • Managers and executives are probably interested in the study’s goal and the overall cost of the study, because they are likely sponsoring the study. Usually, their bandwidth does not allow them more than that.
  • You! The plan is mostly for you. As soon as you put your thoughts in writing, something happens, and you find holes in them. These holes help you improve the plan. A written plan also helps you focus and better prepare for the study. The fact of the matter is that if you can’t boil your plan down to a page, you probably don’t really understand it.

Now that we’ve discussed why a planning document is important and who it is for, let’s get to the nitty gritty of the document.

The Plan That Stakeholders Love: The One-Pager

The users of a research plan love brevity and appreciate succinct definitions of what will happen, why, when and with whom. Here are the sections that go in a one-page research plan:

  • Title
    The title should combine the thing you’re studying and the methodology; for example, “Monster.com field study� or “XYZ Phone data-entry usability test.� Sometimes mentioning the target audience of the study is also appropriate; for example, “Whitehouse.com news page interviews with senior citizens.�
  • Author and stakeholders
    State your full name, title and email address on one line. After you get the stakeholders’ buy-in for the plan, add their details as well — the research belongs to everyone now.
  • Date
    Update it whenever the plan is updated.
  • Background
    Describe what led to this study. Discuss the recent history of the project. Be brief, no more than five lines.
  • Goals
    Briefly state the high-level reason (or reasons) for conducting this study. Try to phrase it in one sentence. If that wouldn’t make sense, create a numbered list of very short goal statements. If you have more than three to four goals, you are either aiming too high (meaning you have too many goals) or repeating yourself.
  • Research questions
    These are the specifics, the core of your plan. Provide a numbered list of questions that you plan to answer during the study. It is extremely important that your stakeholders understand that you will not necessarily be asking the study participants these questions. As a rule of thumb, have no more than seven to ten questions, preferably around five. Later on, you will construct your study script to answer these questions. An effective way to think about research questions is to imagine that they are the headings in the study’s summary.
  • Methodology
    In an academic environment, this section has one primary goal: to provide as many details as other researchers need in order to repeat the exact same study. In practice, the goal of the methodology section is to briefly inform the stakeholders of what will happen, for how long and where.
  • Participants
    Provide a list of the primary characteristics of the people you will be recruiting to participate in the study. Have a good reason for each and every characteristic. If you have two participant groups, describe both groups’ characteristics in lists or in a table. Append a draft form that you’ll use to screen participants.
  • Schedule
    Inform stakeholders of at least three important dates: when recruiting starts, when the study will take place, and when they can expect results. Large research projects require more scheduling details. For example, if the study involves travel to another city or country, more dates might be required for on-site preparation and meetings or for analysis workshops.
  • Script placeholder
    When a full study script is ready, it will appear under this title. Until then, all you need is a heading with a “TBD� indication.

A Sample UX Research Plan

XYZ Phone Data-Entry Usability Test

By John Smith-Kline, Usability Researcher, jskline@example.com

Stakeholders: Wanda Verdi (PM), Sam Crouch (Lead Engineer)

Last updated: 13 January 2012

Background
Since January 2009, when the XYZ Phone was introduced to the world, particularly after its market release, journalists, bloggers, industry experts, other stakeholders and customers have privately and publicly expressed negative opinions about the XYZ Phone’s keyboard. These views suggest that the keyboard is hard to use and that it imposes a poor experience on customers. Some have claimed this as the main reason why the XYZ Phone will not succeed among business users. Over the years, several improvements have been made to data entry (such as using horizontal keyboards for most features), to no avail.

Goals
Identify the strengths and weaknesses of data entry on the XYZ Phone, and provide opportunities for improvement.

Research questions

  1. How do people enter data on the XYZ Phone?
  2. What is the learning curve of new XYZ Phone users when they enter data?
  3. What are the most common errors users make when entering data?

Methodology
A usability study will be held in our lab with 20 participants. Each participant session will last 60 minutes and will include a short briefing, an interview, a task performance with an XYZ Phone and a debriefing. Among the tasks: enter an email subject heading, compose a long email, check news updates on CNN’s website, create a calendar event and more.

Participants
These are the primary characteristics of the study’s participants:

  • Business user,
  • Age 22 to 55,
  • Never used an XYZ Phone,
  • Expressed interest in learning more about or purchasing an XYZ Phone,
  • Uses the Web at least 10 hours a week.

[Link to a draft screener]

Schedule

  • Recruiting: begins on November 12
  • Study day: November 22
  • Results delivery: December 2

Script
TBD

Recap

A short plan that you and your stakeholders prepare together is key to a successful start of a UX research project.

  • Boil down your collective knowledge, agreements and understanding of what will happen, why, with whom and when.
  • Set the right expectations among stakeholders.
  • Try to keep the plan to one page.
  • Secure buy-in for the UX research by making it a team effort.
  • The core of the plan is the list of questions you are trying to answer. Choose the right ones.

Happy planning!

(al) (fi) (il)


© Tomer Sharon for Smashing Magazine, 2012.


How To Deliver Exceptional Client Service


  

We often hear companies, including Web agencies, boast about how they provide exceptional client service. But how do they define exceptional?

Consider this scenario. You are hired to design and develop a new website for a retail client. The client loves the design, and the pages you develop use the latest in HTML5, CSS3 and responsive design, resulting in a website that works wonderfully across browsers and devices. The e-commerce features of the new website help the client significantly increase their online sales, and the entire project is delivered on time and on budget. Now, is this “exceptional� client service? I don’t think it is.

When the client hired you, they expected that you would design and develop a great website. They also expected it would be done according to the timeline and budget set during the planning stages of the project. As successful as this project may have been for both you and the client, in the end, you did exactly what you were hired to do. You did your job.

Just Doing Your Job Vs. Delivering Exceptional Service

Nothing is wrong with “just doing your job.â€� In many cases, that alone is a tall order. So, while doing what you were hired to do is nothing to be ashamed of, it is also not exceptional — nor will it set you apart. There will always be other agencies or designers that will be able to do the work as well as you can — and there will certainly be someone willing to do it cheaper! The service you provide is how you can truly differentiate yourself.

Exceptional client service is about going beyond what is realistically expected of you. It is about surprising, and often delighting, customers, turning them into enthusiastic referral sources and lifelong clients who stick with you not only because you do great work at a fair price, but because the value you bring to them goes far beyond just your products.

In this article, I’ll detail a few of the ways that I have tried to take my own client service to the next level and deliver a better experience, starting with the most important aspect: the relationships that you establish with the clients who hire you.

Superhero racing to help
There is a difference between doing what you were hired to do and delivering a superheroic level of service. (Image: JD Hancock)

Creating Real Relationships

Here’s a quick exercise. Write down your five most important clients (how you define “important� is up to you). Then, write down as many things you know about those clients that have nothing to do with their business or the work you have done for them. What are their hobbies or passions? How many kids do they have? How old are those kids, and what are their names? Where do they like to vacation? Things like that.

So, how long is your list? If you’re like most people I speak with, probably not very long at all. We learn everything we can about a client’s business, but we often fail to discover anything substantial about our clients as people. If we do not engage with our clients in a real, personal way, then we are just another vendor — and vendors are easily replaceable with better cheaper options. However, clients are much less likely to consider replacing people with whom they have real relationships.

So, how do you start learning more about your clients? Simple: ask them questions about themselves and their lives, not just about their business.

Asking Real Questions

When I give this advice to others, it is often met with some apprehension. Asking someone about their business goals is easy. Asking them about their life outside of the office is harder. We often avoid getting personal for fear of offending the person or saying the wrong thing; but by being overly cautious, we miss the chance to create a real relationship.

Whenever I get nervous about getting too personal with a client, I remind myself of a story. A few years ago, I had the privilege to work on the website for the Tori Lynn Andreozzi Foundation. This non-profit foundation was named after a young girl who, walking home from school one afternoon, was struck by a drunk driver. Tori survived but was forever changed. Today, she is in a minimally conscious state, unable to walk, speak or eat.

In one of my first meetings with this client, I sat down with the head of the foundation, Tori’s mother, Cathy. I began the conversation simply by asking her, “How is Tori doing today?�

Cathy smiled and answered that Tori was doing well. We had our meeting and discussed the website and the project. As we were wrapping up, Cathy thanked me for asking her about Tori. She explained that so many people avoid asking about her daughter, fearing the news would be bad or that Cathy would be upset by the question. The truth is that, even though Tori has bad days, Cathy always enjoys talking about her daughter and was very happy to be asked about her. By asking Cathy how her daughter was doing, I showed her that I cared about more than just the project.

Website for the Tori Lynn Andreozzi Foundation
The website for the Tori Lynn Andreozzi Foundation

Today, Cathy is one of my favorite people to speak with, and we begin every conversation by asking how each other’s children are doing. We have much more than a great client-vendor relationship, all because I asked a real question, honestly cared about the answer, and created a real, human connection in the process. Had I been too afraid to ask that question, I might never have been able to build the relationship that I have now.

Don’t be afraid to ask your clients real questions. If they don’t want to answer you, they won’t. But for those who do (and you will find that most, if not all, of your clients will be happy to have a real conversation that has nothing to do with business), you will be well on your way to building real relationships.

Participate In More Than Just Projects

Another way to build a relationship with a client that goes beyond the project is to participate in their events. If the client runs a non-profit organization, they might have fundraisers or similar events that offer you an opportunity to support their cause and nurture the relationship. Go to these events and participate. As a bonus, you will also be helping a worthwhile cause.

Not all of your clients will have fundraising events, but they might invite you to holiday parties and other gatherings. Take advantage of these opportunities to interact with your clients outside of a normal business setting. It will go a long way to reinforcing those real relationships that you are trying to create and show that you are more than just another vendor.

Similarly, consider inviting clients to some of your events to show that you view them as more than just a source of business. When they arrive, greet them warmly and enjoy their company, leaving business talk for another day.

Help Them With Services That You Do Not Provide

Clients may hire you to design and develop a Web presence for them, but in the course of the project you will often discover that they need other services that you do not provide. By listening to their needs, you might learn that they have issues with their payroll company or their accountants or some other aspect of their business.

Look to your own business and the vendors you use. There may be a service or company that you have had success with that you could recommend. Also look to your other clients to see whether they offer services that fit. If appropriate, set up a lunch meeting between you, the client with the need and the client that might be able to fill that need. Not only will you be taking two clients out for lunch, you will hopefully be helping them both by making a valuable connection between the two companies.

When a client can say, “I hired this company to design our website and they ended up helping us revamp our entire payroll system!â€� you position yourself as much more than just their “Web teamâ€� — you show that you are a valued business resource and a trusted advisor.

Pick Up The Phone

Good communication is key to any relationship. Still, judging from the number of clients I speak with who are unhappy with their current Web team — not because they do a poor job, but because they are unresponsive — quality communication is not always a given.

Regularly updating your clients by email is important, but also pick up the phone every now and then, so that you become more than just that distant person behind those electronic updates. By hearing your voice, clients will feel more connected to you and the project. It also shows them that you value them enough to take the time to make a personal call, and it gives you a chance to talk about something other than business.

Conversations bubbles in an office
Regular phone calls allow you to have real conversations with clients, communicating at a personal level that email and other electronic updates do not allow for. (Image: opensourceway)

Face The Bad Times Head On

Have you ever had to share bad news with a client, but rather than pick up the phone to discuss the issue, you waited and sent an email at 5:15 pm on a Friday? By doing this, you may have bought yourself a few more days before having to face the client’s worried questions, but you also damage the relationship by hiding behind an email. It also means that the client will read the bad news first thing on Monday morning; definitely not a good start to their week, and definitely not the way to treat a valued relationship.

Here’s a secret: clients do not expect you to be perfect. They do, however, expect you to be honest. When something goes wrong, let them know quickly so that they are not blindsided by the issue later on. And never deliver bad news by email. Picking up the phone to discuss the news lets you reassure the client and answer any questions they may have. An after-hours email certainly won’t do that for them.

If the matter is handled correctly, the client will not remember that something went wrong. They will remember that you were honest and kept them apprised of the state of the project, even when it did not go according to plan.

Be Thankful And Show Appreciation

When was the last time you thanked a client for working with you? How did you do it? Did you send a basket of cookies or chocolate with a generic “thank you� message, or did you do something more personal?

Too often, we fail to even thank our clients for their business. We are so keen to finish a project and move on to the next one that we forget to properly show our appreciation.

While a basket of sweets and a generic message is better than nothing, consider sending a personal, handwritten thank-you note.

Handwritten letters have become all but extinct these days. With the rise of electronic communication such as email, social networks and text messaging, so few people take the time and effort to actually write a letter. The gesture of a personal letter will delight and surprise your client, not only because you have thanked them, but because the way you did so was personal, memorable and the perfect cap to a successful project.

Handwritten thank you message
A thankful, personal handwritten card is a great way to cap off a successful project. (Image: irrezolut)

How About You? Do You Deliver Exceptional Client Service?

I hope this article starts a conversation. How do you deliver exceptional client service? What tips can you share so that others can delight their own clients and offer them value beyond just products?

In this industry, we are always eager to share the latest tips and tricks on CSS, HTML, JavaScript, PHP or some other Web technology. Let’s also start to share tips on how to deliver exceptional client service, because success in this industry is about much more than developing great websites — it’s about developing great relationships.

(al)


© Jeremy Girard for Smashing Magazine, 2012.


What Successful Products Teach Us About Web Design


  

Web design is a craft that is constantly evolving and yet also sometimes sabotaged. The moment a design is released, a new version is born. In the beginning, like a baby, it seems vulnerable and weak, but in time it grows up and becomes self-sufficient. Redesigning a website for its own sake doesn’t prove anything; quite the contrary, it reveals a lack of effectiveness on the part of the designer.

Product design is a craft in which new versions come to life with increasing difficulty. We can learn a thing or two from it when designing for the Web. First, let’s look at some examples.

  • How many designs for the iPhone has Apple released since 2007? The answer is one, with only two tweaks. How many Motorola phones for Android can you find on the market right now? Thirteen, not counting the old models.
  • How many designs of the Mini Cooper do you know of? Just that one brave design that has continually evolved since 1959! How many Toyota Corolla models can you count since 1967? Nineteen.
  • Zippo lighters have retained their appeal since 1933!

Forget marketing, technical specs and hardware. Products such as the iPhone, the Mini Cooper and the Zippo lighter have become wildly successful because of their outstanding design. Such massive success springs from three sources: the designer, sticking to the scope and iteration. These aspects can help us in Web design, too. In this article, we’ll look at what we can learn from successful product design.

The Ability Of The Designer

Zippo
Zippo lighters have remained elegant and reliable through time. (Image: cell105)

Do you trust your instincts? You should! Because when you see a design, you judge its attractiveness in less than a second. We all know what we like, even if we can’t always explain it. It’s about aesthetics. Aesthetics is a child of harmony, and harmony is not magic. It can be achieved when the designer embraces certain principles, such as balance, contrast and dominance. Becoming a fantastic designer, though, requires more than pure technique. It requires that you see the context and make decisions accordingly.

A couple of comments by Karim Rashid, featured in the documentary Objectified are fascinating and revealing. First, Rashid talks about a stereo that he loved as a teenager:

It was a white kind of bubble stereo with these two bubble white speakers. And it was probably very inexpensive — it was a real democratic product, and it had a turntable and the whole thing built in. It was a beautiful thing. Looking back and thinking why it was a beautiful thing, it was very self-contained, and the message was very strong and very simple, and at the same time it was very human. There was a quality about it.

See? A democratic, self-contained, human, simple thing with a strong message.

Here is Rashid again on thinking outside the box:

Why do we feel like we need to keep revisiting the archetype over and over and over again? Digital cameras, for example, [whose] format, proportion, the fact that they’re a horizontal rectangle, are a model of the original silver film camera. So, in turn it’s the film that defined the shape of the camera. All of a sudden, our digital cameras have no film. So, why on earth do we have the same shape we have?

How is it that Karim Rashid extracts such clear conclusions? What hinders us from doing the same? And not just in theory. Let’s do it for real. The next time you are about to make an important design decision, stop and ask yourself, What would I do if I were Dieter Rams or Jonathan Ive or — since you’re a Web designer — Douglas Bowman?

Asking this kind of question briefly expands our skills of judgment and makes us ultra-alert. Doing it regularly can drastically heighten our perception, values and actions as designers. Is this enough? No, but it is the beginning of a beautiful relationship with design.

And the Zippo lighter? It looks both friendly and solid, a comrade that needs your attention in order to keep working. Ιt has its own scent; it’s windproof; and above all, the sound when you flip open the lid is distinctive. And if you’ve owned a Zippo for a while, you must have noticed that it learns how you touch it when you light it.

All together, a Zippo is a product of craft — just as our designs for the Web should be. This is as simple and as hard as it sounds.

Focusing On The Scope

Mini Cooper
Once a Mini, always a Mini. (Image: Shelley Gibb)

Let’s go back to cars for a moment.

As noted earlier, the Corolla models of Toyota are nothing spectacular in their design. But what is a Toyota car known for? It’s a reliable, relatively cheap family car. Is Toyota successful? You bet!

What’s a Mini Cooper? It’s a beautiful small car that appeals mostly to young people. Is it successful? Of course, it is.

Cars are complicated machines. They do more than transport people. If a Toyota were as fancy as the Mini, then it wouldn’t be affordable. If a Mini were reimagined as a family car, then it would lose some of its charm. Oversimplification? Perhaps. But you get the point.

There’s a scope behind each product. As long as the scope is met, the product will be effective and remain on the market. The same happens in Web design.

Consider a metaphor. The closest physical product to a website is a periodical. Take Wired magazine (the physical magazine, that is, not the website or iPad app, which have slightly different characteristics). I’ve been reading it for more than 10 years, and if I had to describe it succinctly I would say “forward-thinking and cool.� Wired reinvents itself every once in a while and persistently fine-tunes the design, but the scope remains the same. Excellent design and illustration, superbly written long articles and a ton of clever short ones serve the main purpose: to introduce its audience to a new era. Audiences change over time, and new eras dawn, but Wired remains. Why? Because it has always respected a higher purpose. Sure, many magazines are well designed, and enough of them have great content. But you rarely find one with a unique identity, an identity that can’t be easily copied.

Your probably less complicated Web project needs to perform similarly. You must define the objectives. The design must promote them. Good content should prevail. You know the rules; make sure to follow them. Moreover, know where to stop. If it’s a new idea with vague potential or yet another feature or a last-minute change, just say no.

Websites are like breathing organisms. They evolve; new features are added and others are dropped, but they never stay still. Or at least they shouldn’t. Thus, while a promising fresh idea shouldn’t be discarded, it should be held until the next major update.

Big, ambitious, well-funded websites often seem to lose focus. Their owners try to satisfy all requests. This is a recipe for disaster, because it creates unnecessary friction between everyone working on the project. It dulls the impact of the best features and, above all, the scope. Tension fills the air. The worst days are ahead.

Such practices have led to the infamous concept of design by committee. Simply put, if everything is important, then nothing is important.

Iterations

Apple Store, London
Is what Apple does magic? I think not. (Image: Jon Rawlinson)

Let’s talk Apple. Apple’s iconic design and its founder’s exceptional way of thinking have been overanalyzed lately.

No matter how many words we write about Steve Jobs, we still seem to explain away his success as being a kind of magic. But that’s plainly wrong. People are inclined towards the least complicated, least demanding explanation to a conundrum. It is written in our genes. We think more deeply only when there’s a serious reason to do so. (But I digress.)

So, let’s do away with what Adrian Slywotzky refers to as the “Eureka� myth:

Apple would love us to believe it’s all “Eureka.â€� But Apple produces 10 pixel-perfect prototypes for each feature. They compete — and are winnowed down to three, then one, resulting in a highly evolved winner. Because Apple knows the more you compete inside, the less you’ll have to compete outside.

If Apple iterates so painstakingly, why shouldn’t we?

Inspiration for a great design roars when it comes. And implementing the idea brings a rush of enthusiasm. And our eyes sparkle when we anticipate outstanding success. And yet it rarely works that way.

Why? Because ideas and their execution are seldom free from flaws. You know the old cliché, “There is always room for improvement.� It still stands. There is always room for improvement, and accepting that your idea is the one that needs improvement takes courage. Demolishing your next great product in order to make it better takes nerve and self-discipline. But it also makes you wiser, and can dramatically improve the product.

Iterating extensively and in detail doesn’t depend on a certain type of project or a certain budget. It’s a tricky thing, because it forces us to confront our imperfect nature as human beings. To embrace our inner flaws is to walk the road of truth and maturity, silently, without making a show that we’re doing it.

This weight might feel a little heavy on our shoulders. If it does or if you dismiss Apple’s success, consider what Oliver Reichenstein, head of Information Architects, says about the iterations that his team makes in each development phase (this quote appears in the comments section):

It’s often almost impossible to explain easily why things look like they do, because we went through so many iterations, that it feels like explaining a chess game with all the ifs and whats.

The same goes when designing for the Web: there’s no excuse to avoid making as many iterations as we can.

Final Thoughts

When successful designers are asked where they seek inspiration, they often say something like, “Everywhere — I go for a walk and observe the world around me.â€� And it’s true. But what they don’t often say is that they also know what to observe and how to ignore the noise of the world.

There are many beautiful well-functioning products around us. Each has a story to tell, a story that is strongly attached to its design, its scope and the iterations that the designer took before releasing it to the world.

Take the Dyson vacuum cleaner. Its design is at least impressive, and its scope is clear (to suck dirt better than other cleaners and, thus, to make your environment healthier), and it took hundreds of prototypes for the designers to figure out how to make it work without a bag. The first Dyson vacuum cleaner was sold in 1970! To explore further and find similar products, just search for our three key words: “design scope iteration.�

Creating a lasting website is no easier than creating a lasting vacuum cleaner. But neither is it impossible. It requires a holistic approach, focus and maturity, just like the products we’ve looked at here. Not to mention, it requires a paradigm shift.

(al)


© Yiannis Konstantakopoulos for Smashing Magazine, 2012.


Introduction To Linux Commands


  

At the heart of every modern Mac and Linux computer is the “terminal.� The terminal evolved from the text-based computer terminals of the 1960s and ’70s, which themselves replaced punch cards as the main way to interact with a computer. It’s also known as the command shell, or simply “shell.� Windows has one, too, but it’s called the “command prompt� and is descended from the MS-DOS of the 1980s.

Mac, Linux and Windows computers today are mainly controlled through user-friendly feature-rich graphical user interfaces (GUIs), with menus, scroll bars and drag-and-drop interfaces. But all of the basic stuff can still be accomplished by typing text commands into the terminal or command prompt.

Using Finder or Explorer to open a folder is akin to the cd command (for “change directory�). Viewing the contents of a folder is like ls (short for “list,� or dir in Microsoft’s command prompt). And there are hundreds more for moving files, editing files, launching applications, manipulating images, backing up and restoring stuff, and much more.

So, why would anyone want to bother with these text commands when you can use the mouse instead? The main reason is that they are very useful for controlling remote computers on which a GUI is not available, particularly Web servers, and especially Linux Web servers that have been stripped of all unnecessary graphical software.

Sometimes these lean Linux servers are managed through a Web browser interface, such as cPanel or Plesk, letting you create databases, email addresses and websites; but sometimes that is not enough. This article provides a broad introduction to text commands and the situations in which they are useful. We’ll cover the following:

  • Why knowing a few commands is useful;
  • Issuing commands on your own computer;
  • Using SSH to log into your Web server;
  • Getting your bearings: pwd, cs ls;
  • Viewing and moving files: cat, more, head, tail, mv, cp, rm;
  • Searching for files: find;
  • Looking through and editing files: grep, vi;
  • Backing up and restoring files and databases: tar, zip, unzip, mysqldump, mysql;
  • File permissions: chmod.

Why Knowing A Few Linux Commands Is Useful

As a website developer or server administrator, you would gain a big asset in becoming comfortable with these commands: for website emergencies, to configure a server and for your CV. It can also save you money. Many hosting companies offer fully managed servers but at a high monthly premium. Or else they charge by the hour for technical support.

Perhaps you need to archive some big files or make a change to the httpd.conf file or figure out why your website’s images have suddenly stopped loading. You might not want to pay $50 to your server’s administrator for a five-minute job. This article gives you the tools to make such changes yourself.

And why “Linux� commands? Two main types of servers are available today: Windows and UNIX. UNIX-based servers include Linux (which split off in 1991), Mac OS X (2002) and several more traditional UNIX systems, such as BSD, Solaris and HP-UX. Linux commands are basically UNIX commands and so will run on all of them. In fact, I use the term “Linux� here only because it is more common and less frightening than “UNIX.� Windows servers, on the other hand, have a much smaller market share and are more often controlled through GUIs, such as Remote Desktop and VNC, rather than the command line.

In fact, a November 2011 survey showed that Apache accounted for about 65% of all Web servers. Apache usually runs in the popular LAMP configuration: Linux, Apache, MySQL and PHP. Microsoft was a distant second, with 15%. Third place nginx runs on Linux, UNIX, Mac and Windows. So, the commands in this article will work on at least two thirds of all servers.

Issuing Commands To Your Own Computer

You can quickly experiment with text commands on your own computer. On Mac with OS X, go to Applications → Utilities, and run Terminal. On a PC with Windows, go to Start → All Programs → Accessories, and choose “Command Prompt.� On Ubuntu Linux, go to Applications → Accessories, and choose Terminal.

On Windows you should see this:

The Windows command prompt

This is the command line (i.e. shell, prompt or terminal) on your own computer. You can type dir on Windows or ls on Linux or Mac followed by “Enter� to see a list of the files in the current “directory� (i.e. folder, location or path).

All we will be doing for the rest of this article is opening up one of these terminals on a remote computer: your Web server.

You may have used VNC or Remote Desktop, which allow you to actually view the desktop on someone else’s computer: your screen shows their screen, your mouse controls their mouse, your keyboard mimics their keyboard.

The terminal is similar to this but without the fancy menus or scroll bars. If you were to plug a keyboard and screen into your Web server, sitting in a fireproof basement somewhere, you would probably see one of these terminals, waiting patiently for your user name and password.

Using SSH To Log Into Your Web Server

The application SSH, or Secure Shell, is used to log into Web servers. It often takes the same user name and password as FTP, but it has to be allowed by your host. If you have a dedicated Web server, it is probably already allowed. If you use cloud hosting, then you might need to request it first. If you are on shared hosting, you’ll definitely need to request it, and the administrator may refuse.

On Linux or Mac, open up Terminal as described above and type the following:

ssh -l username www.myserver.com

The -l stands for “log in as,� and your user name goes after it. If SSH is allowed, then it will ask for a password. If not, you’ll get an error message, like this one:

SSH Command and Connection Error

Running the ssh command and being denied access

On Windows, you will need to download some SSH software. Putty is a popular and easy choice. It downloads as a single EXE file, which you can save to your desktop and run right away. Type your website as the host name, check the SSH box under “Connection Type,� and click “Open.� It will ask for your user name and then your password.

Running Putty on Windows

Running Putty on Windows in order to SSH to your Web server

Once successfully logged in, you will usually see a welcome message. After that, you will be presented with a few letters and a $ sign (or a # sign if you have logged in as root). The letters often represent your user name and where you’ve come from, or the name of the server. A ~ indicates that you are in your home directory. The $ is the prompt; it indicates that you can start typing commands now, something like:

Successful SSH to a server

A successful SSH log-in to a Web server. The $ means we can start typing commands.

The next section introduces a few basic commands.

Getting Your Bearings

On Windows, when you go to “My Documents� from the Start menu, it opens your “My Documents� directory in Windows Explorer and shows the contents. If some nosy colleague walked by and asked “What directory are you in?� you could say “I’m in my documents.�

If you SSH’ed to a server as the user “admin,� you would land in admin’s home directory, probably /home/admin. You can verify this by typing the command pwd, which shows your current location (i.e. folder, directory or path).

The pwd and ls commands

The pwd command tells you where you are, cd changes the directory and ls shows the contents of a directory.

To change to another directory, use the cd command with the destination, like so:

cd /

This will change the directory to /, the top of the whole UNIX directory structure. The command ls lists the contents of the current directory, in this case /.

In the screenshot above, the terminal is color-coded. Dark-blue entries are subdirectories, and black entries are files. A lot of the interesting stuff on Web servers happens in the /etc, /home and /var directories. Using just cd and ls, you can explore your server and find out where stuff is.

When using cd, you can specify the new directory absolutely (beginning with a slash, like /var/www) or relative to your current location (without the initial slash). You can also go up a directory with two dots. Practice with the sequence below, pressing “Enter� after each command. Can you guess what the last command will tell you?

cd /var
ls
cd www
ls
cd ..
pwd

Viewing And Moving Files

On many Linux servers, websites are located in /var/www/vhosts. You can check on your server by doing the following:

cd /var/www/vhosts
ls

If you see a list of websites, you can move into one of them. Within the website’s main directory, you will probably see the same files that you see when you FTP to the website, things such as httpdocs (where your website’s files are), httpsdocs (if you have a separate secure website), conf (configuration files), statistics (logs and compiled statistics), error_docs, private and more.

You can then change into your website’s public-facing directory, which is myserver.com/httpdocs in this example:

cd myserver.com
ls
cd httpdocs
ls

Now you have arrived, and you can run a new command, cat, which displays the contents of a file. For instance, if you have an index.html file, run:

cat index.html

If your index.html file is more than a few lines long, it will rush past in a blur. You can use the more command to show it slowly, one page at time. After you type the command below, it will show you the first page. You can press the space bar to show the next page, “Enter� to show the next line, and Q to quit.

more index.html

You can also show just the first few or last few lines of a file with the head and tail commands. It shows 10 lines by default, but you can pass in any number:

head index.html
tail -20 index.html

If you would like to rename this file, use the mv command, short for “move�:

mv index.html indexold.html

Similarly, the cp is the copy command, and rm removes files.

cp index.html indexold.html
rm indexold.html

Below is a string of commands in action. In order, it confirms the current directory with pwd, looks at the contents with ls, views index.html with cat, then renames it with mv, and finally removes it with rm, with a lot of ls in between to show the changes.

The cat and mv commands

The cat, mv and rm commands in action, for displaying, moving and then removing a file.

More Advanced Tip: Changing the Prompt

Note that in our initial examples, the full prompt included the current directory. For instance, in [admin@myserver /]$, the / indicated that the user was in the / directory. In the example directly above, it was removed, or else it would have crowded the screenshot by constantly saying [admin@myserver /var/www/vhosts/myserver.com/httpdocs]$.

You can change the prompt to whatever you want by setting the PS1 environment variable. Here are a couple of examples, the latter including the user, host and current directory:

PS1="[woohoooo ]$ "
PS1='[${USER}@${HOSTNAME} ${PWD}]$ '

Searching For Files

On big websites, files can get lost. Perhaps you vaguely remember uploading a new version of your client’s logo about four months ago, but it has since fallen out of favor and been replaced. Now, out of the blue, the client wants it back. You could download everything from the server using FTP and search the files using Finder or Explorer. Or you could log in and search using the command line.

The find command can search through files by name, size and modified time. If you just give it a directory, it will list everything that the directory contains. Try this:

find /var/www

You will probably see lots and lots of file names whizzing past. If you have many websites, it could continue for a couple of minutes. You can stop it by hitting Control + C (i.e. holding down the Control key on your keyboard and pressing the letter C). That’s the way to interrupt a Linux command. A more useful command would be:

find /var/www | more

The pipe symbol (|) takes the output of one command (in this case, the long list of files produced by find) and passes it to another command (in this case, more, which shows you one page of files at a time). As above, press the space bar to show the next page, and Q to quit.

To search for a specific file name, add -name and the file name. You can use \* as a wild card (the backslash is not always necessary but is good practice with the find command). You can combine searches using -o (for “or�). If you leave out the -o, it becomes an “and.�

find /var/www -name logo.gif
find /var/www -name \*.gif
find /var/www -name \*.gif -o -name \*.jpg

You can also search by size by adding -size. So, you could look for all GIFs between 5 and 10 KB:

find /var/www -name \*.gif -size +5k -size -10k

Similarly, to find a file that was last changed between 90 and 180 days ago, you can use -ctime:

find /var/www -name \*.gif -ctime +90 -ctime -180

In both of these cases, you will probably also want to know the actual file size and date last changed. For this, you can add -printf, which is similar to the C function printf in that you use the % sign to output various information. This command outputs the file size (up to 15 characters wide), the date and time changed (down to the nanosecond) and the file name:

find /var/www -name \*.gif -size +5k -size -10k -ctime +90 -ctime -180 -printf "%10s  %c  %p\n"

With that whopper, you have hopefully found the missing file. Here is an example:

Variations on the find command

Searching for all GIFs within a single website, and displaying the file sizes, changed times and file names.

Another useful parameter is -cmin, which lets you see files that have changed in the last few minutes. So, if something goes wrong on a website, you can run this to see everything that has changed in the last 10 minutes:

find /var/www -cmin -10 -printf "%c %p\n"

This will show files and directories that have changed. Thus, it won’t show files that have been removed (because they are no longer there), but it will show the directories that they were removed from. To show only files, add -type f:

find /var/www -cmin -10 -type f -printf "%c %p\n"

More Advanced Tip: Reading the Manual

I didn’t have to remember all of the variations above. I consulted the manual several times, like so:

man find

While reading a manual page, the controls are the same as more: space bar for paging, “Enter� to go forward one line and Q to quit. The up and down arrows also work. You can search within a page of the manual by typing / and a keyword, such as /printf. This will jump you to the next occurrence of that term. You can search backwards with ?printf, and you can repeat the search by pressing N.

Looking Through And Editing Files

Most visual code editors allow you to search through many files when you’re looking for a particular variable or bit of HTML. You can also do this directly on the server using the command grep. This is useful when something goes wrong on a complex website with hundreds of files and you have to find the error and fix it fast.

Let’s say you view the HTML source and see that the error happens right after <div id="left">. You can let grep do the searching for you. Give it the thing to be searched for and the files to search in. These commands change to the website directory and grep through all files ending in php. You need to put quotes around the HTML because it contains spaces, and the inner quotes have to be escaped with backslashes:

cd /var/www/vhosts/myserver.com/httpdocs/
grep "<div id=\"left\">" *.php

This will tell you which files in the current directory contain that bit of HTML. If you want to search in subdirectories, you can use the -r option with a directory at the end, instead of a list of files. The single dot tells it to start in the current directory.

grep -r "<div id=\"left\">" .

Alternatively, you could use the find command from above to tell it which files to look in. To put a command within a command, enclose it in back apostrophes. The following searches only for the HTML in PHP files modified in the last 14 days:

grep "<div id=\"left\">" `find . -name \*.php -ctime -14`

You can also add -n to show the line numbers, as in this example:

Using grep to look for things inside files

Searching for a bit of HTML within the PHP files in the current directory

And how do you quickly fix an error when you find it? To do that, you will need to start up a Linux text editor. Different editors are available, such as pico and emacs, but the one that is guaranteed to be there is vi. To edit a file, type vi and the file name:

vi index.php

vi is a complex editor. It can do most of the amazing things that a fully featured visual editor can do, but without the mouse. In brief, you can use the arrow keys to get around the file (or H, J, K and L on very basic terminals where even the arrow keys don’t work). To delete a character, press X. To delete a whole line, press DD. To insert a new character, press I. This takes you into “insert mode,� and you can start typing. Press the Escape key when finished to go back to “command mode.� Within command mode, type :w to save (i.e. write) the file and :q to quit, or :wq to do both at the same time.

The vi editor also supports copying and pasting, undoing and redoing, searching and replacing, opening multiple files and copying between them, etc. To find out how, look for a good vi tutorial (such as “Mastering the VI Editor�). Note also that on many computers, vi is just a shortcut to vim, which stands for “vi improved,� so you can follow vim tutorials, too.

The Linux editor vi

Editing files with the vi text editor

More Advanced Tip: Tab Completion

When changing directories and editing files, you might get tired of having to type the file names in full over and over again. The Terminal loses some of its shine this way. This can be avoided with command-line completion, performed using tabs.

It works like this: start typing the name of a file or a command, and then press Tab. If there is only one possibility, Linux will fill in as much as it can. If nothing happens, it means there is more than one possibility. Press Tab again to show all of the possibilities.

For example, if above I had typed…

vi i

… And then pressed Tab, it would have filled in the rest for me…

vi index.php

… Unless several files started with I. In that case, I would have had to press Tab again to see the options.

Backing Up And Restoring Files And Databases

Some Linux servers do support the zip command, but all of them support tar, whose original purpose was to archive data to magnetic tapes. To back up a directory, specify the backup file name and the directory to back up, such as:

cd /var/www/vhosts/myserver.com/httpdocs/
tar czf /tmp/backup.tgz .

The czf means “create zipped file.� The single dot stands for the current directory. You can also back up individual files. To back up just things changed in the last day, add the find command:

tar cfz /tmp/backup.tgz `find . -type f -ctime -1`

Both of these commands put the actual backup file in the temporary /tmp directory — if the backup file is in the same directory that you are backing up, it will cause an error. You can move the file to where you need it afterwards. To see what is in an archive, use the tzf options instead:

tar tfz /tmp/backup.tgz

Linux tar command

Creating and showing the contents of a backup file using tar

To restore things, use xzf, for “extract from zipped file.� First, run a listing as above to check what’s in there, and then restore one or more of the files. The second command restores all of the files from the archive into the current directory:

tar xfz /tmp/backup.tgz ./index.php ./test.php
tar xfz /tmp/backup.tgz

If your server has the zip command, then run these commands to do the same thing:

cd /var/www/vhosts/myserver.com/httpdocs/
zip -r /tmp/backup.zip .
zip -r /tmp/backup.zip `find . -type f -ctime -1`
unzip -l /tmp/backup.zip
unzip /tmp/backup.zip test.php
unzip /tmp/backup.zip

If your Web server uses MySQL, then you might want to regularly back up your data. For this, there is the mysqldump command. The format of the command is:

mysqldump --user="username" --password="password" --add-drop-table database

Replace the user name, password and database with your values. Instead of specifying a database, you can use -A to dump all databases. If you get errors about table locking, you can add --single-transaction. Once you submit the user name and password, this will output a load of SQL in a long blur. To save the output to a file, you will need to use the > symbol. This sends the output of a command to a file.

mysqldump --user="username" --password="password" --add-drop-table database > /tmp/db.sql

To restore a database backup, you can use the mysql command. This command lets you run SQL statements from the command line. For example, the following command gets you into the database:

mysql --user="username" --password="password" dbname

At the mysql> prompt, you can type an SQL statement such as:

mysql> SHOW TABLES;
mysql> SELECT * FROM customers;

For restoring, you’ll need to use the pipe (|), which will send the output from one command into another. In this case, cat will output the database backup file and send it into the mysql command:

cat /tmp/db.sql | mysql --user="username" --password="password" dbname

If people are looking over your shoulder while you’re doing this, you might not want to type the password directly into the command. In this case, just leave it out, and mysql or mysqldump will ask for it instead.

cat /tmp/db.sql | mysql --user="username" --password dbname

Once you’ve created the database backup file, you can include it in the backups we did above:

tar czf /tmp/backup.tgz . /tmp/db.sql

More Advanced Tip: Hidden Files and Wildcards

Many websites use a file called .htaccess to implement URL rewriting and password protection. In UNIX, all files starting with a single dot are hidden. They won’t show up when you do ls, and they won’t get backed up if you do this:

tar czf /tmp/backup.tgz *

The * is a wildcard. Before the command executes, the * is replaced with all non-hidden files in the current directory. To include hidden files as well, it’s better to back up the whole directory as above using a single dot:

tar czf /tmp/backup.tgz .

To show hidden files when doing a directory listing, add -a to the command:

ls -a
ls -la

File Permissions

If you use FTP regularly to upload files to websites, then you might be familiar with permissions. All files and directories on Linux (and Mac, Windows and other UNIX systems) have an owner, a group and a set of flags specifying who can read, write and execute them.

The list of user names (and, thus, potential file owners) on a UNIX system is stored in the file /etc/passwd. You can try:

more /etc/passwd

The Apache Web server is started by a command when the Web server boots up. But the user who starts Apache is often a restricted and unprivileged user, such as nobody or apache or www-data. This is for security reasons, to prevent someone from hacking into the website and then gaining control of the whole server. You can find out who that user is by running the command below and looking in the first column. The ps aux command shows all of the processes running on the server, and grep shows only processes that contain the word “apache.�

ps aux | grep apache

This can cause conflicts, though. If you upload a file to a website via FTP and log in as admin, then the file will be owned by admin. If Apache was started by the user named nobody, then Apache might not be able to read that file and won’t be able to send it to any users who request it when viewing the website. Instead, users will see a broken image or a message such as “403 Forbidden. You don’t have permission to access that file.�

A subtler and more common problem is when an image can be viewed but not overwritten or removed via the website’s content management system (CMS). In this case, the user nobody can read the file but can’t write to it.

You can view permissions using the ls command with an extra -l, like so:

ls -l

ls command with long list format

The command ls -l shows information about permissions, owners, size and date.

This directory contains three files, with three subdirectories shown in green. The first letter on each line indicates the type: d for directory and - for normal file. The next nine letters are the permissions; they indicate the read, write and execute permissions for the owner, group and everyone else. After the number (which represents the size) is the owner and group for the file. These files are all owned by admin. This is followed by the file size (less useful for directories) and the date and time of the last modification.

Below is another example of three files in an images subdirectory. Two of the files were uploaded by admin via FTP, and Apache was started by the user www-data. One of the files will be unviewable through a Web browser. Which do you think it is?

Bad permissions

The answer is bg.jpg. Both bg.jpg and logo2.gif have the same permissions: only the owner can read and write them. The logo2.gif file is OK because the owner is www-data, so that file can be accessed, read and returned by Apache. The logo.gif file is also OK because it has r in all three permissions (i.e. owner, group and everyone else). But bg.jpg will fail because only the user admin can read it, not the user who started Apache. If you were to access that file in a Web browser, you would see something like this:

What happens when you try to access a file without the correct permissions in a browser.

These sorts of errors can be resolved with the chmod command, which changes file permissions. The three sets of permissions are represented in commands with u (“user� or owner), g (“group�), o (“other� or everyone else) or a (“all�). So, to enable all users to read bg.jpg, either of these would work:

chmod go+r images/bg.jpg
chmod a+r images/bg.jpg

If this file were also part of a CMS, then you’d have to also add write permissions before the CMS could overwrite it:

chmod a+rw images/bg.jpg

You can also make these changes to all files in all of the subdirectories by adding -R. This recursive operation is not supported by some FTP programs and so is a useful command-line tool:

chmod -R a+rw images/

Directories also need the x (“execute� permission), but files generally don’t (unless they are in a cgi-bin). So, you can give everything rwx (read, write and execute) permissions and then take away the x from the files:

chmod -R a+rwx images/
chmod -R a-x `find images/ -type f`

However, this does leave everything rather open, making it easier for hackers to gain a foothold. Ideally, your set of permissions should be as restrictive as possible. Files should be writable by the Apache user only when needed by the CMS.

More Advanced Tip: Chown and the Superuser

Another useful permissions command is chown. It changes the owner of a file. However, you have to be logged in as a user with sufficient privileges (such as root) in order to run it. To make www-data the owner of bg.jpg, run this:

chown www-data images/bg.jpg

This will probably return “Permission denied.� You have to run the command as the superuser. For this, you will need to find the root password for your server, and then run the following:

sudo chown www-data images/bg.jpg

You will definitely need to be the superuser if you want to edit configuration files, such as Apache’s:

sudo vi /etc/httpd/conf/httpd.conf

If you want to become the superuser for every command, run this:

su

This is dangerous, though, because you could easily accidentally remove things — especially if you are using the rm command, and particularly if you’re using it in recursive mode (rm -r), and most especially if you also force the changes and ignore any warnings (rm -r -f).

Conclusion

This article has introduced some very useful Linux commands, a potential asset for any aspiring Web worker and a surefire way to impress a dinner date.

For a few more commands related specifically to website crashes, check out the Smashing Magazine article “What to Do When Your Website Goes Down.� For a broader view, try this list of Linux commands. And the “Mastering the VI Editor� tutorial mentioned above explains vi well.

Hopefully, you now have the tools and confidence to pitch in the next time one of your websites has a problem.

(al)


© Paul Tero for Smashing Magazine, 2012.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress