Monthly Archives: September 2013

Can’t Gain Shell Access to Web Server

Are you having issues getting into your server's shell or command prompt? Some web hosts simply don't allow it, so you may not even be doing anything wrong. Be sure you have the proper login credentials. Often, the shell prompt or command line login details are the same as ftp login details, so try that first and if you can not get into a shell or command prompt still, try the solution I am about to offer!

 

PHPSHELL

PHPSHELL is a php app that lets you get a sudo shell from your web browser. I gotta tell you it was a bit buggy when I installed it, but I did get it to work. Here is how:

  1. Go to sourceforge.net and download. Here is the link: http://phpshell.sourceforge.net/
  2. unzip the folder you downloaded and upload it to your server.
  3. navigate to the pwhash.php file in the folder you uploaded using your browser and enter a username and password to get a secure password hash. My install didn't work without using this hash script even though it says it will, so be sure you do this. get the password has line and copy and paste it into the config.php file just below the line with the [users] line. I also had to delete all the comments between [users] and [aliases] to keep it from throwing an error. Makes no sense, but that's how I got it to work!
  4. then go to the install directory followed by /phpshell.php in your browser of choice and enter the user and password you set up into the login form.

That's it! you are done!

  1. c

How to get PHP Version

Do you need to know what version of PHP you are running on a web server? Here is a quick couple of ways to find out:

First and sometimes the easiest method if you have FTP access or cpanel access, is to upload a php info file to the server. By "php info file" I refer to a simple file with a call to the phpinfo() function. To make one, just copy and paste the following code into a file and name it info.php:

<?php

phpinfo();

?>

That's it, just upload the info.php file with above content in it to your root directory or wherever you like and open the file in a browser by going to example.com/info.php and it will tell you right in the heading what version of PHP you have! See below illustration for clarification:

phpinfo

Want another way? You got it! Try adding this to the top your PHP info.php file. The following code uses the phpversion() function to return the version of PHP you are using:

echo 'Current PHP version: ' . phpversion();
echo "<hr />";

add the above code just after the opening php tag and upload to the server and open the page again and you will see a line of text before the regular php info that says what version of PHP you have as long as this fuction is supported by your web server which it should.

Learning Laravel Models

Laravel models are based on the common MVC or Model-View-Controller principles. If you don't know what MVC is at all, you can Learn More about MVC Here because I just want to get to the meat of learning how to use Laravel Models in this Laravel models tutorial.

Prerequisites

You may have learned from following my Laravel tutorials, that you often need parts of other Laravel tutorials to fully understand the current tutorial. Well guess what? this applies here as well. You should have an understanding of the following areas of Laravel before attempting to learn about models:

The User Model

Since the user model is necessary in almost any modern web application, Laravel has created a basic user model and provided it in  app/models/User.php  for you to manipulate and copy as needed.

Generally models will follow the same naming convention as the example User Model. So if you added a new model to your project called Cars that was a representation of cars owned by the site's users then that model would also go in the app/models directory and would be named Cars.php so your complete path would of course be app/models/Cars.php.

Models and the Database

Each model in your project is directly related to a table in the database. By default that table will take the same name as the model, but  for the User model the table name is users, so for Cars, the table name would be cars. Follow that basic pattern and you should be okay. If you want to use a different name you can declare the table name for your model as you will see in the example code below.

Since every model interacts with a database table, the first thing we need to do is make our model class extend the Eloquent class. The Eloquent class is a database class Laravel uses with every model in order to interact with the database. So your first line of actual code should read:

class User extends Eloquent {}
Now we have started our class. Simply replace "User" with your class name if you are working on a different class.
To get an idea of how a model class should be written, you can follow the default User model that comes shipped with Laravel. Also while opening the class statement, the User model implements a couple interfaces:
implements UserInterface, RemindableInterface
so the complete first line of the User model looks like:
class User extends Eloquent implements UserInterface, RemindableInterface {

After that, as I mentioned above, is where you could change your table name, however since the User model doesn't do so, the following line could have been left out. It was most likely left in as a way to demonstrate how to name a table other than the default one for those who have a need or desire to do so. Here is how the User model declares its table name:

protected $table = 'users';
As I mentioned, since the name is users and that would be automatically assumed since the name of the model is User, this line is not mandatory but does show you what to do if you wanted to use a table named something other than users which you could do if you wanted simply by replacing "users" with "table_name" for example.
The next line in Users.php looks like:
protected $hidden = array('password');
What the above line does is prevents the user's password from being displayed when you might not want it to such as in a json API call. There are a couple of other measures that could be applied here to further protect your data such as the $fillable and the $guarded properties. $fillable tells Laravel which columns of your database table can be filled and guarded tells Laravel which ones cannot be filled basically. Here is an example of each:
protected $fillable = array('username', 'email');
protected $guarded = array('id', 'password');
The first line above tells us that username and email are allowed to be filled in the database by the user and the second line tells us that they cannot fill in the id and password fields.
Returning Data from a Model
The next practical thing the User.php Model allows us to do is return some data from the database with the following three functions:
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }
    public function getAuthPassword()
    {
        return $this->password;
    }
    public function getReminderEmail()
    {
        return $this->email;
    }
