How can the position of a scrollbar be maintained when reloading a page in PHP?

When reloading a page in PHP, the position of a scrollbar can be maintained by storing the scroll position in a session variable before the page reloads and then using that stored value to set the scroll position after the page reloads. This can be achieved by using JavaScript to capture the scroll position and then passing it to PHP via AJAX or form submission.

<?php
session_start();

if(isset($_POST['scroll_position'])){
    $_SESSION['scroll_position'] = $_POST['scroll_position'];
}

$scroll_position = isset($_SESSION['scroll_position']) ? $_SESSION['scroll_position'] : 0;
?>

<!DOCTYPE html>
<html>
<head>
    <title>Scroll Position Example</title>
</head>
<body>
    <div style="height: 2000px;">
        <!-- Your content here -->
    </div>

    <script>
        window.onload = function(){
            window.scrollTo(0, <?php echo $scroll_position; ?>);
        };

        window.onscroll = function(){
            var scroll_position = window.scrollY;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', window.location.href, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send('scroll_position=' + scroll_position);
        };
    </script>
</body>
</html>