Reputation: 443
I'm working on a crud where I can upload student data including the profile photo.
My problem, is upon update, since not all fields are required. I'm receiving error saying Undefined index: file
which is this line $_FILES["file"]["name"]
.
So what I'm trying to achieve is load the image to the file upload field.
I can only display the file name but my problem is binding the image from its source to the field.
PHP
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
HTML
<div class="form-group">
<label>Upload Image: </label>
<div class="input-group image-preview">
<input type="text" class="form-control image-preview-filename" disabled="disabled"> <!-- don't give a name === doesn't send on POST/GET -->
<span class="input-group-btn">
<!-- image-preview-clear button -->
<button type="button" class="btn btn-default image-preview-clear" style="display:none;">
<span class="glyphicon glyphicon-remove"></span> Clear
</button>
<!-- image-preview-input -->
<div class="btn btn-default image-preview-input">
<span class="glyphicon glyphicon-folder-open"></span>
<span class="image-preview-input-title">Browse</span>
<input type="file" accept="image/png, image/jpeg, image/gif" name="input-file-preview" id="uploadimage" /> <!-- rename it -->
</div>
</span>
</div>
</div>
Upvotes: 1
Views: 54
Reputation: 47567
You need to read this carefully.
Basically you are checking $_FILES["fileToUpload"]["name"]
, but in your HTML code you are referring to name="input-file-preview"
So your $_FILES
index should be input-file-preview
.
E.g. $_FILES['input-file-preview']
;
Also, it is always a good idea to verify an array index exists before you use it.
E.g.
if(isset($_POST["submit"]) && array_key_exists($_FILES['fileToUpload']) ) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
Upvotes: 1