That is all for the User class actually, so lets explain the last three functions. The first is for returning a unique identifier of the user. The second returns the user's password and the third returns that user's reminder email address. Pretty simple really!

How to Use a Model

Everything you have learned so far is great, but how about seeing it in action? Yes, let's do that! In order to use the model, we need to define a route in the app/routes.php file, so open that file and append the following code to the end:
If the code worked, you will see:
bool(true)
only in the resulting page that opens. If it fails you will probably see a big long error page. in which case you will have to go back and check each step of this tutorial to see what you missed or make sure you set up the database and users table properly. If you have not done, so first, you need to create the users table by following this tutorial about database tables and Laravel:
When you are done and have successfully added a user to the users table, comment out the code in routes.php so you don't recreate the user every time you or someone else lands on that url.

Summary

To learn more about Laravel, follow more tutorials I have written by CLICKING HERE!

Creating Database Tables with Laravel

Okay, today we are going to cover how to get started with Laravel Database tables. You can create databases with Laravel, but for this tutorial on creating tables with Laravel, we are going to simply use phpmyadmin to make our database if you don't already have one made for your Laravel project.

Prerequisites

If you have not yet even installed Laravel, see my first tutorial on Laravel, Installing Laravel on XAMPP at http://jafty.com/blog/installing-laravel-php-framework-on-xampp/

That's really all you have to do before using this getting started tutorial, but you may need to reference other tutorials as you go depending on what you already know. I will try to reference the proper ones throughout this tutorial series to help you learn.

Selecting a Database for Laravel

As you probably are aware, most web sites need a database, so the first logical step to getting your Laravel project off the ground after installing the Laravel PHP framework itself, is to add a database. I am going to instruct you on how to install a MySQL database with Laravel. If you want to use a different database or storage option..... well, you are on your own. Sorry, but I don't know why you would want to use anything other than the most popular free developer's database available, MySQL. How do I know? You may have a legitimate reason, unfortunately, I just can't help you, but Laravel can, they have an abstraction layer that makes the syntax for all database and storage methods the exact same. No matter what database you use, you will be okay, but some of the steps in this particular tutorial will be slightly different, but don't worry too much about that, they should be obvious if you have enough experience with your database of choice which you should if you are ready to jump into learning a whole new PHP framework.

Configuring a Laravel Database

Now you are ready to make changes to the config files for Laravel to accommodate your database. Find the config file at app/config/database.php. If you are using a localhost install of Laravel for learning purposes, which is probably smart, then your config file changes will be minimal really. All you have to do is change the name of the database in the "database" variable at or about line number 57(depending on how many edits you made and what version of Laravel you are using). Change the default value of 'database' to the name of your database(unless you named your database, 'database'). I named my database 'laravel_test' for this tutorial. The database will be the main database for your project and will hold all of the project's tables.

Create a Laravel Database

Now you have to go to your PHPMyAdmin url and create the actual database. If you are developing on the localhost, you can go to localhost/phpmyadmin or wherever you installed phpmyadmin and create a database named after the same name you set in your config file for the 'database' option in the database.php config file. In my case, I named my database 'laravel_test' and created that same database from localhost/phpmyadmin.

Creating a Database Table in Laravel

Okay, now that you have created a database, it's time to really get to the meat of this tutorial and execute some code in Laravel to make a table on your new database.

Okay, remember I promised to tell you if you might need another tutorial to understand a part of this one? Here is the first case this has come up. You may wish to take a break from this tutorial now and check out my tutorial on Laravel Routes at:

http://jafty.com/blog/laravel-routes/

...or you may want to assume you can figure them out from the example in this tutorial, but you won't get the whole idea of routes from this tutorial as it only uses routes to make a database table and that is not what they are really all about. Routes are actual routes to your different parts of your Laravel project, hence the name, "routes".

So, whether or not you decided to take my advice and visit my "routes" tutorial, we are moving on! Here is the code you need to add to routes.php in order to create a database table using Laravel. as you can see, it's a lot simpler than creating a table in .sql and a bit faster than creating one in phpmyadmin if you use it correctly:

