Apr 19, 2012

Extended Jquery tutorial

This tutorial is an extension of the basic JQuery tutorial. We will not cover the same stuff here, so if you want a quick and easy primer on JQuery please click on that link. Instead, this offers some extra background information that help put the code examples into context.

You might also want to check out my other posts such as the JQuery Slideshow or AJAX with JQuery and PHP.

What is JQuery?

JQuery is a client-side JavaScript library that can do a wide variety of tasks. This includes browser effects, AJAX, and interact with the DOM. Despite the introduction of CSS3 (which will elegantly handle browser effects and limited DOM manipulation), JQuery still has alot to offer the web developer. It has also been around for longer which means, for the moment, it has better cross-browser support.

JQuery is not meant to be used as an application framework. It does not provide a blueprint around which a developer can build a website. Instead, it offers a wide set of tools to make development much, MUCH easier.

Getting started...

Getting started with jQuery is easy; download the library script from the website and include it in your web-application as you would any other JavaScript file. Alternatively, Google provides live hosting of the jQuery so you could link to that to save on your bandwidth.

<!-- Include the JQuery Library code... JQuery will not work without this -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>


Selectors

JQuery works best by manipulating the DOM (the fancy, technical name given to the HTML page displayed by the browser), but to do this it needs a way of finding the elements to manipulate. To do this jQuery sports a CSS selector engine, meaning you just use standard CSS nomenclature to select an element.

For instance, if we had a div element with an id set to foo, in CSS we would write #foo {} to declare the style for that id. In JQuery, to search for and manipulate element foo you would write:

$('#foo').function()

Make sure the DOM is ready!

A common problem new developers have with jQuery is they start querying the DOM before it is ready. Browsers sometimes execute JavaScript before they have completely parsed the DOM, and this leads to errors where you manipulate the #foo class but it has not loaded on the page yet.

This problem is solved by calling the jQuery function that waits until the DOM has completely loaded:

$(document).ready(function {
      $('#foo').css('colour', 'red');
});

References:

Apr 12, 2012

Designing relational databases

While I was introduced to database theory in University, we never really did much in the way of practically implementing that theory. As such, when I am tasked to design a database for a web application I had no idea where to start. Well, not really; I had a vague idea of where to begin.

Thus I scrambled through my notes and various on-line articles to relearn the topic. Here are my notes; use them wisely...

  • The Relational Database Model describes a database that has a series of unordered relations (or a related set of information) that can be manipulated using operations that return tables.
  • Some interchangeable terms:
    Relations = tables (set of related information)
    Attributes = columns/fields (Descriptor of the information)
    Tuples = rows/record (Actual data)
  • Each table should only represent one (and only one) thing or event.
  • A primary key is a column/attribute of a relation/table that guarantees the uniqueness of a record/row/tuple. You can only have one primary key per relation.
  • A foreign key is an attribute used to reference a primary key in another relation/table.
  •  Normalisation is the process of simplifying the design of a database so that it achieves optimum structure.

    1. First normal form: All attributes must be atomic. Attributes should not be able to be broken down or repeated in a relation.

      In other words, an attribute cannot be an aggregate or list of data.
    2. Second normal form: Every non-key attribute must be dependant on the primary key.

      In other words, the postcode attribute will be dependant on the address and not the person. It stands that the address should be moved to it's own table.
    3. Third normal form: All non-key attributes are mutually independent. And attribute should not be reproducible or rely on information already existing in the tuple.

      For instance, the total cost for a sale is the sum of all costs, and does not deserve it's own table or attribute.
  • A join is used to collate relations into one relation with relevant data. This can be used to perform other operations without going back and forth between the tables.
  • A Natural join relies on an intersection of attributes (i.e. both tables contain attributes with the same name). This can be either a primary key or a foreign key.
  • An Inner Join specifies which matching attributes to use (this is done through the USING keyword). In other words, you get to to specify which attributes are going to be used to match records together.
  • An Outer Join is used where you want to display all data, whether they have a matching record or not. This is because the inner join would simply discard any record that did not have a matching attribute in the other table.
  • A view (also called a named query or stored query) is simply a SELECT statement that is given a name and is stored in the database.
  • A good practice in database design is to avoid having NULL values stored in your relation. If the attribute is not required to make the relation complete, do we need the attribute? Or can we move it to it's own relation?
  • Some common mistakes in database design are:
    1. Poor design/Planning
    2. Ignoring normalisation
    3. Poor naming standards
    4. Lack of documentation
    5. One table to hold them all (a sort of repeat of the 2nd normalisation rule)
    6. Using identity/guid columns as your only key
    7. Not using SQL facilities to protect data integrity
    8. Not using stored procedures
    9. Trying to build generic objects
    10. Lack of testing

