Files
selima-perl/lib/php/monica/addget.inc.php
2026-03-10 21:31:43 +08:00

106 lines
2.9 KiB
PHP

<?php
// File name: addget.inc.php
// Description: PHP subroutines to add a get argument to an url
// Date: 2001-02-13
// Author: imacat <imacat@pristine.com.tw>
// Copyright: Copyright (C) 2001-2007 Pristine Communications
// Constant symbols
if (!defined("DUP_OK")) {
define("DUP_OK", true);
define("DUP_NO", false);
}
// add_get_arg: Add a get argument to the end of an url
function add_get_arg($cururl, $name, $value, $dup_ok = DUP_NO)
{
// Encode the name and value first
$name = urlencode($name);
$value = urlencode($value);
$pos = strpos($cururl, "?");
// No current arguments were appended yet
if ($pos === false) {
return "$cururl?$name=$value";
}
// It's OK to have duplicated same arguments
if ($dup_ok) {
return "$cururl&$name=$value";
}
// Have arguments already. We need to check if there is already
// a duplicated one and replace it if exists.
// Split the arguments
$script = substr($cururl, 0, $pos);
$argslist = substr($cururl, $pos+1);
$oldargs = explode("&", $argslist);
$newargs = array();
$l = strlen("$name=");
$found = false;
foreach ($oldargs as $arg) {
// Replace existing arguments
if (substr($arg, 0, $l) == "$name=") {
// Replace the first one and discard the rest
if (!$found) {
$newargs[] = "$name=$value";
$found = true;
}
continue;
}
$newargs[] = $arg;
}
// Add it if not found at last
if (!$found) {
$newargs[] = "$name=$value";
}
return "$script?" . implode("&", $newargs);
}
// rem_get_arg: Remove a get argument from the end of an url
function rem_get_arg($cururl, $names)
{
// If $names is not an array, set to an one-element array
if (!is_array($names)) {
$names = array($names);
}
// Parse the names
$lens = array();
for ($i = 0; $i < count($names); $i++) {
// Encode the name first
$names[$i] = urlencode($names[$i]);
// Save its length
$lens[$names[$i]] = strlen($names[$i] . "=");
}
$pos = strpos($cururl, "?");
// No current arguments are appended yet
if ($pos === false) {
return $cururl;
}
// Have arguments already. We need to check if there is already
// a duplicated one and remove it if exists.
// Split the arguments
$script = substr($cururl, 0, $pos);
$argslist = substr($cururl, $pos+1);
$oldargs = explode("&", $argslist);
$newargs = array();
foreach ($oldargs as $arg) {
// Skip found arguments
foreach ($names as $name) {
if (substr($arg, 0, $lens[$name]) == "$name=") {
continue 2;
}
}
$newargs[] = $arg;
}
// No arguments left
if (count($newargs) == 0) {
return $script;
}
return "$script?" . implode("&", $newargs);
}
?>