Safe Link Arguments


/ Published in: PHP
Save to your folder(s)

Make sure your URL $_GET variables don't get repeated / duplicated when you are creating links / URLs dynamically.


Copy this code and paste it in your HTML
  1. /**
  2. * Usage:
  3. * <?php $url = 'http://www.yourwebsite.com/?page=1&showposts=10'; ?>
  4. * <a href="<?php echo safe_urls($url, 'page', '1'); ?>" title="Page 1">Page 1</a>
  5. * <a href="<?php echo safe_urls($url, 'page', '2'); ?>" title="Page 2">Page 2</a>
  6. * <a href="<?php echo safe_urls($url, 'page', '3'); ?>" title="Page 3">Page 3</a>
  7. *
  8. * <a href="<?php echo safe_urls($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 'page', '3'); ?>" title="Page 3">Page 3</a>
  9. */
  10.  
  11. function safe_urls($url = '', $var = 'page', $value = '1'){
  12.  
  13. if(strpos($url, '?'))
  14. {
  15. if(strpos($url, $var))
  16. {
  17. $i = explode('?', $url);
  18. foreach($i as $arg)
  19. {
  20. $k = explode('&', $arg);
  21. foreach($k as $t)
  22. {
  23. $s = explode('=', $t);
  24. if ($s[0] == $var) $match = $s[0] . '=' . $s[1];
  25. }
  26. }
  27. $url = str_replace($match, $var . '=' . $value, $url);
  28. }
  29. else
  30. {
  31. $url .= '&' . $var . '=' . $value;
  32. }
  33. }
  34. else
  35. {
  36. $url .= '?' . $var . '=' . $value;
  37. }
  38. return $url;
  39. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.