Route::get('make_table', function()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username', 32);
$table->string('email', 320);
$table->string('password', 60);
$table->timestamps();
});
});

If you have already learned about routes, you know from the above code to go to:

http://localhost/laravel/project1/public/make_table

in my case to execute the above code. Your path will depend on how you installed Laravel of course, but it should be similar if you are following my tutorials. You won't see anything but a blank window open when going to the URL. To check your work, go to phpmyadmin and examine the users table inside the database you created. It should have all the fields from the code above, but note that the timestamps() function actually creates two columns in the table, created_at and updated_at. So you should have six fields in your table, not five as you may have expected with only five lines of code.

Different Types of Data Fields

As you may know there are several types of data fields in Mysql, such as varchar, increment, bigint, etc just to name a few. Here is a list of Laravel commands for each so you can create the necessary fields of data for your own table:

Command Description
$table->increments('id'); Incrementing ID to the table (primary key).
$table->bigIncrements('id'); Incrementing ID using a "big integer" equivalent.
$table->string('email'); VARCHAR equivalent column
$table->string('name', 100); VARCHAR equivalent with a length
$table->integer('votes'); INTEGER equivalent to the table
$table->bigInteger('votes'); BIGINT equivalent to the table
$table->smallInteger('votes'); SMALLINT equivalent to the table
$table->float('amount'); FLOAT equivalent to the table
$table->decimal('amount', 5, 2); DECIMAL equivalent with a precision and scale
$table->boolean('confirmed'); BOOLEAN equivalent to the table
$table->date('created_at'); DATE equivalent to the table
$table->dateTime('created_at'); DATETIME equivalent to the table
$table->time('sunrise'); TIME equivalent to the table
$table->timestamp('added_on'); TIMESTAMP equivalent to the table
$table->timestamps(); Adds created_at and updated_at columns
$table->softDeletes(); Adds deleted_at column for soft deletes
$table->text('description'); TEXT equivalent to the table
$table->binary('data'); BLOB equivalent to the table
$table->enum('choices', array('foo', 'bar')); ENUM equivalent to the table
->nullable() Designate that the column allows NULL values
->default($value) Declare a default value for a column
->unsigned() Set INTEGER to UNSIGNED

Summary

That is it, you know now how to create a table using Laravel and routes! congratulations!

To learn more, see all my Laravel tutorials by Clicking HERE!

 

 

 

Connecting to Amazon Cloud Server using Filezilla

Go to Filezilla and click edit/settings and select "sftp" in the left column of the pop up window. Then in the right side of the window, click on the "Add key file..." button to add your new key file to Filezille so you can connect to your Amazon EC2 web server. Click "Ok" to close the Filezilla settings popup.

Now go to the Filezilla Site Manager by clicking on the icon under "File" in the top tool bar. enter the IP address of your server where it asks for a host. Select SFTP for protocol. Select Normal as the logon type. Enter ec2-user as the user name and leave the password blank. Finally click connect to open your server and place a check beside the box to always trust.... so you don't have to do it each time.

Convert .pem to .ppk File

If you have an Amazon EC2 server like me, you have probably had to convert a .pem file to a .ppk. No matter why you might need to convert a .pem to a .ppk, here is how it's done.

  1. Start PuTTYgen
  2. Click "Load" and select the .pem file then click "Ok" when it says it generate the key.
  3. Click "Save private key" then click "yes" to allow it to download without a pass-phrase as you don't need one with Amazon.
  4. That's it! Pretty easy huh! now X out the window and go get your key file from where you downloaded it to. You are done. Follow the link at the bottom of this tutorial for a new tutorial on how to connect to your EC2 web server using the FileZilla FTP client.

 

Low level steps:

  1. If you don't have PuTTYgen, download Putty and start the Start PuTTYgen app that comes with it. Google "download putty" to get the latest release.
  2. Just click Load and upload your .pem file.
  3. Do not mess with any of the defaults on the next screen unless you know what you are doing. Simply click "Download Private Key..."
  4. Save it to a safe place then follow the link below to learn how to use your new .ppk file with Filezilla to connect to your instance.

Connect to Amazon EC2 Server with FileZilla:

http://jafty.com/blog/?p=444

Amazon EC2 Lost Key Pair Fix

Okay, so say you lose your Amazon cloud server's key pair. uh oh, yes, you are in trouble, but not to worry to much, there is a solution. The solution is pretty complex if you try to learn it from Amazon docs, so here is an easy explanation that worked for me.

Prerequisites:

  • know the instance name
  • write down the availability zone:
    Zone: us-east-1b
  • Write down the instance id

High level steps:

