url.class.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. class url {
  3. function __construct() {
  4. global $db_c;
  5. $this->db = $db_c;
  6. }
  7. // 生成短地址
  8. public function set_url($url, $size = 4) {
  9. $id = $this->get_id($url);
  10. if(!$id) {
  11. $id = $this->create_id($url, $size);
  12. $ip = get_ip();
  13. $ua = get_ua();
  14. $this->db->insert('urls', 'id, url, ip, ua', "'$id', '$url', '$ip', '$ua'");
  15. }
  16. $s_url = get_uri() . $id;
  17. return $s_url;
  18. }
  19. // 生成地址 ID
  20. public function create_id($url, $size = 4) {
  21. $md5 = md5($url);
  22. // 随机抽取 MD5 中的字符作为 ID
  23. $id = '';
  24. for($i = 0; $i < $size; $i++) {
  25. $rand_id = rand(0, strlen($md5) - 1);
  26. $id .= $md5[$rand_id];
  27. }
  28. // ID 检测
  29. if($this->has_id($id)) {
  30. return $this->create_id($url, $size);
  31. } else {
  32. return $id;
  33. }
  34. }
  35. // 查询 ID 号
  36. public function get_id($url) {
  37. $result = $this->db->query('urls', "WHERE url = '$url'");
  38. (count($result) > 0) ? $opt = $result[0]['id'] : $opt = false;
  39. return $opt;
  40. }
  41. // 查询目标地址
  42. public function get_url($id) {
  43. $result = $this->db->query('urls', "WHERE id = '$id'");
  44. (count($result) > 0) ? $opt = $result[0]['url'] : $opt = false;
  45. return $opt;
  46. }
  47. // 检测 ID 是否已经存在
  48. public function has_id($id) {
  49. $result = $this->db->query('urls', "WHERE id = '$id'");
  50. (count($result) > 0) ? $opt = true : $opt = false;
  51. return $opt;
  52. }
  53. // 清空短地址
  54. public function clean_urls() {
  55. $del = $this->db->delete('urls');
  56. if($del) return true;
  57. return false;
  58. }
  59. }
  60. ?>