Marco Johannesen
Marco Johannesen

Reputation: 13134

PHP URL Shortener error

I have this PHP code which is supposed to increase a URL shortener mask on each new entry. My problem is that it dosen't append a new char when it hits the last one (z). (I know incrementing is a safety issue since you can guess earlier entries, but this is not a problem in this instance)

If i add 00, it can figure out 01 and so on... but is there a simple fix to why it won't do it on its own?

(The param is the last entry)

<?php

class shortener
{

    public function ShortURL($str = null)
    {
        if (!is_null($str))
        {
            for($i = (strlen($str) - 1);$i >= 0;$i--)
            {
                if($str[$i] != 'Z')
                {
                    $str[$i] = $this->_increase($str[$i]);
                    #var_dump($str[$i]);
                    break;
                }
                else
                {
                    $str[$i] = '0';
                    if($i == 0)
                    {
                        $str = '0'.$str;
                    }
                }
            }
            return $str;
        }
        else {
            return '0';
        }
    }

    private function _increase($letter)
    {
        //Lowercase: 97 - 122
        //Uppercase: 65 - 90
        //  0 - 9  : 48 - 57
        $ord = ord($letter);
        if($ord == 122)
        {
            $ord = 65;
        }
        elseif ($ord == 57)
        {
            $ord = 97;
        }
        else
        {
            $ord++;
        }
        return chr($ord);
    }
}

?>

Upvotes: 2

Views: 124

Answers (1)

dave
dave

Reputation: 64657

Effectively, all you are doing is encoding a number into Base62. So if we take the string, decode it into base 10, increment it, and reencode it into Base62, it will be much easier to know what we are doing, and the length of the string will take care of itself.

class shortener
{
  public function ShortURL($str = null)
  {
    if ($str==null) return 0;
    $int_val = $this->toBase10($str);
    $int_val++;
    return $this->toBase62($int_val);
  }

  public function toBase62($num, $b=62) {
    $base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $r = $num  % $b ;
    $res = $base[$r];
    $q = floor($num/$b);
    while ($q) {
      $r = $q % $b;
      $q =floor($q/$b);
      $res = $base[$r].$res;
    }
    return $res;
  }

  function toBase10( $num, $b=62) {
    $base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $limit = strlen($num);
    $res=strpos($base,$num[0]);
    for($i=1;$i<$limit;$i++) {
      $res = $b * $res + strpos($base,$num[$i]);
    }
    return $res;
  }
}

Upvotes: 3

Related Questions