References

Apr 5, 2012

CSS tips and tricks

As someone with a background in developing electronics and embedded systems, it is no shock that when it comes to pretty UX interfaces I suck. My interfaces is the definition of 'total suckage'. But nevertheless, the job market demands that I at least attempt to make pretty interfaces for clients; the critical criteria for modern web applications seem to lie in the appearance instead of the substance. But alas, I digress...

I have been doing research into CSS as it is the dominant method of creating nice structured web interfaces (yes, JavaScript can do that too but I prefer to stick to using JS for behavioural coding). So I have come across a HEAP of useful tutorials that will help turn your steaming pile of crap into glistening gold!

Rounded Borders

Rounded borders looks awesome on anything. Here is the code:

.roundBorder
{
     border: 2px solid #505050;
     /* Rounded Border */
    -webkit-border-radius: 8px; /* Saf3-4, iOS 1-3.2, Android ≤1.6 */
    -moz-border-radius: 8px; /* FF1-3.6 */
    border-radius: 8px; /* Opera 10.5, IE9, Saf5, Chrome, FF4, iOS 4, Android 2.1+ */

    /* useful if you don't want a bg color from leaking outside the border: */
    -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box;
}


Background Gradient

You can read more about this here, but for now here is some code for you to play with:

.gradient
{
    /* Background Gradient */
    background-color: #69aef1;
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #69aef1), color-stop(100%, #ffffff));
    background-image: -webkit-linear-gradient(top, #69aef1, #fff); /* Chrome 10+, Saf5.1+, iOS 5+ */
    background-image: -moz-linear-gradient(top, #69aef1, #fff); /* FF3.6 */
    background-image: -ms-linear-gradient(top, #69aef1, #fff); /* IE10 */
    background-image: -o-linear-gradient(top, #69aef1, #fff); /* Opera 11.10+ */
    background-image: linear-gradient(to bottom, #69aef1, #fff);
}


Word Wrapping/Breaking

This piece of CSS should provide nicer looking word-breaking/hyphenation:

    /* CSS3 word break */
    -ms-word-break: break-all;
    word-break: break-all;
    word-break: break-word;
    -webkit-hyphens: auto;
    -moz-hyphens: auto; 


Centre Tables (and Elements)

I used this code to make a table centre properly in one of my elements. I'm sure it could find uses elsewhere though:

.center
{
      /* Reset margins for the elements (defaults to centered( */
    margin-left:auto;
    margin-right:auto;
}


CSS toggled accordion

This effect is created using a simple unordered list with added radio button functionality. Here is the code:

/* Clean up the lists styles */
ul.accordion {
    list-style: none;
    margin: 0;
    padding: 0;
}

/* Hide the radio buttons */
/* These are what allow us to toggle content panes */
ul.accordion label + input[type='radio'] {
    display: none;
}

/* Give each content pane some styles */
ul.accordion li {
    background-color: #CCCCCC;
    border-bottom: 1px solid #DDDDDD;
}

/* Make the main tab look more clickable */
ul.accordion label {
    background-color: #666666;
    color: #FFFFFF;
    display: block;
    padding: 10px;
}

ul.accordion label:hover {
    cursor: pointer;
}

/* Set up the div that will show and hide */
ul.accordion div.content {
    overflow: hidden;
    padding: 0 10px;
    display: none;
}

/* Show the content boxes when the radio buttons are checked */
ul.accordion label + input[type='radio']:checked + div.content {
    display: block;
}


So our HTML code will then be:

<ul class='accordion'>
    <li>
        <label for='cp-1'>Content pane 1</label>
        <input type='radio' name='a' id='cp-1' checked='checked'>
        <div class='content'>
            <p>text</p>
        </div>
    </li>
   
    <li>
        <label for='cp-2'>Content pane 2</label>
        <input type='radio' name='a' id='cp-2'>
        <div class='content'>
            <p>text2</p>
        </div>
    </li>
</ul>


References:

  • This website is an absolute must! 'CSS3 Please!' lists a whole heap of cross-browser compatible CSS3 techniques that you can just copy and paste into your website!
  • Blog post by Kenneth Auchenberg on how to achieve word wrapping in pure CSS
  • Blog post by Scott Granneman on how to centre a table in CSS
  • Blog post by Mike Cherim on the different types of web page layouts; fixed, fluid/liquid, and elastic.
  • Another post about the three types of web page layouts (fixed, fluid, and elastic) by Extend Studio
  • w3schools CSS reference
  • Pure CSS toggle accordian implementation by Oliver Caldwell
  • CSS Menu Maker provides a range of open source css menus
  • A list of CSS tutorials by Design Festival

Mar 29, 2012

CodeIgniter: PHP web app authentication

I have recently begun using CodeIgniter as my PHP framework for quickly whipping up web applications. And as a continuation on my web application blog posts (such as my AJAX with JQuery and PHP tricks) I have decided to whip this one up about how to use the CodeIgniter framework to create a site wide authentication system.

This tutorial assumes some knowledge in database administration and basic knowledge of CodeIgniter (time of writing I was using version 2.1.0) and PHP (version 5.3.10).

Model

First we will need to know the data we will be saving. The following SQL script was created using MySQL, but you should be able to configure with some minor modifications:

CREATE TABLE IF NOT EXISTS `users` (
  `userID` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT 'The unique ID',
  `username` varchar(64) NOT NULL COMMENT 'A unique username',
  `password` varchar(128) NOT NULL COMMENT 'The password with embedded salt',
  `personID` int(10) unsigned zerofill NOT NULL COMMENT 'Foreign key to person data',
  `active` tinyint(1) NOT NULL COMMENT 'Whether the user is activated',
  `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'The date the user was created',
  PRIMARY KEY (`userID`),
  UNIQUE KEY `username` (`username`),
  KEY `personID` (`personID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



Now that we know what data we are storing, we can create our model in CodeIgniter. In the folder 'application/models/', create a file called auth_model.php.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Login Authentication Model Class
 *
 * This is the model that will access authentication data (and provide some
 * functions).
 *
 * @package        Application
 * @subpackage    Models
 * @category    Models
 * @author         Almighty Olive
 * @copyright    Copyright (c) 2012, olivecodex.blogspot.com.au
 */

class Auth_model extends CI_Model
{
    /**
     * Modified constructor class
     */
    function __construct()
        {
            parent::__construct();
       
        // Ensure that sessions are loaded
        $this->load->library('session');
    }

    /**
     * Secure hash generation function.
     *     $input - the data to be hashed
     *     $salt - OPTIONAL: the salt to be used in the hashing function
     *
     * For more info about hashing, please see http://crackstation.net/hashing-security.html
     */
    function createHash($input, $salt = null)
    {
        // If no salt is passed then generate it
        if ($salt === null)   
        {
            //get 256 random bits in hex
            $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
        }

        //Prepend the salt, then hash
        $hash = hash("sha256", $salt . $input);
   
        //store the salt and hash in the same string, so only 1 DB column is needed
        $final = $salt . $hash;
   
        return $final;
    }


    /**
     * De-hash function (provided it has been hashed like above)
     * Returns true if the hashed input matches what is stored in the database
     *
     *     $salthash - the salt and hash created by authed_hash (stored in your DB)
     *     $input    - the data to verify
     *     returns   - true if the password is valid, false otherwise.
     *
     * For more info about hashing, please see http://crackstation.net/hashing-security.html
     */
    function validate($input, $salthash)
    {
        // Extract the salt and hash from the stored string
        $salt = substr($salthash, 0, 64); //get the salt from the front of the hash
        $validHash = substr($salthash, 64, 64); //the SHA256

        // Create a hash using the input and salt
        $testHash = hash("sha256", $salt . $input); //hash the password being tested
   
        //If the hashes are exactly the same, the password is valid
        return $testHash === $validHash;
    }
   
    /**
     * For a given username and password combination, this function
     * will look-up the database and determine if the user can access
     * the system
     *     $username = the passed username
     *    $password = the passed password
     *    returns true if the user is active
     */
    function checkAuth($username,$password)
    {
        // Sets up the query parameters
        $this->db->select("*");
        $this->db->where("username",$username);
        $this->db->where("active",'1');

        // Executes the specified query
        $query = $this->db->get("users");

        // Checks that only one row exists
        if(($query->num_rows()>0) && ($query->num_rows()<2))
        {
            $data = array();

            // Grab the resulting row
                $data = $query->row();

            // Checks to see if the password is correct
            if ( $this->validate($password, $data->password))
            {
                    // Create a data array to save to the session session
                    $sessionArray = array( 'userID'=>$data->userID,
                        'username'=>$data->username,
                        'personID'=>$data->personID,
                        'main'=>array(),
                        'logged_in'=>'TRUE');
                    $this->session->set_userdata($sessionArray);

                    // Return from the function
                    return TRUE;
            }
        }

        // If we have arrived here, it means we were not successful
        return FALSE;
    }

    /**
     * Check if a session has already been created
     *    returns true if a session exists
     */
    public function check_session()
    {
        if ($this->session->userdata('userID') AND $this->session->userdata('logged_in')=='TRUE')
        {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Deletes all session data
     *    returns true if a session exists
     */
    public function logout()
    {
        $this->session->unset_userdata('userID');
        $this->session->unset_userdata('logged_in');
        session_destroy();
    }
}
?>


Custom Controller Class

CodeIgniter uses the MVC design pattern, so most of our processing will be through our Controllers. To make our application automatically check if a user has logged in (and redirect them to the login screen if they haven't), we will create a new parent controller class. ALL pages that need authentication will be required to be a child of our new class!

Create a new file in 'application/core/' called 'MY_Controller.php' (change MY_ to whatever you have set it in your config file).

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Application Controller Class
 *
 * This class object is a super class
 *
 * @package        CodeIgniter
 * @subpackage    Libraries
 * @category    Libraries
 * @author        ExpressionEngine Dev Team
 * @link        http://codeigniter.com/user_guide/general/controllers.html
 */

class MY_Controller extends CI_Controller
{
    function __construct()
    {
    // Performs all the initilisation for a controller
        parent::__construct();

    // Ensure that sessions are loaded
    $this->load->helper('url');

    // Ensure that sessions are loaded
    $this->load->library('session');

    // Load our Authentication Model
    $this->load->model('Auth_model');

    // Check our session to see if we are logged in or not
    if(!$this->Auth_model->check_session()){
        redirect('/auth/login');
    }
    }
}

// END Controller class

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */


Login page controller

Now we need to create a login controller. Note that this controller is NOT derived from our custom class! The custom class redirects to our Login page, so if you do this then you will just end up with a continuous loop!

Create a new file under 'application/controllers/auth/' (create the folder if necessary) called 'login.php'. Note that I am using three view files; header.php, footer.php and login.php. I won't bother making these files as they should be pretty straightforward; you just need a simple form (that redirects to the login page) with a username field, a password field and a submit button.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

    /**
     * Constructor for this controller.
     *
     * Load up some common modules
     *
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
        {
        // Performs all the initilisation for a controller
            parent::__construct();

        // Loads the URL helper (redirection)
        $this->load->helper('url');

        // Ensure that sessions are loaded
        $this->load->library('session');

        // Load our Authentication Model
        $this->load->model('Auth_model');
        }

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/auth/login
     *    - or - 
     *         http://example.com/auth/login/index
     *
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        // Loads the form helper
        $this->load->helper('form');

        // Loads the form validation library
        $this->load->library('form_validation');

        // Check our session to see if we are logged in
        if($this->Auth_model->check_session())
        {
            redirect('/');
        }

        // Set the validation rules for the form
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required');

        // Run Validation check
        if($this->form_validation->run() == TRUE){
            // Grab our submitted data
            $username = $this->input->post('username');
            $password = $this->input->post('password');

            // Check if the user details matches that in our database
            if( $this->Auth_model->checkAuth($username,$password))
            {
                // Authentication is successful
                redirect('/');
            }
        }

        // If we are here it means authentication has failed... load up the error page
        $this->load->view('slair_header');
        $this->load->view('slair_login');
        $this->load->view('slair_footer');
    }

    /**
     * Logout Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/auth/login/logout
     *
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function logout()
    {   
        // Perform the logout functions
        $this->Auth_model->logout();

        //Goes back to the login screen
        redirect('/auth/login/');
    }
}

/* End of file slair.php */
/* Location: ./application/controllers/slair.php */


Conclusion

You should now be able to just do the following on any controller that requires authentication to access:

class CLASSNAME extends MY_Controller {

     ....

}


The MY_Controller will automatically redirect to the Login page if no session has been detected, otherwise we have a valid user so it will continue processing the rest of the PHP script.

Enjoy!

References:

  • Blog post from Afruj Jahan about writing a simple Login authentication system in CodeIgniter
  • CodeIgniter website
  • List of useful CodeIgniter Tutorials
  • Article about why we should ALWAYS salt our passwords
  • Article about the best way to secure your passwords from Cracked Station

Mar 10, 2012

Using GIT

GIT is a distributed version control system. Unlike SVN, which is centralised, each copy of a git project tree contains it's very own repository. This makes it easier to create branches and forks for development without polluting the main code trunk.

  • To start your first local git repository:
    1. Initialise the repository
      git init
    2. Add all the files in the current directory
      git add .
    3. Commit your initial import
      git commit
  • To monitor changes and logs in your code:
      1. View the revision history
        git log
      2. View the file changes in the repository
        git diff
      3. View the changes for a specific revision and file/directory path
        git diff revision path
      4. Summary of the current changes to the repository
        git status
  •  Some house cleaning functions:
      1. To add a file:
        git add file
      2. To remove a file:
        git rm file
      3. To move a file:
        git mv file
      4. To remove all untracked files (such as temporary files used during compilation):
        git clean
  •  Configure your git instance
      1. Change your username
        git config --global user.name "Your Name"
      2. Change your email
        git config --global user.email email@domain.com
  •  Common functions
      1. Clone an existing repository
        git clone url
      2. Fetch the changes from remote master repository
        git fetch
      3. Similar to above, but this command will merge the changes as well
        git pull
      4. Push your changes to a remote repository
        git push url
      5. Commit all your changes to the local repository
        git commit -a
      6. Edit your last commit with latest changes
        git commit --append
      7. Toss away your last commit
        git reset HEAD^
      8. Assign blame for problematic files
        git blame file
  • Tags and branches
      1. Tags a version
        git tag -a name
      2. List tags
        git tag -l
      3. Show the details about a tag
        git show tag
      4. Create a new branch
        git branch branch
      5. Switch to a branch
        git checkout branch
      6. Delete a branch
        git branch -d branch
      7. List all branches
        git branch
      8. Merges a branch to our current working branch
        git merge branch
 References
http://schacon.github.com/git/gittutorial.html
http://gitref.org 

Mar 9, 2012

AJAX with JQuery and PHP

AJAX stands for Asynchronous JavaScript And XML, and allows us to make our websites seem more dynamic.

A first example...

Our first example outlines how this is done within a single page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <title>Ajax With Jquery</title>

       <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our own JQuery code to do the AJAX-y stuff -->
       <script type="text/javascript" charset="utf-8">

          $(document).ready(function(){
             $('#txtValue').keyup(function(){
                 $('#display').html($(this).val());
             });
          });

       </script>
    </head>

    <body>
       <label for="txtValue">Enter a value : </label>
       <input type="text" name="txtValue" value="" id="txtValue">

        <div id="display"></div>
    </body>
</html>



Pretty much all this will do is update the display section of of the page with the latest text in the text box. The event the script will listen for is a 'Key Up' event on the txtValue item. Pretty simple really...

Something a little more AJAX - The HTML

So our original example just showed how we could manipulate the DOM (Document Object Model) of the browser during run-time, without a page refresh. How can we use this knowledge utilizing the power of PHP? Well, first let us edit our HTML to something we can manipulate:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

       <title>Ajax With Jquery</title> <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our external JS script file... we will write this up later -->
       <script src="tutorial.js"></script>
    </head>

    <body>
         <form name="contact" method="post" action="">
            <label for="txtValue">Enter a value : </label>
            <input type="text" name="txtValue" value="" id="txtValue">
            <input type="button" name="submit" class="button" id="submit_btn" value="Send" />
         </form>
         <div id="display">
         </div>
   </body>
</html>

The JavaScript and JQuery file

Now we need to create the JavaScript file:

$(function() {
    // This will run when the item of class 'button' is clicked
    $(".button").click(function() {
 
         // Grabs the text input
         var name = $("input#txtValue").val();
         var dataString = 'txtValue='+ name;
         // This creates the AJAX connection
         $.ajax({
            type: "POST",
            url: "tutorial.php",
            data: dataString,
            dataType: 'json',
            success: function(data) {
               $('#display').html(data.text);
            }
         });
         return false;
    });
});

This simply sends data to an external php script (tutorial.php) and then change the contents of <div id="display"> to whatever it returns. This is much more AJAX-y.

The PHP file

The final thing we have to do is write the PHP output...

<?php
if (isset($_POST['txtValue'])) {
    $txtValue = stripslashes(strip_tags($_POST['txtValue']));
} else {$txtValue = 'Nothing';}
    echo json_encode(array('text' => $txtValue));
?>


Of course, there are multiple ways of achieving the same result, but this should help you get started.

Reference

Mar 8, 2012

SSH and Keys

Key Generation

On the server run the following command to create a pair of keys in ~/.ssh/ (or whatever the default is configured to on your system):

ssh-keygen
Disclaimer: You may need to install the cryptography packages and openSSH on your system.

The command will create the following files:

  • id_rsa: Your private key. This will identify the user on this machine.
  • id_rsa.pub: The public counterpart of the private key. This is distributed to other users.

On the client machine, copy/append the contents of id_rsa.pub from the server to ~/.ssh/authorized_keys (or whatever it is configured to on your system)
The user on the server should not be able to remotely log into the client without the use of password (as long as the connection is secure)

Example commands

The following example shows how to copy a file from the local machine to a remote machine. The command should not ask for a password if the above steps have been followed correctly and the SSH server is set-up to accept key authentication:

ssh [user@][host] cat < [local_file] ">" [remote_location]

The following example does the opposite: it copies a remote file to a local location:

ssh [user@][host] cat [remote_file] > [local_location]