Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding a url shortener function
    primarykey
    data
    text
    <p>I am trying to better understand how a function works. I am not familiar with how the function below works and I was looking for some help and possibly an explanation. I get most of it except one part that uses math functions like floor(). The part that confuses me the most is the do...while loop. How exactly does using $id, floor() and $base convert a long url into a short url? Also, what exactly is it iterating through where you need a do...while loop to do it?</p> <pre><code>$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $base = strlen($chars); // base 62 $site = 'http://short.co'; // Replace with your domain // ...Connect to MySQL server here... function shorten_url($url) { global $chars, $site, $base; $hash = md5($url); $alnum = NULL; // // Check if URL is already exist on db // Otherwise add this URL to table $res = mysql_query("SELECT id FROM urls WHERE url_hash='$hash'"); if (mysql_num_rows($res)) { $row = mysql_fetch_object($res); $id = $row-&gt;id; } else { mysql_query("INSERT INTO urls (url, url_hash) VALUES ('$url', '$hash')"); $id = mysql_insert_id(); } // Convert id to base 62 and decode to alphanumeric do { $alnum = $chars[($id%$base)].$alnum; } while ($id = floor($id/$base)); return "$site/$alnum"; } </code></pre> <p>If someone could provide an explanation without a ton of math jargon...I would appreciate it. Thanks.</p> <p>I got the function from: <a href="http://bsd-noobz.com/blog/how-to-create-url-shortening-service-using-simple-php" rel="nofollow">http://bsd-noobz.com/blog/how-to-create-url-shortening-service-using-simple-php</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload