Pages

This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Monday, August 27, 2012

Installing LAMP Server On Ubuntu


Install Apache

To start off we will install Apache.
1. Open up the Terminal (Applications > Accessories > Terminal).
2. Copy/Paste the following line of code into Terminal and then press enter:
sudo apt-get install apache2
3. The Terminal will then ask you for you're password, type it and then press enter.

Testing Apache

To make sure everything installed correctly we will now test Apache to ensure it is working properly.
1. Open up any web browser and then enter the following into the web address:
http://localhost/
You should see a folder entitled apache2-default/. Open it and you will see a message saying "It works!" , congrats to you!

Install PHP

In this part we will install PHP 5.
Step 1. Again open up the Terminal (Applications > Accessories > Terminal).
Step 2. Copy/Paste the following line into Terminal and press enter:
sudo apt-get install php5 libapache2-mod-php5
Step 3. In order for PHP to work and be compatible with Apache we must restart it. Type the following code in Terminal to do this:
sudo /etc/init.d/apache2 restart

Test PHP

To ensure there are no issues with PHP let's give it a quick test run.
Step 1. In the terminal copy/paste the following line:
sudo gedit /var/www/testphp.php
This will open up a file called phptest.php.
Step 2. Copy/Paste this line into the phptest file:
<?php phpinfo(); ?>
Step 3. Save and close the file.
Step 4. Now open you're web browser and type the following into the web address:
http://localhost/testphp.php

Install MySQL

To finish this guide up we will install MySQL. (Note - Out of Apache and PHP, MySQL is the most difficult to set up. I will provide some great resources for anyone having trouble at the end of this guide.)
Step 1. Once again open up the amazing Terminal and then copy/paste this line:
sudo apt-get install mysql-server
Step 2 (optional). In order for other computers on your network to view the server you have created, you must first edit the "Bind Address". Begin by opening up Terminal to edit the my.cnf file.
gksudo gedit /etc/mysql/my.cnf
Change the line
bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
Step 3. This is where things may start to get tricky. Begin by typing the following into Terminal:
mysql -u root
Following that copy/paste this line:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yourpassword');
(Make sure to change yourpassword to a password of your choice.)
Step 4. We are now going to install a program called phpMyAdmin which is an easy tool to edit your databases. Copy/paste the following line into Terminal:
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
After that is installed our next task is to get PHP to work with MySQL. To do this we will need to open a file entitled php.ini. To open it type the following:
gksudo gedit /etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the semicolon (;).
Change this line:
;extension=mysql.so
To look like this:
extension=mysql.so
Now just restart Apache and you are all set!
sudo /etc/init.d/apache2 restart

Wednesday, August 22, 2012

How to Validate a Form Using PHP Part 2: Streamline Using Arrays

We’ve touched upon the basic elements of form validation and error messages in part 1 of this series, which outlines a relatively static method identifying errors and validating a form. In this edition we are going to make the elements we began with more dynamic and reduce the amount of script required to do so using arrays.

Setting Up the Form

First we’re going to want to create a form on a new .php document, mine is going to be called errorpart2.php. Below is my form complete with fields name, email, and comments.
<form id="commentform" method="post" action="errorpart2.php"> 
    <p> 
    <label for="name">Name:</label> 
    <br/> 
    <input name="name" id="name" type="text"/> 
    </p> 
    <p> 
    <label for="email">Email:</label> <br/> 
    <input name="email" id="email" type="text"/> 
    </p> 
    <p> 
    <label for="comments">Comment:</label> 
    <br/> 
    <textarea name="comments" id="comments" rows="4"></textarea> 
    </p> 
    <p> 
    <input name="submit" id="submit" type="submit" value="Submit" /> 
    </p> 
</form>  
The next step is to put in place a check to see if the form is submitted, so the script knows to validate. For those that have read part 1 of this series I had used a hidden input to pass this check, I have since done some additional research on the matter and found an alternative more secure method.
if (array_key_exists('submit',$_POST)){ 
//Form has been submitted 
}  
This method checks the $_POST array for the key ‘submit’, which is the array key for our Submit button, and would only be present if the form was submitted. We will be placing all of our validation related script within this IF statement, ensuring it only runs when required.

Laying Down Array Groundwork

We will need to define the arrays we will be using for this script, one containing all the field names on the form, one with all the mandatory fields, and one to store any errors we come across.
    // Fields that are on form  
    $expected = array('name''email''comments'); 
    // Set required fields 
    $required = array('name''comments'); 
    // Initialize array for errors 
    $errors = array();  
