Question

I'm writing custom.php file to my moodle and i have question.

  1. How to check if user is logged in and how to check his login ?

    2.How to make my page avaliable only for logged students ?

Some Code i already wrote:

// The number of lines in front of config file determine the // hierarchy of files. 
require_once(dirname(dirname(__FILE__)).'/../../config.php');    

$PAGE->set_context(get_system_context());
$PAGE->set_pagelayout('admin');
$PAGE->set_title("Badanie Umiejętności - eszkolenia24.pl");
$PAGE->set_heading("Blank page");
$PAGE->set_url($CFG->wwwroot.'/blank_page.php');

echo $OUTPUT->header();
?>

<h1>Some Text</h1>

<div class="row">
  <div class="col-lg-12 col-md-12 col-xs-12 col-sm-12">
</div>

<?php
echo $OUTPUT->footer();
?>

Answer 1: require_login();

Was it helpful?

Solution

require_login();

This will redirect the user to the login page, if they're not already logged in ('guest' is considered logged-in for these purposes).

You will then want to check the user has permission to access the page, by defining a suitable capability (in YOURPLUGIN/db/access.php ) and checking it via:

require_capability('PLUGINTYPE/PLUGINNAME:CAPABILITYNAME', context_system::instance());

Assuming the 'guest' user doesn't have that capability, this will prevent them from accessing your page.

As an alternative, you can write:

is_siteadmin() || die('Site admins only');

(but that only works if you want to restrict the page to site admins only).

You can also access further information about the logged in user via the $USER global.

A couple of other corrections to your code - use 'context_system::instance()', not 'get_system_context()'. It is better to write:

new moodle_url('/blank_page.php')

instead of

$CFG->wwwroot.'/blank_page.php'

Also, leave out the final '?>', as that will help to prevent whitespace problems.

OTHER TIPS

Just to add to Davosmith

For custom code, create a structure like this

http://docs.moodle.org/dev/Local_plugins#Standard_plugin_features:

In local/pluginname/db/access.php add the new capabilities

http://docs.moodle.org/dev/Access_API#How_to_define_new_capabilities_in_plugins

You will also need a /local/pluginname/version.php so the capabilities are installed

http://docs.moodle.org/dev/version.php

And update the /local/pluginname/lang/en/local_pluginname.php with the names of the capabilities.

Also try to use html_writer::tag() rather than using tags directly.

http://docs.moodle.org/dev/Output_API#HTML_low-level_components

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top