Block link in . php

Asked

Viewed 260 times

0

Well, I was doing some tests in the image upload on my site and what I came across was the following, when the user put a link as ".php", ".js", ".html" he could easily make 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>";

}

3 answers

2


You can use regex to verify the 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 the 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 (is in .png), but it would be ignored, since it does not have the extension in the URL.

In this case, just send a request and capture the return of the 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");
}

1

does a validation with regex on front-end and/or back-end, making it impossible to send files with extension other than the desired

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

In the 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

In HTML:

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

I recommend the use both in the back-end and in 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 the validation is easily circumvented, so put in the back-end too.

regex = regular Expression, en en regular expressions

  • Couldn’t give example of the code? because I have no idea what this "Regexp"

  • I edited the answer

1

It is important to check the file mimetype, because there is a type of attack in which vc sends a php file with jpg extension and manages to run it on the server. That’s why IT’S NOT ENOUGH check the file name string according to the other responses they put here.

For this use the class feint.

<?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 to file. Example:

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

Source of code snippet: http://php.net/manual/en/features.file-upload.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.