Follow these high level steps if you know your way around Amazon's management console fairly well, otherwise, read on for more specific instructions for replacing an Amazon EC2 instance's key pair and regain access to your server.

  1. Shut down instance.
  2. Make a new AMI from the instance.
  3. Launch new instance using the AMI you created.
  4. Create and download a new key pair.
  5. Start the new instance and check that the key pair works then delete the old instance if you wish.

 

  1. Go to aws.amazon.com and login to your account. Select EC2/instances and place a check-mark beside the running instance you need a new key pair for and then select "stop" from the actions drop down. Finally click yes to stop the instance.
  2. With the same instance still checked, select "Create Image" from the "Actions" drop down. Give the image a name and a description and leave rest of defaults for most cases, then click "yes create". Take note of the id that looks similar to ami-5d623734 in the next window.
  3. Click on "AMIs" in the left nav and click "Launch" to launch a new Instance with the AMI". Click to continue. Make selections similar to your previous instance you are replacing the key pair for. Be sure to select the same availability zone.
  4. When you get to the third step of creating a new instance, where it says create a key pair, be sure you select "Create a new key pair" and create and download the file. Also be sure to select the same security group you had on the original server. When you are done creating the new instance, write down the instance id like: i-f9ead583 or i-11438868
  5. Wait for the instance to be created, it can take a few minutes. Go back to your Instances page and place a check beside the newly created Instance. Then you will see it's information pop up at the bottom of the page. copy the URL that looks like ec2-50-16-136-250.compute-1.amazonaws.com. You can get the IP from that URL by taking the numbers after the ec2- so in my case, the ip was 50.16.136.250 as you can see those numbers in the above URL.

Now that you have your new server, if you need help connecting to it, follow my next tutorial on how to connect to an Amazon ec2 instance and convert a .pem to a .ppk file here:

http://jafty.com/blog/?p=440

then after that, follow the link at the bottom of that tutorial to learn now to gain FTP access to your Amazon ec2 web server.

 

Enable mod_rewrite on Apache EC2 Linux Server

Today I was working on a client's Amazon Linux EC2 web server and had to enable mod_rewrite. This tutorial should help anyone else trying to do the same thing.

I read online that mod_rewrite was probably the culprit. Before assuming this, you should make sure your .htaccess file is working properly with correct permissions. You can simply make sure the file exists and set permissions to 777, test, then set your permissions back as they were to make your file secure once again. If that doesn't do it, then check your mod_rewrite using the following procedure:

  1. make a info.php file with only this for content: "<?php phpinfo(); ?>" and save it as info.php. Upload to your root directory and go to your domain name/info.php and search for the text "mod_rewrite" if you find it in the php info file, then your mod_rewrite is enabled. If not, then enable it.
  2. To enable mod_rewrite, try the command line command: sudo a2enmod rewrite

If mod_rewite was enabled then something else is wrong. Check your etc/httpd/conf/httpd.conf file. It should have the following in it:

AllowOverride All

Basically, you'll be adding All insted of None to AllowOverride, you do not want to edit the main directory configuration, you want to edit the one that looks like this:

<Directory "/var/www/html">

Not:

<Directory />

Then restart Apache with:

sudo service httpd restart

from the command line.

Now, if you are using WordPress and trying to enable Permalinks as I was, next, go to your wp-admin page and go to settings/permalinks and change from default to post-name and click the save button to save the changes and try again. If you did this before making mod_rewrite fixes, you may need to change back to default, save, and then change to post-name again and save one last time for the settings to work.

Good Luck!

Fixing WordPress Permalinks

Today I was working on a client's WordPress site who needed permalinks enabled so that the post name would show up in the address bar which is much better for SEO purposes. I enabled permalinks with the post name option in the admin of WordPress, but got page not found errors when visiting the posts, so I had to find the solution. Here is what I did.

I read online that mod_rewrite was probably the culprit. Before assuming this, you should make sure your .htaccess file is working properly and is writable from WordPress before setting permalinks up. You can simply make sure the file exists and set permissions to 777, enable permalinks, then set your permissions back as they were to make your file secure once again. If that doesn't do it, then check your mod_rewrite using the following procedure:

  1. make a info.php file with only this for content: "<?php phpinfo(); ?>" and save it as info.php. Upload to your root directory and go to your domain name/info.php and search for the text "mod_rewrite" if you find it in the php info file, then your mod_rewrite is enabled. If not, then enable it.
  2. To enable mod_rewrite, try the command line command: sudo a2enmod rewrite

If mod_rewite was enabled then something else is wrong. Check your etc/httpd/conf/httpd.conf file. It should have the following in it:

AllowOverride All

Basically, you'll be adding All insted of None to AllowOverride, you do not want to edit the main directory configuration, you want to edit the one that looks like this:

