How to get current URL - Drupal 8 & 9
Every now and then you may find yourself needing to collect the URL of the current page. I haven't seen Drupal provide a way to do that in one go.
But there is a combination of codes that can help you. Let me show you what I mean.
$host = \Drupal::request()->getSchemeAndHttpHost();
This will output "https://example.com" - important to note there is no trailing slash!
$page = \Drupal::request()->getRequestUri();
This will output "/tutorial/another-drupal-thing-learn/again"
All together now:
$full_url = $host . '' . $page;
This will output https://example.com/tutorial/another-drupal-thing-learn/again
Done!