currentPageStrict (function)

Last updated: Mon, Apr 17, 2023 7:03 am
Return to Knowledgebase

Purpose

Only return a page ID if the page is marked as "active" in the database. This can be useful in cases where you only want to allow access to certain pages.

Location

users/helpers/us_helpers.php

Parameters

This function does not take any arguments

Returns

Data Type Description of Returned Data
string Returns the name of the current page as a string.

Further Documentation:

The currentPageStrict() function is another custom function in the UserSpice PHP framework, which is used to retrieve the ID of the current page based on the URI. The difference between currentPageStrict() and currentPageId() is that currentPageStrict() will only return a page ID if the page is marked as "active" in the database. This can be useful in cases where you only want to allow access to certain pages.

Here's the function code:


function currentPageStrict($uri) {
global $db;
$us_url_root = Config::get('URL_ROOT');

$path = str_replace($us_url_root, '', $uri);
if (strlen($path) == 0) {
$path = '/';
}

$query = $db->query("SELECT id FROM pages WHERE page = ? AND private = 0 AND status = 1", [$path]);
if ($query->count() > 0) {
return $query->first()->id;
} else {
return false;
}
}

To use this function, you simply call it with the current URI as its parameter, like so:


// Include UserSpice
require_once 'users/init.php';

// Get the ID of the current page (only if it's active)
$pageId = currentPageStrict($_SERVER['REQUEST_URI']);

// Check if page ID was found
if ($pageId !== false) {
// Use the page ID for something
echo "The ID of the current active page is: " . $pageId;
} else {
// Redirect to error page or handle error
echo "Sorry, the requested page is not available.";
}
?>

In this example, we first include the UserSpice framework by calling the init.php file. Then, we call the currentPageStrict() function with the current URI, which is retrieved from the $_SERVER['REQUEST_URI'] variable. The function will only return a page ID if the page is marked as "active" in the database. If an active page is found, we use its ID for something, such as displaying it on the page. If the page is not active, we handle the error by redirecting the user to an error page or displaying a message.