Torben
Torben

Reputation: 5494

Handling URLs correctly with PHP

i have the following case within my plugin for wordpress: I have a details page of a database entry which can be accessed like this:

http://localhost:8888/studio/wp-admin/admin.php?page=myplugin-details&id=42

The next would be to add sorting options to this page and i solved it with this code:

The url would be:

http://localhost:8888/studio/wp-admin/admin.php?page=myplugin-details&id=42&orderby=answer&order=asc



<?php
            if (!empty($_GET['orderby'])) {
                $pos = strpos($_SERVER["REQUEST_URI"], 'orderby');
                $url = substr($_SERVER["REQUEST_URI"], 0, $pos-1); 
                if ($_GET['order'] == 'desc') {
                    echo '<th class="sortable desc">';
                    echo '<a href="'.$url.'&orderby=answer&amp;order=asc">';
                } else {
                    echo '<th class="sortable asc">';
                    echo '<a href="'.$url.'&orderby=answer&amp;order=desc">';
                }
            } else {
                echo '<th class="sortable desc">';
                echo '<a href="'.$_SERVER["REQUEST_URI"].'&orderby=answer&amp;order=asc">';
            }
            ?>

This works fine, but do i have to do that URL/REQUEST_URI stuff or is there a solution which is much simpler?

Thanks!

Upvotes: 0

Views: 87

Answers (1)

Ahmad Essam
Ahmad Essam

Reputation: 1104

In my opinion you should not use strpos to extract the URL. Things could get funky if you made changes to your code later on. You could use str_replace instead :

if ($_GET['order'] == 'desc') {
    echo '<th class="sortable desc">';
    echo '<a href="'.str_replace("order=desc", "order=asc", $_SERVER["REQUEST_URI"]).'">';
} else {
    echo '<th class="sortable asc">';
    echo '<a href="'.str_replace("order=asc", "order=desc",$_SERVER["REQUEST_URI"]).'">';
}

Upvotes: 1

Related Questions