The $expected array serves to identify and process all  fields, mandatory or not. It also ensures that only the fields you specify are processed and prevents security issues from rogue $_POST values.


Making It Dynamic

The next part is where a big benefit of using arrays comes into play. Instead of typing out IF statements for each $_POST field, we can make use of the foreach statement to do this dynamically.
foreach ($_POST as $field => $value){ 
    // Make sure field was done correctly otherwise add error.  
 
This snippet goes through each key and the corresponding value that the $_POST array holds. This means that each field submitted will be processed, which is especially useful when dealing with long forms.
From within this foreach we now want to do two things to each variable passed through it..
1. Clean up the variable by eliminating whitespace if it is not an array. I used shorthand for this conditional statement:
// Assign to $temp and trim spaces if not array  $temp = is_array($value) ? $value : trim($value);  
2. If field is empty then make sure it is not required, otherwise add related error message to the $error array. For those unfamiliar with array_push, it can be used to append additional values into an existing array, in this case the one we defined before:
  1. // If field is empty and required, tag onto $errors array  
  2. if (empty($temp) && in_array($field, $required)) {  
  3.       array_push($errors, $field);  
  4.   
  5. }  
Once these two steps are in place, we have finished the foreach statement.

Handling the Errors

Now that we have the $error array with the names of each required field not filled out, we need to either accept the form or show the error messages.
If the form is done correctly:
if (empty($errors)){ 
        //The form is completed properly to do with as you please 
        unset($errors); 
}  
The unset(); function destroys the $errors array, so it does not cause incorrect error messages to be displayed.
To display error messages I placed the following lines of code next to the corresponding labels, only appearing when applicable:

<?php if (isset($errors) && in_array('name'$errors)){?> 
<div class="red">Please enter name</div> 
<?php } ?>  
This checks the $errors array for the specified field name , in this case ‘name’, which would only be present if an error happened. The same lines must be placed next to each field you are displaying an error for. I included the error message with my CSS styles applied, they can be found in the complete script at the bottom of this page.

Prevent Inputs from Clearing After an Error

When a user submits the form after completing some of the mandatory fields but not all, they would currently be shown an error message and the form would be cleared. This is a frustrating usability problem that can drive users away. Luckily, now that we have implemented array based validation, it is also easy to fix.
This line of code checks if there are any errors and, if there are, it inserts value = “” containing the user input submitted. This puts the value of the input to whatever the user had it as prior to the error, so they don’t have to retype anything. It is important to enclose this echo statement in literal ‘ ‘ quotes as well as wrap the $_POST[] in htmlentities. To ensure quotes and other symbols inputted do not break your page htmlentities converts some symbols to their HTML equivalent (example:  ” to &quot; ).
<input name="name" id="name" type="text"  
    <?php if (isset($errors)) { echo 'value="'.htmlentities($_POST['name']).'"'; } ?>  
/>  
The above will work for inputs, but the following tweak must be done to accommodate a textarea:
<textarea name="comments" id="comments" rows="4"><?php 
    if (isset($errors)) { echo htmlentities($_POST['comments']); } 
?></textarea>  
It is important to note that in order to avoid white space, make the <?php tags touch the textarea tags.

How to Validate a Form Using PHP Part 1: Streamline Using Arrays

Having a site visitor fill out a form is the primary way to gather information. Forms are the main line of communication with anyone that visits your site, so taking the time to make sure users fill them out correctly is key. Using PHP, we are able to ensure that all fields are properly filled out before submission, with required adjustments being called to attention through the use of error messages.

The CSS & HTML Groundwork

Let’s start off by opening up a fresh php document and putting a form within it. I have created errorpart1.php

<html>
    <head>
        <title>Form validation using PHP</title>
        <style type="text/css"><!--Styles--></style>
    </head>
    <body>
        <div id="content">
           <!--PHP and Form to go here-->
        </div>
    </body>  
</html>  
With the following styles applied to the form:

*{
    padding:0px;
    margin:0px;
}
body{
    text-align:center;
    font:11px "Lucida Grande",Arial,sans-serif;
}
#content{
    width:300px;
    text-align:left;
    margin:10px;
}
.formitem{
    width:100%;
    padding6px;
    font:11px "Lucida Grande",Arial,sans-serif;
}
h2{
    font:18px "Helvetica",Arial,sans-serif;
}
.box{
    width:100%;
    padding:10px 0px 10px 5px;
    margin-bottom8px;
    font-weight:bold;
}
.green{
    background-color:#95ca78;
    border-bottom:solid 1px #8AA000;
}
.red{
    background-color:#FDCBCA;
    border-bottom:solid 1px #E8514A;
 Next we have to construct our form, I have chosen to create a three field form, including one hidden field entitled “submitted”, which serves to check if the form has been completed.
<form action="index.php" method="POST" enctype="multipart/form-data">
    <h2>Title</h2>
    <input class="formitem" type="text" name="title"/>
    <br/><br/>
    <h2>Content</h2>
    <textarea class="formitem" name ="textentry" rows="3"></textarea>
    <input type="hidden" name="submitted" value="1">
    <br/><br/>
    <input type="submit" value="Submit"/>
</form>  

Now that we’ve laid out and styled up our page, it’s time to come in with some PHP.

The PHP and Validation

First we’ll use the hidden field (“submitted”) that we created earlier to check if the form is ready to be validated aka if they submitted it. We can do this with a simple IF statement, checking to see if submitted has a value of “1″, which it it automatically set to on form submission. This prevents error messages from popping up unless the form was actually completed and turned in.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
   //Do something
}
?>
Next up we have to check each mandatory field for a value of some kind. I have decided that both the title and content fields are mandatory for this example. The below code checks for values in each field on the form and assigns them to a variable if they exist.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
    if ($_POST[title]){
        $title = $_POST[title]; //If title was entered
    }
    if ($_POST[textentry]){
        $textentry = $_POST[textentry]; //If comment was entered
    }
}  
Now that we have put the values retrieved from the form into variables, we can perform a check to see if any are blank. If they have all been filled out properly, a message alerts them they completed the form properly.
//If all fields present
if ($title && $textentry){
    //Do something
    echo "<div class=\"box green\">Form completed!</div>";
}
?>  
Now for those of you that are currently questioning why I didn’t combine the last two parts into one big IF statement, hold on, it’s error message time.

