-3
 <input type="url" id="url" class="form-control image_url">

I need to allow users add only links from popular drive sites like google drive or one drive

    $url_allowed = array("https://drive.google.com/", "https://1drv.ms/"); //Add Allowed Website list Here

    if(!$url_allowed){
        echo 'invalid link';
        return;
    }

What is the right method to do that ?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Mohammad
  • 3
  • 4
  • First give the HTML input element a `name` attribute, for example `name="url"`or the data will never be sent to the server by the browser! _I assume there is a `
    ` wrapped around that ``_
    – RiggsFolly Jun 29 '22 at 09:50
  • 3
    Then look up `in_array()` in the [PHP Manual](https://www.php.net/manual/en/function.in-array.php) – RiggsFolly Jun 29 '22 at 09:51
  • It's better to just have the hostname in your array `drive.google.com` etc without the protocol or any trailing slashes. Then you can use [parse_url](https://www.php.net/manual/en/function.parse-url.php) to get the hostname of the URL the user entered and use `in_array()` to see if it exists in the array – M. Eriksson Jun 29 '22 at 09:59
  • @RiggsFolly Thank you ` $url_allowed = array("https://drive.google.com/", "https://1drv.ms/"); //Add Allowed Website list Here ` it just allow this domains only , if i pu a link like `https://drive.google.com/file/d/1-C_W3aFokd5GGA6riBHA8LXu_N1w0LNk/view?usp=sharing` but the system reject it – Mohammad Jun 29 '22 at 10:42

1 Answers1

0

Loop all possible links and check if provided link starts with it:

$whitelist = ['https://drive.google.com/', ...];
$link = $_POST['link'] ?? null;
$isValid = false;

if (empty($link)) {
    throw new Exception('Missing link');
}

foreach ($whitelist as $whitelistLink) {
    if (str_starts_with($link, $whitelistLink)) {
        $isValid = true;
 
        break;
    }
}

if (!$isValid) {
    throw new Exception('Invalid link');
}

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • Thank you , it is for php 8 , i am using version 7.3 – Mohammad Jun 29 '22 at 10:44
  • @Mohammad the only thing that is PHP 8 here, is `str_starts_with`. The manual has a replacement for lower PHP versions in the user comments already, and typing something like "str_starts_with for php 7" into Google, could also have lead you to https://stackoverflow.com/q/2790899/1427878 in no time. – CBroe Jun 29 '22 at 11:16
  • @Mohammad Replace `str_starts_with` with `str_pos($link, $whitelistLink) === 0` – Justinas Jun 29 '22 at 11:21