Skip to content

Instantly share code, notes, and snippets.

@guibranco
Created March 14, 2021 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibranco/410f74d6b6da60b69578c3ec468f2a69 to your computer and use it in GitHub Desktop.
Save guibranco/410f74d6b6da60b69578c3ec468f2a69 to your computer and use it in GitHub Desktop.
Proteger imagem com PHP - Facebook - Desenvolvimento Web - https://www.facebook.com/groups/desenvolvimentoweb/permalink/3990689637656112/
<?php
$isAuthorized = isUserAuthorized(); //sua lógica para validar se o usuário está ou não autorizado.
if(!$isAuthorized)
die(header("Location: index.php")); //se o usuário não tiver autorização, redireciona ele pra index e encerra o script com die()
// aqui ele tá autorizado, então bora servir a imagem...
$image = $_GET["image"]; //supondo que a URL foi acessada via: showImage.php?image=foto123.png
$isValidImage = preg_match("#\.(jpg|jpeg|gif|png)$# i", $image);
if(!$isValidImage)
die(header("Location: index.php")); //validação básica para garantir que o usuário espertinho não tentou acessar um .php da vida.
$filepath = "/images/usuarios/".$image; //supondo que as imagens estejam a partir do root, na pasta images/usuarios/, use o seu path de acorod.
if(!file_exists($filepath))
die(header("Location: index.php")); //validação que a imagem existe na pasta de fotos dos usuários
$pathPart = pathinfo($filepath);
//pegamos a extensão do arquivo para informar ao navegador qual tipo de arquivo esta sendo servido
switch(strtolower($pathPart['extension']))
{
case "gif":
header("Content-type: image/gif");
break;
case "jpg":
case "jpeg":
header("Content-type: image/jpeg");
break;
case "png":
header("Content-type: image/png");
break;
case "bmp":
header("Content-type: image/bmp");
break;
}
header('Content-Length: ' . filesize($filepath)); //tamanho da imagem pro navegador saber o que tem que baixar
readfile($filepath); //serve a imagem
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment