Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Auto pull for Yii2
namespace app\controllers;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
* Class WebhookController
* Runs git pull & composer install & yii migrate after push on main repo.
* @package app\controllers
* @author CyanoFresh <>
class WebhookController extends Controller
* @inheritdoc
public $enableCsrfValidation = false;
* @var string Secret field on GitHub
public $secret = '917a34072663f9c8beea3b45e8f129c5';
* @var array of commands to be executed
public $commands = [
'cd .. && /usr/bin/git pull 2>&1',
'/usr/bin/php ../yii migrate --interactive=0 2>&1',
public function actionIndex()
$requestSignature = Yii::$app->request->headers->get('x-hub-signature');
$hash = hash_hmac('sha1', Yii::$app->request->rawBody, $this->secret);
$actualSignature = 'sha1=' . $hash;
if ($requestSignature !== $actualSignature) {
throw new BadRequestHttpException('Wrong signature');
foreach ($this->commands as $command) {
echo 'Executing "' . $command . "\":\n\n";
echo shell_exec($command);
echo "\n\n";
  1. Generate ssh keys for www-data:
sudo mkdir /var/www/.ssh
sudo chown -R www-data /var/www/.ssh
sudo -u www-data ssh-keygen -t rsa
  1. Add that ssh key to the Deploy keys for your account or repo
  2. Put this WebhookController into your app and fill the secret with random data
  3. Create Webhook, put secret from controller into the Secret field. URL has to be like this:
  1. Add access to your repo for www-data user:
chown -R www-data /var/www/yourrepo/

All done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment