'How to get page context in MOODLE

How do we get the context of the current page opened in moodle i.e., the context could be either system/course/coursecat etc.,

I would appreciate your help



Solution 1:[1]

Really simple :)

$context = $PAGE->context;

And to check the type of context, use the context constants

switch ($context->contextlevel) {
    case CONTEXT_SYSTEM:
        break;
    case CONTEXT_USER:
        break;
    case CONTEXT_COURSECAT:
        break;
    case CONTEXT_COURSE:
        break;
    case CONTEXT_MODULE:
        break;
    case CONTEXT_BLOCK:
        break;
}

Solution 2:[2]

Make sure you have the following set before you call $PAGE:

GLOBAL = $PAGE;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Andi McDonald