How to make image uploads safe.
Posted: Sat Aug 20, 2011 10:06 am
Here is what I use to upload profile pictures to a folder. I know this isn't secure yet. The folder's permission is set to 777 because that is the only way I could make it work.
Let me know what needs to be added/changed to keep hackers away.
Thanks!
Let me know what needs to be added/changed to keep hackers away.
Thanks!
Code: Select all
<?php
session_start();
if(!isset($_SESSION['username'])){header("location: ../index.php"); exit();}
$con = mysql_connect("**","**","**");
mysql_select_db("**", $con);
$username = mysql_real_escape_string($_SESSION['username']);
// get extension
if ($HTTP_POST_FILES['uploadedfile']["type"] == "image/gif") {$ext = ".gif";}
if ($HTTP_POST_FILES['uploadedfile']["type"] == "image/png") {$ext = ".png";}
if ($HTTP_POST_FILES['uploadedfile']["type"] == "image/jpeg") {$ext = ".jpg";}
// validate
if ($HTTP_POST_FILES['uploadedfile']["type"] != "image/gif" && $HTTP_POST_FILES['uploadedfile']["type"] != "image/png" && $HTTP_POST_FILES['uploadedfile']["type"] != "image/jpeg") {$valid = "false"; $errors = $errors . "1";}
if ($HTTP_POST_FILES['uploadedfile']['size'] > 3000000) {$valid = "false"; $errors = $errors . "2";}
// if invalid, go to error page
if ($valid == "false"){
header("location: ../error_pages/upload_picture_error.php?why=$errors");
exit();}
// resize, rename, copy to folder
$path = "../profile_pictures/".$username . $ext;
$file_name = $HTTP_POST_FILES['uploadedfile']['tmp_name'];
copy($file_name, $path);
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($path);
$image->resizeToWidth(100);
$image->save($path);
$picture = $username . $ext;
$result = mysql_query("SELECT * FROM perm WHERE username = '$username'");
while($row = mysql_fetch_array($result))
{$old_picture = $row['picture'];}
// delete old default picture
unlink("../profile_pictures/".$old_picture);
mysql_query("UPDATE perm SET picture = '$picture' WHERE username = '$username'");
echo '<script type="text/javascript">window.location = "../account.php";</script>';
?>