This is my first time trying to upload an image file to a directory using php . I fetch data from a mongodb database and print it as html .
foreach($storeCursor as $store){
echo "
<tr class = 'product-columns'>
<td class ='product__thumbnail store__thumbnail'>
<img src = ".$store["picture"]." class='cartItemImage' />
<form class = 'StoreImageForm' method = 'POST' action = ''
enctype= 'multipart/form-data'>
<input type = 'file' name ='storeImg' class = 'storeImage' required/>
<br/>
<button type ='submit' name = 'submitImage' class = 'btn btn-sm btn-primary changeImageBtn' > Change Image </button>
</form>
</td>
</tr>";
}
Now for each element I also print a form for the user to upload an image to my ../images/stores/
directory as shown above .
On my same page on top I have this php script to upload the file when submit button is clicked and my form is submitted :
<?php
if(isset($_POST['submitImage'])) {
echo "ENTERED"; //NOT SHOWN
$target_dir = "../images/stores/";
$target_file = $target_dir . basename($_FILES["storeImg"]["name"]);
if (move_uploaded_file($_FILES["storeImg"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["storeImg"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
My script never runs as it never enters the if statement and I have no idea why . "ENTERED" is not echoed on my page after submitting the image and no image is added to my directory
Everything happens on the same page as I submit my form and the page is refreshed .
What I tried : I thought that maybe the problem was that I create the form as html when the data from mongodb is fetched so I also added a new form at the beginning of my page created with plain html and after submitting it I had the same result so that's not the problem I suppose .
I would appreciate your help .
NOTICE : If I do not refresh my page on action and move on another page my post method works ! But I still want it to work on my page on refresh . It seems that the issue is on refreshing on action=''