<Directory "/var/www/html">

Not:

<Directory />

Then restart Apache with:

sudo service httpd restart

from the command line.

Now, if you are using WordPress and trying to enable Permalinks as I was, next, go to your wp-admin page and go to settings/permalinks and change from default to post-name and click the save button to save the changes and try again. If you did this before making mod_rewrite fixes, you may need to change back to default, save, and then change to post-name again and save one last time for the settings to work.

Good Luck!

Adding Links to Other Blog Pages in a WordPress Post

Many times I have wanted to reference and link to another post in my blog from within a post or a page. This short tutorial will show you how to link to another post from within a post on any WordPress blog. I will show you how to create links to posts, pages and even categories. If you are using permalinks, you can simply use the permalink, so this guide is for those of us that don't always use permalinks.

For example, CLICK HERE TO SEE ALL OF MY WORDPRESS POSTS on this blog! and then look below to see how I did this.

First of all, I created the above link using the visual view that most people are most familiar with when using the WYSIWYG editor in the WordPress admin, however, after a quick demonstration on how I did it, the rest of this tutorial will be based on how to add links using the Text view tab in the WYSIWYG editor, just because it is easier to explain from a coder's perspective.

To create the link to my WordPress category, I typed the text "CLICK HERE TO SEE...." then highlighted that text and clicked on the link icon in the editor's tool bar. In the link dialog box that pops up, I replaced the default "http://" with just "index.php cat=48", ,checked the box to make the link open in a new window and saved it. That's it!

Getting the Category ID

you need the category ID for the link. The id for my blog's WordPress category was 48 in the above example as you can see. To get it, go to your WordPress admin area and go to posts/categories then hover over the category title and you will see a number in your browsers info bar which is at the bottom left of the webpages in Firefox and most other browsers. Sometimes you might have to activate the info bar from your browser/settings dialog if you don't see anything when hovering over links. The ID for categories will be right after the text that reads "tag_ID=" in the info bar when hovering over the category name in the edit category page.

 

Linking Without Permalinks

If you're not using Permalinks, here is how to link to pages, posts, and categories:

*Using the number values found in the ID column of the Posts, Categories, and Pages Administration, you can create links as follows.

Posts

To link to a Post, find the ID of the target post on the Posts administration panel, and insert it in place of the '123' in this link:

<a href="index.php?p=123">Post Title</a>

Categories

To link to a Category, find the ID of the target Category on the Categories administration panel, and insert it in place of the '7' in this link:

<a href="index.php?cat=7">Category Title</a>

Pages

To link to a Page, find the ID of the target Page on the Pages administration panel, and insert it in place of the '42' in this link:

<a href="index.php?page_id=42">Page title</a>

*information from the asteric to here was taken from http://codex.wordpress.org/Linking_Posts_Pages_and_Categories

laravellogo

Installing Laravel PHP Framework on XAMPP

This is a straight-to-the-point tutorial on how to install and use the Laravel PHP framework with a local XAMPP server on your machine's localhost. This post covers installing Laravel, but be sure to read other posts here in the Laravel Category to learn much more about the Laravel PHP framework.

Prerequisites:

  1. php version 5.3.7 or higher
  2. mcrypt module which comes with xampp and wampp by default so you shouldn't have to do anything, but maybe check php info to make sure it's there.
  3. Make sure openssl is enabled in your php.ini file
  4. make sure your httpd.conf file includes the httpd-vhosts.conf file in it.

Install Directions

  1. First, install composer by going to http://getcomposer.org/download/ and clicking on the link that reads: "Composer-Setup.exe" just under the "Windows INstaller" heading on that webpage.
  2. Secondly, install Laravel by going to http://laravel.com/ and click on the "Five Minute Quickstart" button to get a full set of instructions in case you need help, but I'll give you the basic install steps next to keep it quick and easy for you.
  3. Go into your Xampp directory, open the htdocs folder and make a new directory for your Laravel project. You can name it simply "laravel" if you like to keep it easy to follow these instructions.
  4. Open your Command Prompt in Windows by clicking on start/All Programs/Accessories/Command Prompt and change your current working directory to that of the laravel folder you just created by using the cd command followed by the directory path.
  5. copy and paste the following text into your command prompt window: composer create-project laravel/laravel your-project-name --prefer-dist
  6. before you hit enter, replace "your-project-name" with a project name of your choice such as "project1" as I did for this tutorial. Then press enter and Laravel will take several minutes to install usually.

That is all there is to a simple install on Xampp. Now you can go to your favorite browser and open up http://localhost/laravel/project1 and you should see the Laravel logo along with a quick message saying "You have arrived." Now it's time to learn how to use Laravel and find out about some of Laravel's features.

