How to create a custom php page on Drupal 8

In Drupal 7, we can create a custom page using hook_menu(). In Drupal 8, please follow below steps to create your custom page.

  1. Assumed your module is named my_module,append following into my_module.routing.yml located at "/modules/my_module/".
     
    my_module.custom:
      path: 'custom_path'
      defaults:
        _controller: '\Drupal\my_module\Controller\customPageController::getPage'
        _title: 'Page title'
      requirements:
       _permission: 'access content'
    • my_module.custom: You can customize this name. This route name can be used for the page redirection.
    • path: The path for accessing to this page via browser.
    • _controller: The location of your controller (It will be created on the new step) .
    •  _title: The title of the page.
    • _permission: Normally, you could set it to 'access content'.
  2. Create customPageController.php at "/modules/my_module/src/Controller/". Add the following code into this file.
    <?php
    namespace Drupal\my_module\Controller;
    
    use Symfony\Component\HttpFoundation\Request;
    use Drupal\Core\Controller\ControllerBase;
    
    class customPageController extends ControllerBase{
      /**
       * Returns a simple page.
       *
       * @return array
       *   A simple renderable array.
       */
    
       public function getPage(Request $request) {
            $element = array(
              '#markup' => t('This is my content')
            );
             return $element;
        }
    }
  3. Finally, you can clear the cache and visit this page via the line http://{yourdomain}/custom_path.