0

I need to check input value before save in db table.

I have a domains, and I want to check inserted link in url field. If url use one of domains from list validation true else false.

Ex.

$urls = array('domain.com','domain2.com','domain3.com');

In url field will put link e.x (domain2.com/priflie/1234 OR domain.com/profile/4321)

I try with this, but no work

if (in_array($url, $urls)) 
{
// error code here
 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kaja
  • 13
  • 4

1 Answers1

2

You need to parse the domain from the URL. See this answer for an explanation - Parsing Domain From URL In PHP

<?php
$url = 'http://example.com/index.html';
$parse = parse_url($url);
$domain = $parse['host'];

$domains = array('example.com','example2.com','example3.com');

if (in_array($domain, $domains)) {
    ...
}

EDIT - Not 100% certain on the requirements here but sounds like you want a function that returns a boolean.

Need only to check if url is with domain from list or not. If yes write in db if not return error

/**
 * Returns a boolean indicating if the given URL is in a list of valid domains.
 * @param string $url
 * @return bool
 */
function validDomain($url)
{
    $parse = parse_url($url);
    $domain = $parse['host'];

    $validDomains = array('example.com', 'example2.com', 'example3.com');

    return in_array($domain, $validDomains);
}

if (validDomain('http://example.com/index.html')) {
    // Insert into DB.
} else {
    // Handle your error.
}
waterloomatt
  • 3,662
  • 1
  • 19
  • 25
  • If the question is a duplicate, it should be marked as one instead of being answered again. – M. Eriksson Aug 23 '19 at 13:40
  • True, but this answer provides a bit more detail for OP. – waterloomatt Aug 23 '19 at 13:41
  • Not really. The only thing you've added to the original answer is the `$domains` and `if (in_array(...))`, which the OP already have. This is definitely close enough to be marked as a dupe. – M. Eriksson Aug 23 '19 at 13:41
  • Need only to check if url is with domain from list or not. If yes write in db if not return error – Kaja Aug 23 '19 at 13:46
  • So, are you looking for a function that returns true or false? Will you give the function a URL to check? – waterloomatt Aug 23 '19 at 13:48
  • @Kaja - That's exactly what this does (except from the db-code). If the domain exists in the list, the if-statement would evaluate as `true` so put your db-code in there. – M. Eriksson Aug 23 '19 at 13:59
  • Not work, need just get error if url do not with valid domain from list. If yes in db write the url, if not get error. – Kaja Aug 23 '19 at 19:18