phppagination

Pagination causes error when going to page 1 other than that it's fine


I have a pagination that is quite old, I have been succesful in getting it to work with php8.1 but I have one error I can not fix, and would like some help if possible please.

The line of code causing the problem is this one.

if ($page == "") { $page = "1"; } else { $page = $page; }
[11-Jun-2024 17:52:48 UTC] PHP Warning:  Undefined variable $page in /home/****/public_html/gallery.php on line 30

I am using .htaccess to make seo friendly urls.

RewriteEngine On
RewriteBase /
RewriteRule ^gallery(.+)/ /gallery/?page=$1

So gallery2/ being page 2 gallery3/ being page 3 etc. All of which work perfectly

My error occurs when I go to page 1 which I want to be just /gallery. I am assuming my error occurs because of the first line of code posted at the top of here since there is no page number so $page would be empty for the first page of the gallery.

So basically I need help with what to do with this line.

if ($page == "") { $page = "1"; } else { $page = $page; }

Thank you in advance


Solution

  • You need to check, if the variable $page is actually defined at the point of evaluation. You can do that with isset(), more specifically here !isset():

    <?php
    
    if (!isset($page) || $page == "") { $page = "1"; } else { $page = $page; }
    
    echo $page;
    

    This will return "1", if $page is not defined and not throwing a warning.

    Fiddle: https://3v4l.org/soYAk