Using Composer in shared hosts with allow_url_fopen off.

2 minutes

(AKA Using composer on hosts where one may not have root privileges).

Due to the nature of the servers used by a few clients, I found myself scratching my head on how best to use Composer on these shared hosts. I hate having to require files from all over the place, it just rubs me the wrong way. Some projects just don’t lend themselves to a full blown MVC solution, and for those, a relatively quick way to get up and running is Composer. However, due to the restrictions placed by shared hosts, PHP might not be compiled with the allow_url_fopen=on. That causes an issue with installing and using composer.

Here’s a quick way to get started for such hosts. This is assuming that you have access to the server via SSH.

Install Composer in the project folder via the terminal, while SSH’d into the remote server (to pull in dependencies and for autoloading components)

curl -sS https://getcomposer.org/installer | php -d allow_url_fopen=on

Create a composer.json file within the root. Initialize it as an empty JSON file with

{

}

Run composer install via the terminal.

php -d allow_url_fopen=on composer.phar  install

Make edits to the composer.json file.

{
    "autoload":{
        "psr-4":{
            "Acme\\": "src"
        }
    }
}

Make the server re-read the composer.json file by executing the following in terminal. Check the vendors directory to see whether the namespace is pointing to the right directory for the source.

php composer.phar dump-autoload

Confirm that it works by pulling in the autoload.php and prefixing all the class instantiations with the namespace.

require ‘vendor/autoload.php’;
use Acme\User;
$user = new User();

And Bob’s your uncle. That went well right? If not, and you are getting the dreaded “Class not found” error, most likely you didn’t name your class file, exactly like your class name.

class User
{

}

Needs to be in User.php. Not user.php or uSer.php.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.