WordPress has a function to get the page or post id inside a post or page. Using get_the_id() function, you can retrieve the post or page id even outside the loop as long as you are inside a single page or post.

However, if you are looking for a bit different approach or you find hard to make retrieve the post or page id using the function mentioned, there is a different approach which uses the permalink to extract the page or post id.

WordPress has a function called url_to_postid() which accept 1 argument which is the page, post, or attachment url and returns the id of the page, post, or attachment.

However, this function will only work If rewrite rules is enable in your website.

Example:

<?php
$url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$page_ID = url_to_postid($url[0]);
?>

This page id is <?php echo $page_ID; /* print "This page id is 23" */ ?>;