Block link in .php

0

Well, I was doing some testing on image upload on my site and what I came across was the following, when the user put a link like " .php ", " .js .html "it can easily do a iplogger with this, I want to block the links with" .php ", etc ... I just want to allow .gif , .png and .jpg

Follow the code:

<input type="text" name="img" class="listcc" placeholder="URL DA IMAGEM"/><br/><br/><br/>

$img = trim($_POST["img"]);

if ($img != null) {
  mysql_query("UPDATE usuarios SET img='$img' WHERE id='$id'") or die(mysql_error());
  echo "<script language='javascript' type='text/javascript'>alert('Imagem de perfil atualizada com sucesso');</script>";

}
    
asked by anonymous 02.03.2018 / 22:20

3 answers

2

You can use regex to check URL .

if ( preg_match("/\.(?:gif|png|jpe?g)(?:\?.*)?$/", $img) ) {
    die("É uma imagem válida. Pode atualizar no seu banco de dados");
} else {
    die("Ops! Não me parece ser uma imagem.");
}

Explanation of Regex:

\.(?:gif|png|jpe?g)(?:\?.*)?$
└───────┬────────┘ └──┬──┘ └┬┘
        │             │     └─── Captura a última ocorrência
        │             └───────── Remove tudo que há após '?'
        └─────────────────────── Verifique a extensão é 'gif', 'png', 'jpeg' ou 'jpg'

But that may not be enough. If you check https://www.gravatar.com/avatar/a95dfb4f780323740a8ce56633a184ed?s=48&d=identicon&r=PG is a valid image (it is in .png ), but it would be ignored since it does not have the URL extension.

In this case, just send a request and capture the return of content-type , for example:

<?php

$url = 'https://www.gravatar.com/avatar/a95dfb4f780323740a8ce56633a184ed?s=48&d=identicon&r=PG';

ob_start();
/* Instancia o curl */
$ch = curl_init($url);

/* Informa que deseja seguir os redirecionamento */
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

/* Desabilita a verificação do SSL */
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

/* Executaa requisição */
curl_exec($ch);

/* Captura o Content-Type retornado */
$i = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

/* Fecha a coenxão */
curl_close($ch);
ob_end_clean();


/* Define os mimetypes permitidos */
$mimeAllowed = [
    'image/png',
    'image/jpeg',
    'image/gif',
];

/* Verifica se o mimetype retornado, consta na variável acima. */
if (in_array($i, $mimeAllowed)) {
    mysql_query("UPDATE usuarios SET img='$url' WHERE id='$id'") or die(mysql_error());
} else {
    die("Error");
}
    
02.03.2018 / 22:56
1

In PHP:

preg_match("[a-zA-Z0-9-_\.]+\.(jpg|gif|png)", "exemplo/minha_imagem.png")
//Retorna TRUE se for válido ou FALSE se for inválido

No JS:

"exemplo/minha_imagem.png".match("[a-zA-Z0-9-_\.]+\.(jpg|gif|png)")
//Retorna TRUE se for válido ou FALSE se for inválido

No HTML:

pattern="[a-zA-Z0-9-_\.]+\.(jpg|gif|png)"

I recommend using both the backend and the front end, the front end is better for the user since it will not leave the page, also making it faster, but in the front end validation is easily circumvented, so put it on the backend as well.

regex = regular expression, en pt regular expressions

    
02.03.2018 / 22:53
1

It is important to check the mimetype of the file, as there is a type of attack in which you send a php file with jpg extension and can execute it on the server. So NOT ENOUGH check the file name string according to the other answers you put here.

For this use the class finfo .

<?php

$finfo = new finfo(FILEINFO_MIME_TYPE);
if ( array_search(
    $finfo->file($_FILES['teste']['tmp_name']),
    array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
    ), true) == true) {
    mysql_query("UPDATE usuarios SET img='$img' WHERE id='$id'") or die(mysql_error());
    echo "<script language='javascript' type='text/javascript'>alert('Imagem de perfil atualizada com sucesso');</script>";

}

In HTML you need to modify your input type for file . Example:

<form enctype="multipart/form-data" method="POST" action="file.php">
<input type="file" name="teste">
<input type="submit">
</form>

Source code snippet: link

    
02.03.2018 / 22:56