Idle thoughts and technical knots.

Setup Laravel queue on shared hosting

We specialise in bespoke web and mobile development at Papertank, and we’re proud to use Laravel as our PHP framework of choice on web and API projects.

When it comes to hosting a Laravel application, installing on a shared host is perfectly possible, although we normally use a more powerful VPS server for more flexibility and control. We’ve previously blogged about setting up installing Laravel on shared hosting on papertank.co.uk. If you do go down the shared hosting route, you’ll want to make sure you are using a decent web hosting company. This will save a lot of headache and make deploying custom apps much easier. We recommend Cloud Above in Cornwall for great value and support.

Modern web apps use queues for background job handling of intensive tasks, allow your API or front-end app to return data, redirect the user, or perform other actions without waiting for the ‘job’ to finish. Laravel’s driver based queue system makes this easy to set up with Beanstalkd, Amazon SQS or Redis. Unfortunately shared hosting makes using these services difficult or impossible, since your host will often forbid installing software or logging in as root.

Laravel 5’s new database driver fills in for other tools, storing the jobs on a database table – https://laravel.com/docs/5.2/queues. The next step is running or listening for jobs using the command line ‘artisan’ tool, which can be a little tricky on shared hosting without process monitors. To get around this, you can use a cron job which can usually be setup in cPanel on shared hosting, however cron jobs can only be run once per minute which isn’t ideal for high traffic websites.

As a workaround, we recently customised a Laravel web app using the built in Task Scheduler. By setting up the server’s cron to run the schedule:run command every minute, our application spawns off a new queue:listen process and checks to see if it needs restarted every 5 minutes.

/**
* Define the application's command schedule.
*
* @param IlluminateConsoleSchedulingSchedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
	$path = base_path();
	$schedule->call(function() use($path) {
		if (file_exists($path . '/queue.pid')) {
			$pid = file_get_contents($path . '/queue.pid');
			$result = exec("ps -p $pid --no-heading | awk '{print $1}'");
			$run = $result == '' ? true : false;
		} else {
			$run = true;
		}
		if($run) {
			$command = '/usr/bin/php -c ' . $path .'/php.ini ' . $path . '/artisan queue:listen --tries=3 > /dev/null & echo $!';
			$number = exec($command);
			file_put_contents($path . '/queue.pid', $number);
		}
	})->name('monitor_queue_listener')->everyFiveMinutes();
}

The full code for this setup is on Gist at https://gist.github.com/davidrushton/b7229df4c73372402fc1

If you’re looking for more help with Laravel, you should check out the following websites which we subscribe to and read regularly.

Of course, if you’re looking for a Glasgow based company with experience building advanced web apps with Laravel then please get in touch

Setup Laravel on shared hosting

Hosting Laravel

We’ve always specialised in PHP development at Papertank, but for the past 12 months we’ve been exclusively using the excellent Laravel framework for our bespoke web projects.

Laravel is relatively straightforward to get set up, particularly since it utilises  the new PHP dependency manager, Composer. For a quick start guide see the Laravel Docs.

Installing on a shared host is perfectly possible, although we normally use a more powerful VPS server for more flexibility and control. You’ll want to make sure you are using a decent web hosting company. This will save a lot of headache and make deploying custom apps much easier. We recommend South West Broadband in Cornwall for great value and support.

Installing on shared hosting

If you decide to use shared linux hosting, setting things up can be a little more footery, but following these steps should hopefully help fix main two issues:

Requirements

Laravel only has two main requirements which you’ll need to make sure your shared server meets:

  • PHP >= 5.4
  • MCrypt PHP Extension

Before you go any further however, you’ll also need to check (or ask) if your web server and hosting company also allows:

  • SSH shell access
  • PHP 5.4 command line interface

Public Path

If you’re installing and using Laravel correctly, you’ll be forced to put all the public content of your website (including js, css and img assets) into a /public directory. When using cPanel on a shared linux server, however, you will normally put your files in a public_html directory which is already accessible publicly.

Placing the Laravel files in your public_html directory has two consequences:

  • All of your sensitive files (including temporary files) might be openly accessible through the web browser
  • Your web addresses will be ugly, since they might look like http://example.com/public/contact

The easiest way (we think) to fix this is simply:

  1. Install your Laravel app in the directory above public_html inside a new folder of your choosing, e.g. code.
  2. Move the index.php file and .htaccess files from the laravel public folder to your normal public_html directory.
  3. Update the index.php file to reflect the path to your new code folder (or whatever you called it in step 1)

For example, from the normal index.php file (GitHub) we now have the following:

<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/

require __DIR__.'/../../code/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/

$app = require_once __DIR__.'/../../code/bootstrap/start.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simply call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have whipped up for them.
|
*/

$app->run();

SSH in to your server and run something similar to the below (replacing the italics with your values).

  cd /home/username/public_html
  ln -s /home/username/code/public/css css
  ln -s /home/username/code/public/img img

 

This creates an alias for the css and img folders from your laravel public directory inside the public_html directory.

Composer

Still with us? Load up your website in your browser and you’ll no doubt see a blank white page (if error reporting is off), or the following:

Warning: require(/home/username/code/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /home/username/code/bootstrap/autoload.php on line 17
Fatal error: require(): Failed opening required '/home/username/code/bootstrap/../vendor/autoload.php' (include_path='.:/opt/alt/php54/usr/share/pear:/opt/alt/php54/usr/share/php') in /home/username/code/bootstrap/autoload.php on line 17

This means we haven’t installed laravel (and its dependencies) via Composer.

SSH in to your server again and cd into the directory containing your laravel code (not public_html).

You’d normally install composer by running:

   curl -sS https://getcomposer.org/installer | php

 

But you’ll probably get the error

Some settings on your machine make Composer unable to work properly.
Make sure that you fix the issues listed below and run this script again:

Let’s fix this by creating a custom php.ini file in the same directory with the content from https://gist.github.com/davidrushton/8a65e6c194786bec881a

suhosin.executor.include.whitelist = phar;
disable_functions = none;
memory_limit = 512M;

 

Now if we run the command again specifying that we want to use this new php.ini file, composer should be installed correctly:

curl -sS https://getcomposer.org/installer | php -c ./php.ini

 

Now you want to install laravel fully by running the command

php -c ./php.ini composer.phar install

 

You can periodically run the following command to update the version of the laravel framework and other components.

php -c ./php.ini composer.phar update

Other Resources

If you’re looking for more help with Laravel, you should check out the following websites which we subscribe to and read regularly.

Of course, if you’re looking for a Glasgow based company with experience building advanced web apps with Laravel then please get in touch