'Image File Path Not getting Saved In Database
I am trying to save an image file when uploaded by the user but I am not able to save it in the desired location
<div class="container-fluid">
<form action="" id="product-form">
<input type="hidden" name ="id" value="<?php echo isset($id) ? $id : '' ?>">
<input type="hidden" name ="vendor_id" value="<?= $_settings->userdata('id') ?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input name="name" id="name" type="text"class="form-control form-control-sm form-control-border" value="<?php echo isset($name) ? $name : ''; ?>" required>
</div>
<div class="form-group">
<label for="category_id" class="control-label">Category</label>
<select type="text" id="category_id" name="category_id" class="form-control form-control-sm form-control-border select2" required>
<option value="" disabled <?= !isset($category_id) ? 'selected' : "" ?>></option>
<?php
$categories = $conn->query("SELECT * FROM `category_list` where delete_flag = 0 and `status` = 1 and vendor_id= '{$_settings->userdata('id')}' ".(isset($category_id) ? " or id = '{$category_id}' " : '')." order by `name` asc ");
while($row = $categories->fetch_assoc()):
?>
<option value="<?= $row['id'] ?>" <?= isset($category_id) && $category_id == $row['id'] ? 'selected': '' ?>><?= $row['name'] ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<textarea name="description" id="description" rows="4"class="form-control form-control-sm rounded-0 summernote" required><?php echo isset($description) ? html_entity_decode($description) : ''; ?></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="price" class="control-label">Cost</label>
<input name="price" id="price" type="number" step="any" class="form-control form-control-sm form-control-border" value="<?php echo isset($price) ? $price : ''; ?>" required>
</div>
<div class="form-group">
<label for="logo" class="control-label">Product Image</label>
<input type="file" id="logo" name="img" class="form-control form-control-sm form-control-border" onchange="displayImg(this,$(this))" accept="image/png, image/jpeg" <?= !isset($id) ? 'required' : '' ?>>
</div>
<div class="form-group col-md-6 text-center">
<img src="<?= validate_image(isset($image_path) ? $image_path : "") ?>" alt="Product Image" id="cimg" class="border border-gray img-thumbnail">
</div>
<div class="form-group">
<label for="status" class="control-label">Status</label>
<select name="status" id="status" class="custom-select selevt" required>
<option value="1" <?php echo isset($status) && $status == 1 ? 'selected' : '' ?>>Active</option>
<option value="0" <?php echo isset($status) && $status == 0 ? 'selected' : '' ?>>Inactive</option>
</select>
</div>
</div>
</div>
</form>
</div>
PHP Script
if(isset($_FILES['img']) && $_FILES['img']['tmp_name'] != ''){
$fname = 'uploads/logo-'.(time()).'.png';
$dir_path =base_app. $fname;
$upload = $_FILES['img']['tmp_name'];
$type = mime_content_type($upload);
$allowed = array('image/png','image/jpeg');
if(!in_array($type,$allowed)){
$resp['msg'].=" But Image failed to upload due to invalid file type.";
}else{
$new_height = 200;
$new_width = 200;
list($width, $height) = getimagesize($upload);
$t_image = imagecreatetruecolor($new_width, $new_height);
imagealphablending( $t_image, false );
imagesavealpha( $t_image, true );
$gdImg = ($type == 'image/png')? imagecreatefrompng($upload) : imagecreatefromjpeg($upload);
imagecopyresampled($t_image, $gdImg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if($gdImg){
if(is_file($dir_path))
unlink($dir_path);
$uploaded_img = imagepng($t_image,$dir_path);
imagedestroy($gdImg);
imagedestroy($t_image);
}else{
$resp['msg'].=" But Image failed to upload due to unkown reason.";
}
}
if(isset($uploaded_img) && $uploaded_img == true){
if(isset($_SESSION['system_info']['logo'])){
$qry = $this->conn->query("UPDATE system_info set meta_value = '{$fname}' where meta_field = 'logo' ");
if(is_file(base_app.$_SESSION['system_info']['logo'])) unlink(base_app.$_SESSION['system_info']['logo']);
}else{
$qry = $this->conn->query("INSERT into system_info set meta_value = '{$fname}',meta_field = 'logo' ");
}
unset($uploaded_img);
}
}
I tried to save all the data given by the user to the database all the other details are getting saved successfully but there are some error in the img file upload part
Solution 1:[1]
this is a simple method to upload a file to the server. observe it and create your own solution. cheers!!
index.php
<body>
<form id="formData" enctype="multipart/form-data">
<label for="myFile">Select a file:</label>
<input type="file" id="myFile" name="myFile">
<button type="submit" id="formDataSubmit">Upload</button>
</form>
<script>
$("#formData").submit(function(event) {
FormSubmit();
event.preventDefault(); //blocking default submit method
});
function FormSubmit() {
var data = new FormData(document.getElementById("formData")); //always use form Id
$.ajax({
type: "POST",
url: "test.php",
data: data,
dataType: "JSON",
contentType: false, //Required
cache: false, //Required
processData: false, //Required
beforeSend: function() {
// Your functions need to run before form submit
},
success: function(feedback) {
// Your functions need to run After form submit successfully
console.log(feedback.msg); // log "msg" coming after running the test.php file
},
error: function(error) {
console.log(error); //log Request Errors
},
});
}
</script>
</body>
test.php
include_once '../classes/Database.php'; //Link your Database connection Here
if (is_uploaded_file($_FILES['myFile']['tmp_name'])) { // Checking file selected or not
$targetDir = "../app/assets/img/uploads/"; // File upload path
$temp = explode(".", $_FILES["myFile"]["name"]);
$newFileName = 'newFileName.' . end($temp); // Renaming your File ( it will be upload to server like "newFileName.png" )
$targetFilePath = $targetDir . $newFileName; // File path : ../app/assets/img/uploads/newFileName.png
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
//Allow certain file formats
$allowTypes = array('jpg', 'png', 'jpeg');
//Checking if you are uploading allowed types?
if (in_array($fileType, $allowTypes)) {
// Upload file to server
if (move_uploaded_file($_FILES["ps_news_cr_img_name"]["tmp_name"], $targetFilePath)) {
$conn = Database::mysqliConnectDB(); //call to your database connection
$insert = $conn->query("INSERT INTO test (DBfileNameCol) VALUES('" . $newFileName . "');");
if ($insert) {
$statusMsg = "Upload Success.";
} else {
$statusMsg = "Upload failed, please try again.";
}
} else {
$statusMsg = "File Not uploaded because of error #" . $_FILES["myFile"]["error"];
}
} else {
$statusMsg = "This File Type not allowed.";
}
echo json_encode(['msg' => $statusMsg]); // Returning "msg" to the AJAX Request
} else {
$statusMsg = "Please select a file to upload";
echo json_encode(['msg' => $statusMsg]); // Returning "msg" to the AJAX Request
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hishan_98 |
