PHP
Image via Wikipedia

If you’d like to develop PHP and MySQL web apps in Linux but you’re not sure how to get started then feel free to follow along with this blog post. For the most part, installation and configuration is simple and straightforward.

Though this article is directed toward users of Mandriva Linux (my Linux distribution of choice for a desktop / web-development PC), the same instructions can apply to many of the different Linux distributions including Fedora, Red Hat Enterprise Linux, Ubuntu, and Eeebuntu. For a huge list and up-to-date news of Linux distributions available to you, take a look at the Distrowatch news site.

The easiest way to install all of the software in the LAMP stack (Linux Apache MySQL and PHP) quickly is to do it using the command-line (also known as the console). Since many new users are uncomfortable with the command-line, feel free to do all of these installations graphically using the software installer from your respective distribution.

If you’d like to proceed using the graphical installer built into Mandriva Linux, use the “Install & Remove Software” icon located in the main menu.

To install apache, mysql, and php using the Mandriva command-line, follow these instructions:

  • Open up a terminal by clicking on the Mandriva star and clicking on Terminal
  • Type “su” and press enter (this will log you in as the administrator or “root” user)
  • Enter your root password
  • Type “urpmi apache php mysql phpmyadmin nano”
  • If asked which version of apache, select a stable version to install (likely the first choice)
  • If asked which version of php, select the apache module version (not CGI or CLI)
  • If asked for permission to install extra software that is required for proper operation of the LAMP stack, select “yes” and proceed

Once the software has been installed, you should be able to open up Firefox and navigate to http://localhost . This should bring up a screen that says “It works!”, meaning that apache has been properly installed.

For reference, Mandriva Linux puts your web files in the directory /var/www/html . Straight away you may not be able to access those folders with your regular user so feel free to change the permissions of the directory recursively by using the command

  • chown -R yourusername:yourusername /var/www/html

Note that this operation is definitely not secure if you plan on actually hosting your website on the live Internet using this computer, but for local development you should be okay. :) To learn more about file and directory permissions in Linux, take a look at the official documentation.

Before you are able to access your databases through phpmyadmin, you will need to set your MySQL root password using the following command (being sure to change NEWPASSWORD to a password of your choice):

  •  mysqladmin -u root password NEWPASSWORD

Using Firefox (or whatever browser you normally use) navigate to http://localhost/phpmyadmin . Log into MySQL with your “root” user and the password you just entered into the command-line. This should give you access to your MySQL databases. For more information on how to use phpmyadmin, take a look at the official website.

Let’s create a small Hello World PHP web application by navigating to our web directory and creating it. Use the following commands to achieve this:

  • cd /var/www/html
  • nano test.php

In the editor screen that appears, enter

  • <?php echo "Hello World!"; ?>

Press CTRL-X and save the file before quitting. You should now be able to navigate to http://localhost/test.php and see your hello world application :)

Hopefully this has given you enough information to get you up and running. Please feel free to post comments if you’ve run into problems and hopefully I or another person in the community will be able to help you out.

Have fun with PHP on Linux!

Reblog this post [with Zemanta]
Tagged with:
 

Every website has ‘em. Forms. Places for users to enter data into your website. Whether it be a search box, a “Contact Us” form, or variables in the website address, at some point in the flow of your script these suckers are going to touch your database

Oh, that’s no problem — We’ll just take what they type in and run a query in MySQL on it!

WHOA, there! Are you sure you want to do that? Any input from a user should be treated like a nuclear fuel rod. You can handle it, but you’ve got to make sure you do it right. You wouldn’t just pick it up with your bare hands, would you?

Why? Just what are MySQL Injection attacks anyway?

Lets say your database has a table inside called ‘tbl_Users’. Inside ‘tbl_Users’ are a list of your users, which all have usernames, passwords, first names, last names, addresses, etc.

Let’s pretend you’ve got a website and in that website you have an area where users have to log in to gain access to a restricted area. After the user types in their username and password your site will check the database to verify the username and password are correct. If it is correct, your site will provide them access.

The query below is an extremely simplified version of what may be running on your site, though I have seen examples of this before.

SELECT * FROM `tbl_Users` WHERE `username`='".$_POST['username']."' AND `password`='".$_POST['password']."'"

Ugh. I feel dirty just writing that.

There are numerous problems in this example that relate not only to MySQL but to general security hazards. Better solutions would be to verify the username and password separately to make logging login attempts easy and also adding a “salt” to the password.

Though this article deals directly with MySQL injection hazards, it is advisable that you do your research when it comes to login forms and security. There are other hazards out there!