Bundles

Bundles are add-ons that you can download and plug into your Laravel installation for added functionality. Be sure to check out the bundles at http://bundles.laravel.com/

Click on the Laravel category at the bottom of this page or type "laravel" in the search box of my blog to find more tutorials on Laravel right here! ...or CLICK RIGHT HERE to jump there now.

Laravel Routes & Controllers

One of the first things I learned when discovering the Laravel PHP framework, was how to use routes. Routes are a simple method of using sub-directories in a URL to show different content. For example you can set a route to "about" and code that route to show your about page content. Let's expand on that idea with a code example to help you get it:

Go to your project directory in Laravel and locate the app directory and the file name routes.php. This is where you can add your own routes. Lets start with simple route by adding the following code to routes.php at the end of the file:

Route::get('about', function(){

return('<h1>About Us</h1>Jafty.com is a fully functional web development company offering almost any service to do with web development, including, but by no means limited to, PHP, HTML5, CSS3, JavaScript, Photoshop, Logo Design, Jquery, Server Installation, Site Migration, WordPress, Joomla, Linux servers, Windows servers, etc. Just ask, I pretty much do it all. Yes, Jafty.com is basically, jut me, Ian L. I do hire additional help as needed ,but I personally manage and oversee every project that comes through my company and make sure that it meets or exceeds my rigid quality control standards.');

});

You can copy and paste the above green text into your app/routes.php file at the end and it will produce the following when you go to (in my case)localhost/laravel/project1/public/about. Here is a screenshot:

Snap 2013-09-19 at 12.13.15Now you may not wish to put all that code inside your routes.php file, especially in times where you need a lot more code for a page. You can use controller classes with your routes to effectively put most of the code in another file which I will explain next.

Here is an example of a basic controller class:

class UserController extends BaseController {

    public function showWelcome()
    {
        return 'Hello controller world!';
    }

}

to make that class work, you would put the above code in a file named "UserController.php" inside of the app/controllers folder of your Laravel project directory and then add the following to your app/routes.php file at the end:

Route::get('usercontrol', 'UserController@showWelcome');

Finally, after you create a new controller, you always need to flush the autoload contents before the new controller will work, so do so by opening your command prompt that you use composer from, change the working directory to that of your application and type:

composer dump-autoload

I've found you don't need to do the above command if you only create a route, but if you make a controller, do it! Also if you have issues running the above command from localhost, make sure you have the correct path and command prompt. If you installed Composer through Windows, open a Windows command prompt. If you installed it in Xampp, open a Xampp command prompt etc.

That's all there is to learning how to use basic routes and basic controllers. Of course there are more complex solutions than this, but this will get you started off on the right foot at least. To learn more, CLICK HERE FOR MORE LARAVEL TUTORIALS. I have written a boat load of Laravel tutorials on this blog and am adding more daily as of September of 2013, so check back if it is still 2013 when you read this or the start of 2014 even.

Get Rid of Top Margin on Custom WordPress Themes

I found out from experience and from browsing the internet that a lot of people are having issues with a mysterious 28px margin appearing at the top of their blog when developing a custom theme or a page template for an existing theme.

The Problem

The problem is that a built-in core WordPress function inserts an inline style into the head of your webpage with a top-margin set to 28 pix.

The Reason

The reason for the 28px top margin is to make room for the WordPress top admin bar, so you may have noticed that this margin is only there if you are logged in.

The Cause

the cause of the inline style is the wp_head function. It happens most of the time when you do not call the wp_footer function at the bottom of the HTML markup, just before the closing body tag.

The Solution

Therefore, the most common solution to make this go away, is to simply make sure to include the wp_footer function in your theme's files just before the closing body tag. It can be inserted in either the page.php file or the footer.php file. It can also be inserted in any other page template file as long as it is directly before the ending body tag.

Converting .pem File to .ppk File

When working with Amazon's EC2 servers, you will need to know how to convert the key file which Amazon allows you to download in .pem format to a .ppk format. You can accomplish this task with the use of Putty and Puttygen, so if you don't have both, you can get them from:

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Convert your file by following the below instructions:

  1. Run Puttygen.
  2. From the menu option “Conversions”, select “Import key”
  3. In the dialog, locate the pem file and “Open” it.
  4. Change the comment from ‘imported-openssh-key” to a something more descriptive like “my-db-server”
  5. Optional: Enter a passphrase.
  6. Create PPK file by clicking on “Save private key”

PHP Create Database From SQL File