At this point in the game, we want to go back to where we first assigned the $_POST variables to strings variables, appending an else to each IF statement.
if ($_POST['submitted']==1) {
    $errormsg = ""//Initialize errors
    if ($_POST[title]){
        $title = $_POST[title]; //If title was entered
    }
    else{
        $errormsg = "Please enter title";
    }
    if ($_POST[textentry]){
        $textentry = $_POST[textentry]; //If comment was entered
    }
    else{
         ($errormsg){ //If there is already an error, add next error
            $errormsg = $errormsg . " & content";
        }else{
            $errormsg = "Please enter content";
        }
    }
}  
That last section might have seemed like a lot, so let’s break it down.
First off we established the variable $errormsg, which will contain a string with all the errors we come across.
$errormsg = ""//Initialize errors  
Next we append the first IF statement for the title field, stating that if there is no value, set the  

$errormsg to store that error.
else{
    $errormsg = "Please enter title";
}  
When we check the next field, textentry, we will essentially be doing the same thing, although this time we must check if $errormsg has any errors stored from the previous IF. Should this be the case, we must append our current error message to the previous one.
else{
    if ($errormsg){ //If there is already an error, add next error
         $errormsg = $errormsg . " & content";
    }else{
         $errormsg = "Please enter content";
    }
}  
At this point your $errormsg variable should have an accurate list of error messages stored. Now it is time to alert the user of any problems.
if ($errormsg){ //If any errors display them
    echo "<div class=\"box red\">$errormsg</div>";
}  
And that’s it. You’ve created a basic form validation/alert system, good work. There are a number of other tweaks that can be added to a form validation script, so be sure to stay tuned for Part 2.




 

Sunday, August 12, 2012

Make WAMPServer Run Automatically on System Start-up

 As with all web developers, it’s always important to test your projects locally before putting it out there for the entire web community to see. One must-have developer tool for this purpose is WAMPServer. We’ve all wished it’s automatically up and running when we need it. These easy steps will help you automate WAMPServer to run on system start-up.

For those unfamiliar with WAMPServer, it is a development package that lets you run web development projects locally. WAMP stands for Windows, Apache, MySQL, PHP/Perl/Python. It’s basically four programs packaged to work as one. WAMP basically turns any Windows PC into a localized web server. The Linux counterpart is called LAMP, obviously.

