Friday, April 25, 2014

First Steps in OpenShift

OpenShift is a Platform as a Service (PaaS) provided by the Linux gurus at Red Hat.  It is like Amazon Web Services (AWS) but not as confusing for a newbie.  For free (truly free, no CC required or worries about utilization based billing) they give you three "small gears", or three servers with 512 MB of RAM and 1 GB of hard drive space each.  After you sign up for a free account, you can host "applications" on your "gears".  The "applications" can have additional components added by installing "cartridges".  So, I have hosted a PHP "application" and added a MySQL "cartridge" to one of my "gears".  ((I hate the lingo, sorry but this type of jargon drives me nuts and I only have it here to provide you with an orientation to the platform.))
After you sign up for that free account the documentation kind of tapers off and people who are super nerds tell you how easy things are without actually explaining anything.  That is why I am writing this, to provide some context and explanation which will hopefully let someone understand this great platform.
Here are two things that had me stuck once I got started:

1. Install the "rhc" tools.  The process is simple and well documented on ( https://www.openshift.com/get-started ), with more details on ( https://www.openshift.com/developers/rhc-client-tools-install ).  
These tools are important as the platform is tightly bound to local files on your computer using Git (rather than copying files with FTP to/from the server).  With the tools installed and a basic PHP application, you can now use Git to make a nice web page with basic PHP.  If you want to add MySQL, things are a bit more complex.

2. Adding MySQL is easy but connecting to it is a little... different.  OpenShift uses environment variables to connect to your database.  They give you the normal credentials just in case, but it is best to use the environment variables so that your PHP code does not contain sensitive information which could get your site hacked.  As I am rusty on PHP, it gave me a few hours of head scratching before I got things to work right.  But here is some code to save you a lot of time:
define('DB_HOST',getenv('OPENSHIFT_MYSQL_DB_HOST'));
define('DB_PORT',getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER',getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
define('DB_PASS',getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
define('DB_NAME',getenv('OPENSHIFT_GEAR_NAME'));
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);
This will set the "$con" variable as your database connection so that you can do select and insert queries.

A longer tutorial is in the works, but I hope this can get just one newbie up and going with OpenShift.

No comments:

Popular Posts