1

At the moment I'm migrating an old site to Drupal. To redirect all old url's to new ones, I made a script that has to be inserted before anything goes off, so in index.php at the top.

   <?php

    include 'custom.php';

    use Drupal\Core\DrupalKernel;
    use Symfony\Component\HttpFoundation\Request;
    etc.etc.

All is fine until an update wipes this out. Could (should?) it be done some other way to preserve this?

0

1 Answer 1

4

If you want to run code before the Drupal kernel is started use a middleware.

Use the drush code generator drush gen middleware and put your code in handle() of the generated middleware class:

MymoduleMiddleware.php

<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * MymoduleMiddleware middleware.
 */
class MymoduleMiddleware implements HttpKernelInterface {

  use StringTranslationTrait;

  /**
   * The kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs the MymoduleMiddleware object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   The decorated kernel.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    if ($request->getClientIp() == '127.0.0.10') {
      return new Response($this->t('Bye!'), 403);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.