While migrating a WordPress website from my localhost to a live server today, I had an issue with creating the database from the sql dump file on the new live server. I won't get into why it wouldn't work besides to tell you it was a permissions issue that would of taken forever to fix, so instead I found this solution for creating a new database from a .sql file using a PHP script. This method is very light weight and works perfect!

Simply copy and paste the following code and give it an easily remembered name followed by the .php file extension and upload it and the sql dump file to your server wherever you want to run the script from.

<?php
ini_set('memory_limit', '5120M');
set_time_limit ( 0 );
/***************************************************************************
*                             sql_parse.php
*                              -------------------
*     begin                : Thu May 31, 2001
*     copyright            : (C) 2001 The phpBB Group
*     email                : support@phpbb.com
*
*     $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
*
****************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

/***************************************************************************
*
*   These functions are mainly for use in the db_utilities under the admin
*   however in order to make these functions available elsewhere, specifically
*   in the installation phase of phpBB I have seperated out a couple of
*   functions into this file.  JLH
*
\***************************************************************************/

//
// remove_comments will strip the sql comment lines out of an uploaded sql file
// specifically for mssql and postgres type files in the install....
//
function remove_comments(&$output)
{
   $lines = explode("\n", $output);
   $output = "";

   // try to keep mem. use down
   $linecount = count($lines);

   $in_comment = false;
   for($i = 0; $i < $linecount; $i++)
   {
      if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
      {
         $in_comment = true;
      }

      if( !$in_comment )
      {
         $output .= $lines[$i] . "\n";
      }

      if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
      {
         $in_comment = false;
      }
   }

   unset($lines);
   return $output;
}

//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
   $lines = explode("\n", $sql);

   // try to keep mem. use down
   $sql = "";

   $linecount = count($lines);
   $output = "";

   for ($i = 0; $i < $linecount; $i++)
   {
      if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
      {
         if (isset($lines[$i][0]) && $lines[$i][0] != "#")
         {
            $output .= $lines[$i] . "\n";
         }
         else
         {
            $output .= "\n";
         }
         // Trading a bit of speed for lower mem. use here.
         $lines[$i] = "";
      }
   }

   return $output;

}

//
// split_sql_file will split an uploaded sql file into single sql statements.
// Note: expects trim() to have already been run on $sql.
//
function split_sql_file($sql, $delimiter)
{
   // Split up our string into "possible" SQL statements.
   $tokens = explode($delimiter, $sql);

   // try to save mem.
   $sql = "";
   $output = array();

   // we don't actually care about the matches preg gives us.
   $matches = array();

   // this is faster than calling count($oktens) every time thru the loop.
   $token_count = count($tokens);
   for ($i = 0; $i < $token_count; $i++)
   {
      // Don't wanna add an empty string as the last thing in the array.
      if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
      {
         // This is the total number of single quotes in the token.
         $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
         // Counts single quotes that are preceded by an odd number of backslashes,
         // which means they're escaped quotes.
         $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

         $unescaped_quotes = $total_quotes - $escaped_quotes;

         // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
         if (($unescaped_quotes % 2) == 0)
         {
            // It's a complete sql statement.
            $output[] = $tokens[$i];
            // save memory.
            $tokens[$i] = "";
         }
         else
         {
            // incomplete sql statement. keep adding tokens until we have a complete one.
            // $temp will hold what we have so far.
            $temp = $tokens[$i] . $delimiter;
            // save memory..
            $tokens[$i] = "";

            // Do we have a complete statement yet?
            $complete_stmt = false;

            for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
            {
               // This is the total number of single quotes in the token.
               $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
               // Counts single quotes that are preceded by an odd number of backslashes,
               // which means they're escaped quotes.
               $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

               $unescaped_quotes = $total_quotes - $escaped_quotes;

               if (($unescaped_quotes % 2) == 1)
               {
                  // odd number of unescaped quotes. In combination with the previous incomplete
                  // statement(s), we now have a complete statement. (2 odds always make an even)
                  $output[] = $temp . $tokens[$j];

                  // save memory.
                  $tokens[$j] = "";
                  $temp = "";

                  // exit the loop.
                  $complete_stmt = true;
                  // make sure the outer loop continues at the right point.
                  $i = $j;
               }
               else
               {
                  // even number of unescaped quotes. We still don't have a complete statement.
                  // (1 odd and 1 even always make an odd)
                  $temp .= $tokens[$j] . $delimiter;
                  // save memory.
                  $tokens[$j] = "";
               }

            } // for..
         } // else
      }
   }

   return $output;
}

$dbms_schema = 'jafty_wplandio.sql';

$sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
$sql_query = remove_remarks($sql_query);
$sql_query = split_sql_file($sql_query, ';');

