buck1112
buck1112

Reputation: 502

Pagination Links Not Directing Properly

I'm new to PHP, and I'm developing a PHP plugin for CraftCMS.
On my local dev machine, this code was working; however, on the server, the pagination links are not directing properly.

This is a plugin which imports an XML feed and paginates the results.

For example, when using 'PHP_SELF' in the code, the link redirects to the index page, and when using 'REQUEST_URI,' the link works correctly the first time, yet is appended with each successive URI.

I was wondering if there would be a work around or better method for correcting this problem?

This version takes you back to the home page: code:

echo '<a href="'.$_SERVER['PHP_SELF'].'?page=1#rss" title="First" class="btn">&lt;&lt;</a> <a href="'.$_SERVER['PHP_SELF'].'?page='.( $page - 1 ).'#rss" title="Previous" class="btn prev">&lt;</a> ';

while this version appends the querystring each time: e.g. http://mypage/test?page=1&page=2

code:

echo '<a href="'.$_SERVER['REQUEST_URI'].'?page=1#rss" title="First" class="btn">&lt;&lt;</a> <a href="'.$_SERVER['REQUEST_URI'].'?page='.( $page - 1 ).'#rss" title="Previous" class="btn prev">&lt;</a> ';

Upvotes: 0

Views: 55

Answers (1)

S Raghav
S Raghav

Reputation: 1526

Here is what is happening

The first time you use $_SERVER['REQUEST_URI'] the URL on the address bar (which is the value returned by $_SERVER['REQUEST_URI']) is http://mypage

Now say you click on the "First" button, you get redirected to $_SERVER['REQUEST_URI'].'?page=1#rss' so now your URL on the address bar reads http://mypage?page=1#rss

So now what happens when you click on "First" again? The text ?page=1#rss is appended to the already existing request Uri i.e http://mypage?page=1#rss. So the result is? You guessed it http://mypage/test?page=1#rss&page=1#rss

To avoid this, you need to strip the querystring (the part following the ?) from the request Uri and there exists a wonderful SO answer to help you do just that

So your code should look like

$url=strtok($_SERVER["REQUEST_URI"],'?');
echo '<a href="'.$url.'?page=1#rss" title="First" class="btn">&lt;&lt;</a> <a href="'.$_SERVER['REQUEST_URI'].'?page='.( $page - 1 ).'#rss" title="Previous" class="btn prev">&lt;</a> ';

Upvotes: 1

Related Questions