-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions.php
54 lines (43 loc) · 1.49 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
// provide some SQL injection protection by sanitizing any variables
function sanitize($var)
{
$var = trim($var);
$var = htmlspecialchars($var, ENT_QUOTES);
return $var;
}
// function for creating the random string for the unique url
function generate_code()
{
// create the charset for the codes and jumble it all up
$charset = str_shuffle(CHARSET);
$code = substr($charset, 0, URL_LENGTH);
// verify the code is not taken
while (count_urls($code) > 0)
$code = substr($charset, 0, URL_LENGTH);
// return a randomized code of the desired length
return $code;
}
// function to count the total number of short urls saved on the site
function count_urls($code = '')
{
// build the extra query string to seach for a code in the database
if ($code != '')
$extra_query = " WHERE code='$code'";
else
$extra_query = "";
// connect to the database
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// count ow many total shortened urls have been made in the database and return it
$count = (int) mysqli_num_rows(mysqli_query($conn, "SELECT * FROM short_links " . $extra_query));
return $count;
}
// function to perform all the validation needed for the urls provided
function validate_url($url)
{
// make sure the user isn't trying to shorten one of our urls
if (substr($url, 0, strlen(SITE_ADDR)) != SITE_ADDR) {
return filter_var($url, FILTER_VALIDATE_URL);
} else
return false;
}