The direct MySQL injection threat is that unscrupulous users (read: bad ones) could enter this into your form:

username: no_one
password: ' OR ''=''

Which would make your query look something like this:

SELECT * FROM `tbl_Users` WHERE `username`='no_one' AND `password`='' OR ''=''

This query would allow that user access to restricted page by logging them in. There are a multitude of other ways this can be dangerous, but this is by far the easiest example.

You may be safe from query stacking, though. MySQL will not allow two queries to be executed in a single function call. To make it simple, consider this example, which will cause MySQL to throw an error:

username: no_one
password: ' OR ''=''; DELETE * FROM `tbl_Users`;

Okay so I’ve got this friend… and his website isn’t secure. What can I do to help him out?

The good news is that with a few precautions, your “friend’s” website will be pretty secure against these types of attacks. I say pretty secure because there is no way to prevent every attack. We can only do our best to increase security to a point to take every realistic precaution to prevent these attacks.

 

#1: Escape your variables!

Using the php function ‘mysql_real_escape_string’ you can “escape” the single quote character from user input. This is probably the easiest method to prevent MySQL injection attacks. It works by adding a backslash (“\”) before each quote that the user enters into their input. So, to use our example from before:

username: hey'there

becomes

username: hey\'there

This effectively stops MySQL injection in its tracks since it not only escapes the single quote (“‘”) character but also all other characters that the baddies can use to hijack your queries.

If you’ve got an array of data coming in, you can use this neat function that I found on the PHP mysql_real_escape_string page (code by “brian dot folts at gmail dot com”). It escapes all of the values in your array with ease.

To escape an array, use this function:

function mysql_real_escape_array($t){
return array_map("mysql_real_escape_string",$t);
}

Then you can call that function easily by passing your array to it:

$your_array = mysql_real_escape_array($your_array);

 

#2: Check the variable type of your input.

This is done by using the php functions “is_numeric()“, “is_string()“, “is_float()“, and “is_int()” to determine if the input the user is sending in is the same type that you were asking for. It’s not perfect, but if you were asking for a number and they sent in a word you know to discard it straight away and return an error thereby entirely avoiding any chance of a MySQL injection attack.

 

#3: Use Prepared Statements.

Consider switching from using mysql_xxx commands in php to MySQL Improved (mysqli). A great document by Zak Greant and Georg Richter cover a lot of the basics and reasoning behind this switch.

All of these things put together will help make your site better equipped to handle malicious injection attacks. I hope this gives you a better indication of what you can do to help secure your websites. I want to personally thank Sven Arild Helleland and exsecror.pip.verisignlabs.com who smacked me upside the head a few times while reviewing this article and helped to steer me in the right direction. Thanks a ton!

Leave a comment or two if this helped you at all or if you have different suggestions on how to secure your code from MySQL injection attacks!

This is really handy for those of us who have the same code handling multiple sites or multiple sub-domains.

A case in point: When I coded NetBoardz (my free forum hosting service now defunct), I had one codebase handling all 250 forums. How? Simple. When the code runs, it determines which site the user is loading and does different things (like using different databases) dynamically.

How to determine the domain the user is using to view your site:

$domain = $_SERVER['HTTP_HOST'];
if ($domain == "xyz") {
...
} else if ($domain == "uvw") {
...
}

In the example above you can see that we have put the domain that the user has used to view your site into the $domain variable, loading the value from the PHP global variable, $_SERVER. The $_SERVER variable is global, which means you can access it anytime and anywhere in your code.

For more information on PHP’s predefined global variables to see what’s available to you, click here.

How to determine the sub-domain the user is using to view your site:

Sample code is from NetBoardz, which is based off of phpBB 2:

$subdomain = strpos($_SERVER['HTTP_HOST'], ".");
$subdomain = substr($_SERVER['HTTP_HOST'], 0, $subdomain);
$dbname = "nb_".$subdomain;
mysql_select_db($dbname, $sql_link);

Here you can see that we retreived the whole hostname, including the top-level domain and subdomain, then used the PHP functions strpos and substr to take anything before the first dot. For example, the whole hostname “testforum.netboardz.com” passed through this code would end up as “testforum”.

After, we use that subdomain name to calculate which forum database to load. Of course, once you have the domain or subdomain in a variable, you are able to handle your code as you wish!

I hope this small tid-bit of code helps you out in some way. I know that there are tons of these snippets and tips littered across the internet and while I was learning PHP they were really handy. I’ll post more over time, always in this same category.