List of allowed links that the user input should contain

1

In my form, I would like the visitor to be able to enter in any field any URL that is test.com or test2.com (wildcard), for example test.com/loquesea/39292, like a wildcard.

I have the following in PHP:

$allowedsites = array(
'http://test.com/*',
'http://test2.com/*',
);

if(in_array($longlink, $allowedsites)) {
$error = "The URL is in the array!";
}else{
$error = "The URL doesn't exists in the array.";
include ("crear.php");
exit;
}

I have tried without * and with *, it has not worked for me.  It is for a URL shortener restricted to certain pages . Why in bold? Because I'm not looking if the input matches with a single page, but with more than one. Thanks.

    
asked by Hernando Pineda 05.04.2017 в 20:39
source

2 answers

0

Well, I can think of a function like this:

echo check('test.com/wtf'); //url válida
echo check('test.com.mx/wtf'); //url válida
echo check('testddd2.com/wtf'); //url no válida

function check($cadena) //funcion que recibe una cadena
{
  if (strpos($cadena, 'test.com') !== false) //strpos() busca coincidencias de una cadena dada con un valor definido. Este te regresa true o false segun sea el caso
  {
      return 'URL válida';
  }

  else
  {
    if (strpos($cadena, 'test.com.mx') !== false) //anidar la función tantas veces como consideres necesario. O hacer un array de "test" y recorrerlo.
    {
      return 'URL válida';
    }

    else
    {
      if (strpos($cadena, 'test2.com') !== false)
      {
        return 'URL válida';
      }

      else
      {
        return 'URL inválida';
      }
    }
  }
}

The idea you already have, use your ingenuity to adapt it little by little what you need. Nobody will give you the entire answer to your program.

Greetings.

    
answered by 05.04.2017 в 21:02
0

in_array looks for an exact match, if you try to evaluate variations of the string you need regular expressions.

$patron = '/^http:[s]?\/\/test[a-z0-9]*\.com\/[a-z]*$/';
$url = 'http://test.com/';

preg_match($patron, $url);

preg_match returns 1 if the string matches the pattern or 0 if it does not, if you try urls like link or link will return 1 for example.

    
answered by 05.04.2017 в 22:44