Once WAMPServer is installed in your PC, you’ll be able to test your web projects before putting it into the live environment. But I always found it a hassle to manually start the service every time I need it. With these easy steps, you’ll never have to manually start WAMPServer ever again.

   From All Programs, go to the Accessories folder and select Run. A shortcut for this is Windows Key + R.

   Type services.msc and click OK. This will open the Services Management Console.
   
   In Services Management Console, look for ‘wampapache‘. The Startup Type will be set to ‘Manual’ and so we’ll need to change this to ‘Automatic‘. Right-click on it and select ‘Properties’.

    In the properties window, select ‘Automatic‘ for ‘Startup Type‘. Then, click on ‘Apply‘ and then close the property window. We’ve just set the Apache side of WAMP to run automatically on startup.

   
   Still in Services Management Console, look for ‘wampmysqld‘. We’ll also set this to automatic, so right-click on it and select ‘Properties‘.

   
    Select ‘Automatic‘ for ‘Startup Type’. Click on ‘Apply’ and then close the Properties and Services Management Console.
  
   Restart your machine/PC.
   After the restart, log back in and open a browser. Type localhost (127.0.0.1) in the address bar. localhost is the address for the local installation of WAMPServer in your PC. If the Server Configuration page for WAMPServer loads – Congratulations, you’ve just successfully automated your WAMPServer startup.

Thursday, July 5, 2012

Shortcut the else

This tip accidentally stumbles upon a useful practice, which is to always initialize variables before you use them. Consider a conditional statement that determines whether a user is an administrator based on the username:
<?php
 
if (auth($username) == 'admin') {
    $admin = TRUE;
} else {
    $admin = FALSE;
}
 
?>
This seems safe enough, because it’s easy to comprehend at a glance. Imagine a slightly more elaborate example that sets variables for name and email as well, for convenience:
<?php
 
