I am trying to create an automatic deployment for a Symfony 2 project. Part of this deployment process should be the download and installation of Composer (http://getcomposer.org).
The instructions for installing Composer differ between Windows and Linux but this command seems to work on both systems: php -r "readfile('https://getcomposer.org/installer');" | php
Basically, what this does is download a PHP script and then run it to install composer. I wanted to create my own PHP script because I wanted to avoid creating different shell scripts (.bat and .sh) for different operating systems.
My very simple PHP script looks like this:
<?php
$installer = readfile('https://getcomposer.org/installer');
eval($installer);
However, when calling this script I always get an error:
PHP Parse error: syntax error, unexpected end of file in C:\Users\chrisandomproject\getcomposer.php(4) : eval()'d code on line 1 Parse error: syntax error, unexpected end of file in C:\Users\chrisandomproject\getcomposer.php(4) : eval()'d code on line 1
It seems the script delivered by the composer server can not be executed via eval().
What other options do I have?
Instead of relying on a shell_exec
as suggested by Polak I chose to execute the downloaded installer file with include
. This has the advantage that we do not need to know the path to the PHP executable and don't rely on the PHP executable being in the path.
Here is my full download and install script:
<?php
$installerFilename = "composer-installer.php";
$installer = file_get_contents('https://getcomposer.org/installer');
file_put_contents($installerFilename, $installer);
include($installerFilename);
Note that this unfortunately means we have no way of removing our created file because the included code uses exit
. This means we can not execute some more of our own code after including the composer installer.
You could use file_get_contents to download installer, write it in a file installer.php, and then something like:
shell_exec('php installer.php');
Just make sure you are able to execute "php" via cmd (environment variables issue) or find a way to detect php installation folder to replace php by the correct path.
Most of the credit goes to Chris. I just ironed out a few things. Firstly $argv needs to be set and also you can do a find and replace to make sure the script doesn't exit before executing your own code.
function install($file){
$argv = array(
// '--install-dir=../',
// '--filename=composer.phar',
// '--version=1.0.0-alpha8'
);
include_once($file);
}
$installerFilename = "composer-installer.php";
$composer_installer_content = file_get_contents('https://getcomposer.org/installer');
$find = array('#!/usr/bin/env php', 'exit(','print');
$replace = array('', 'return(','//print');
$new_composer_installer_content = str_replace($find,$replace, $composer_installer_content);
file_put_contents($installerFilename, $new_composer_installer_content);
$return = install($installerFilename);