$host = 'localhost';
$user = 'jafty_wplandio';
$pass = 'Mypass11!';
$db = 'jafty_wplandio';

mysql_connect($host,$user,$pass) or die('error connection');
mysql_select_db($db) or die('error database selection');

$i=1;
foreach($sql_query as $sql){
echo $i++;
echo "
";
mysql_query($sql) or die('error in query: '.mysql_error());
}

?>

Of course, before running the above code, be sure to replace the variable values for the database name, user name and password towards the bottom of the script as well as the .sql file name above that.

<?php
ini_set('memory_limit', '5120M');
set_time_limit ( 0 );
/***************************************************************************
*                             sql_parse.php
*                              -------------------
*     begin                : Thu May 31, 2001
*     copyright            : (C) 2001 The phpBB Group
*     email                : support@phpbb.com
*
*     $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
*
****************************************************************************/

/***************************************************************************
*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 2 of the License, or
*   (at your option) any later version.
*
***************************************************************************/

/***************************************************************************
*
*   These functions are mainly for use in the db_utilities under the admin
*   however in order to make these functions available elsewhere, specifically
*   in the installation phase of phpBB I have seperated out a couple of
*   functions into this file.  JLH
*
\***************************************************************************/

//
// remove_comments will strip the sql comment lines out of an uploaded sql file
// specifically for mssql and postgres type files in the install....
//
function remove_comments(&$output)
{
$lines = explode("\n", $output);
$output = "";

// try to keep mem. use down
$linecount = count($lines);

$in_comment = false;
for($i = 0; $i < $linecount; $i++)
{
if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
{
$in_comment = true;
}

if( !$in_comment )
{
$output .= $lines[$i] . "\n";
}

if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
{
$in_comment = false;
}
}

unset($lines);
return $output;
}

//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
$lines = explode("\n", $sql);

// try to keep mem. use down
$sql = "";

$linecount = count($lines);
$output = "";

for ($i = 0; $i < $linecount; $i++)
{
if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
{
if (isset($lines[$i][0]) && $lines[$i][0] != "#")
{
$output .= $lines[$i] . "\n";
}
else
{
$output .= "\n";
}
// Trading a bit of speed for lower mem. use here.
$lines[$i] = "";
}
}

return $output;

}

//
// split_sql_file will split an uploaded sql file into single sql statements.
// Note: expects trim() to have already been run on $sql.
//
function split_sql_file($sql, $delimiter)
{
// Split up our string into "possible" SQL statements.
$tokens = explode($delimiter, $sql);

// try to save mem.
$sql = "";
$output = array();

// we don't actually care about the matches preg gives us.
$matches = array();

// this is faster than calling count($oktens) every time thru the loop.
$token_count = count($tokens);
for ($i = 0; $i < $token_count; $i++)
{
// Don't wanna add an empty string as the last thing in the array.
if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
{
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

$unescaped_quotes = $total_quotes - $escaped_quotes;

// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
if (($unescaped_quotes % 2) == 0)
{
// It's a complete sql statement.
$output[] = $tokens[$i];
// save memory.
$tokens[$i] = "";
}
else
{
// incomplete sql statement. keep adding tokens until we have a complete one.
// $temp will hold what we have so far.
$temp = $tokens[$i] . $delimiter;
// save memory..
$tokens[$i] = "";

// Do we have a complete statement yet?
$complete_stmt = false;

for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
{
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

$unescaped_quotes = $total_quotes - $escaped_quotes;

if (($unescaped_quotes % 2) == 1)
{
// odd number of unescaped quotes. In combination with the previous incomplete
// statement(s), we now have a complete statement. (2 odds always make an even)
$output[] = $temp . $tokens[$j];

// save memory.
$tokens[$j] = "";
$temp = "";

// exit the loop.
$complete_stmt = true;
// make sure the outer loop continues at the right point.
$i = $j;
}
else
{
// even number of unescaped quotes. We still don't have a complete statement.
// (1 odd and 1 even always make an odd)
$temp .= $tokens[$j] . $delimiter;
// save memory.
$tokens[$j] = "";
}

} // for..
} // else
}
}

return $output;
}

$dbms_schema = 'jafty_wplandio.sql';

$sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
$sql_query = remove_remarks($sql_query);
$sql_query = split_sql_file($sql_query, ';');

$host = 'localhost';
$user = 'jafty_wplandio';
$pass = 'Mypass11!';
$db = 'jafty_wplandio';

mysql_connect($host,$user,$pass) or die('error connection');
mysql_select_db($db) or die('error database selection');

$i=1;
foreach($sql_query as $sql){
echo $i++;
echo "
";
mysql_query($sql) or die('error in query: '.mysql_error());
}

?>