gareth power gareth power - 3 months ago 7
MySQL Question

Why won't my image files upload in PHP?

I want my users to be able to upload images to their account (my MySQL database). However, when I try to encode it and upload it, it appears that the file was never uploaded and is empty. I have checked the maximum upload size etc. in my PHP settings. Thanks in advance!!

$data = "";
if(isset($_FILES["up"])) {
$data = file_get_contents($_FILES['up']['tmp_name']);
$data = base64_encode($data);
$data = $connection->real_escape_string($data);
} else {
echo '<div style="position:absolute;height:100px;top:0px;left:0px;
<font style="color:#BB0000;font-size:2.2vw;">'.$_FILES['up']['error'].'</font>

My HTML is: (And the form submits correctly)

<input type="file" accept=".jpg,.png,.jpeg" name="up" id="up"/>


Suggestion: store the images in a directory.

why not DB you ask?

  1. read/write to a DB is always slower than a filesystem
  2. your DB backups will become more time consuming

so, here is my solution.

STEP 1: create a directory userPhotos

STEP 2: create a form

<form action="upload.php" method="post" enctype="multipart/form-data">
 Select your profile picture:
 <input type="file" name="fileToUpload" id="fileToUpload">
 <input type="Upload" value="Upload Image" name="submit">

STEP 3: create a file called upload.php which handles file uploads.

$target_dir = "userPhotos/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$newfilename = ;//assign unique user ID
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    if (move_uploaded_file($_FILES["fileToUpload"][$newfilename.$imageFileType], $target_file)) {
      echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";$uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
 store the path of image in DB as "/userPhotos/".$newfilename
 echo "uploaded photo : <img src='userphotos/".$newfilename."'">
//to display the image fetch the path using user ID as put it in src of img tag. 

Let me know if anyone has a better solution. thanks and Good luck.