if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} else {
    /* Get the name and email from the database. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
}
 
?>
Because $admin is still always explicitly set to either TRUE or FALSE, all is well, but if a developer later adds an elseif, there’s an opportunity to forget:
<?php
 
if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
    $moderator = FALSE;
}
 
?>
If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition.
By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether:
<?php
 
$admin = FALSE;
$moderator = FALSE;
 
if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email'];
}
 
?>
Regardless of what the rest of the code does, it’s now clear that $admin is FALSE unless it is explicitly set to something else, and the same is true for $moderator. This also hints at another good security practice, which is to fail safely. The worst that can happen as a result of not modifying $admin or $moderator in any of the conditions is that someone who is an administrator or moderator is not treated as one.
If you want to shortcut something, and you’re feeling a little disappointed that our example includes an else, we have a bonus tip that might interest you. We’re not certain it can be considered a shortcut, but we hope it’s helpful nonetheless.
Consider a function that determines whether a user is authorized to view a particular page:
<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username)) {
            return TRUE;
        } elseif (isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>
This example is actually pretty simple, because there are only three rules to consider: administrators are always allowed access; those who are blacklisted are never allowed access; and isAllowed() determines whether anyone else has access. (A special case exists when an administrator is blacklisted, but that is an unlikely possibility, so we’re ignoring it here.) We use functions for the rules to keep the code simple and to focus on the logical structure.
There are numerous ways this example can be improved. If you want to reduce the number of lines, a compound conditional can help:
<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username) || isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>
In fact, you can reduce the entire function to a single compound conditional:
<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) {
        return TRUE;
    } else {
        return FALSE;
    }
}
 
?>
Finally, this can be reduced to a single return:
<?php
 
function authorized($username, $page) {
    return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page));
}
 
?>
If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive.
This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply:
<?php
 
function authorized($username, $page) {
 
    if (isBlacklisted($username)) {
        return FALSE;
    }
 
    if (isAdmin($username)) {
        return TRUE;
    }
 
    return isAllowed($username, $page);
}
 
?>
This uses more lines of code, but it’s very simple and unimpressive (we’re proudest of our code when it’s the least impressive). More importantly, this approach reduces the amount of context you must keep up with. For example, as soon as you’ve determined whether the user is blacklisted, you can safely forget about it. This is particularly helpful when your logic is more complicated.

Know the Difference Between Comparison Operators


This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems.
If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading:
<?php
 
$authors = 'Chris & Sean';
 
if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}
 
?>
Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is!
This can be corrected with a strict comparison:
<?php
 
if (strpos($authors, 'Chris') !== FALSE) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}
 
?>

Use an SQL Injection Cheat Sheet


This particular tip is just a link to a useful resource with no discussion on how to use it. Studying various permutations of one specific attack can be useful, but your time is better spent learning how to safeguard against it. Additionally, there is much more to Web app security than SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous.
We can provide some much-needed context, but because we don’t want to focus too much on one attack, we’ll first take a step back. Every developer should be familiar with good security practices, and apps should be designed with these practices in mind. A fundamental rule is to never trust data you receive from somewhere else. Another rule is to escape data before you send it somewhere else. Combined, these rules can be simplified to make up a basic tenet of security: filter input, escape output (FIEO).
The root cause of SQL injection is a failure to escape output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP apps that construct queries as follows:
<?php
 
$query = "SELECT *
          FROM   users
          WHERE  name = '{$_GET['name']}'";
          
?>
In this case, the value of $_GET['name'] is provided by another source, the user, but it is neither filtered nor escaped.
Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted.
Assuming we're using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called "defense in depth" and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity:
<?php
 
// Initialize arrays for filtered and escaped data, respectively.
$clean = array();
$sql = array();
 
// Filter the name. (For simplicity, we require alphabetic names.)
if (ctype_alpha($_GET['name'])) {
    $clean['name'] = $_GET['name'];
} else {
    // The name is invalid. Do something here.
}
 
// Escape the name.
$sql['name'] = mysql_real_escape_string($clean['name']); 
 
// Construct the query.
$query = "SELECT *
          FROM   users
          WHERE  name = '{$sql['name']}'";
 
?>
Although the use of naming conventions can help you keep up with what has and hasn't been filtered, as well as what has and hasn't been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not.
Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps:
<?php
 
// Provide the query format.
$query = $db->prepare('SELECT *
                       FROM   users
                       WHERE  name = :name');
 
// Provide the query data and execute the query.
$query->execute(array('name' => $clean['name']));
 
?>
The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection.

MySQL Server Crashed – Site was still online!

You don’t hear this often… MySQL server crashed and the sites hosted in that server went offline for hours together. But, when a similar thing happened to my VPS, it wasn’t the case. My site was still online, while I was troubleshooting the issue with MySQL server. Ultimately, I could not figure out the issue and I had to purge the entire MySQL installation. However, I was still cool during the entire process. You may ask how. Here is what happened and how you can prevent the same for your own VPS too…

First Things First

As part of regular tweaking of MySQL, I changed a few things in my.cnf, then restarted the mysqld. Bump! It didn’t start. I reverted the changes. Still it didn’t budge. Immediately I knew that MySQL server has crashed for unknown reason. Upon checking the log, here is what I found…


120525 06:54:11 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
120525  6:54:11 [Note] Plugin 'FEDERATED' is disabled.
06:54:11 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=31457280
read_buffer_size=524288
max_used_connections=0
max_threads=100
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 133850 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0xffffffffbfb01d80
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = ffffffffbfb03ab8 thread_stack 0x20000
/usr/libexec/mysqld(my_print_stacktrace+0x2d)[0x83b70e2]
/usr/libexec/mysqld(handle_fatal_signal+0x4a2)[0x829d156]
[0xb777c400]
/usr/libexec/mysqld(_Z18ha_resolve_by_nameP3THDPK19st_mysql_lex_string+0xad)[0x82a104c]
/usr/libexec/mysqld(_Z14open_table_defP3THDP11TABLE_SHAREj+0x1822)[0x82213c2]
/usr/libexec/mysqld(_Z15get_table_shareP3THDP10TABLE_LISTPcjjPij+0x197)[0x8169869]
/usr/libexec/mysqld(_Z10open_tableP3THDP10TABLE_LISTP11st_mem_rootP18Open_table_context+0x545)[0x817010a]
/usr/libexec/mysqld(_Z11open_tablesP3THDPP10TABLE_LISTPjjP19Prelocking_strategy+0x456)[0x8171683]
/usr/libexec/mysqld(_Z20open_and_lock_tablesP3THDP10TABLE_LISTbjP19Prelocking_strategy+0x54)[0x8171f86]
/usr/libexec/mysqld[0x81adf41]
/usr/libexec/mysqld(_Z11plugin_initPiPPci+0x8dc)[0x81b0db9]
/usr/libexec/mysqld[0x8133a34]
/usr/libexec/mysqld(_Z11mysqld_mainiPPc+0x42a)[0x8136cc8]
/usr/libexec/mysqld(main+0x27)[0x812ce33]
/lib/i686/nosegneg/libc.so.6(__libc_start_main+0xe6)[0xb7288ce6]
/usr/libexec/mysqld[0x812cd95]

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (0): is an invalid pointer
Connection ID (thread ID): 0
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
120525 06:54:11 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
I tried everything I could, for about 90 minutes. Then I gave up and purged the entire MySQL installation and installed it again. Viola! It started fine! Then it was only a matter of taking the latest database backup and putting it back.