...was asked for some php file upload code, so I thought I would post some stripped down, barebones code that I use in admin/dashboard pages to add/change images associated with products.
Please see attached image for folder setup.
The code uses the jQuery Form plugin by Mike Alsup.
index.php has two forms; one for the image uploads and the other to show where you would have your "product add/update" form. Files are immediately uploaded to a tmp directory whenever you select an image. If you change your mind a few times you can end up with lots of images in your tmp folder, so there is a small routine to empty the tmp folder whenevery index.php is called.
<?php
//remove old tmp files
$tmpImageFolder = $_SERVER['DOCUMENT_ROOT'].'/assets/images/tmp';
$files = glob($tmpImageFolder.'/*.*');
if ($files){
foreach($files as $filename){
unlink($filename);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload File Demo</title>
<style>
/* hide the browse button */
#input-file {
display:block;
height:0;
width:0;
}
</style>
</head>
<body>
<p><img id="display-image" src="/assets/images/placeholder.jpg"></p>
<form id="upload" action="/ajax/uploadfile.php" method="post" enctype="multipart/form-data">
<input id="input-file" name="file" type="file" value="" />
</form>
<p><button id="choose-photo" type="button">Choose Photo</button></p>
<!-- the product form handler can be ajax or standard post -->
<form id="product-update">
<!-- use a hidden field to send over new filename. hidden field is updated via the js uploadFile() function -->
<input id="product-newfilename" type="hidden" value="">
<!-- Your actual product form data goes here -->
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/assets/js/jquery.form.min.js"></script>
<script src="/assets/js/uploadform.js"></script>
</body>
</html>
CSS is used to remove the ugly "browse" input type="file" control and then jQuery is used to trigger the control when "Choose Photo" button (which can be nicely styled) is clicked. When an image is selected the jQuery Form is triggered and uploads the file to the forms action url.
uploadform.js
$("#input-file").on("change",function(){
var reg=/(.jpg|.gif|.png)$/;
if (!reg.test($("#input-file").val())) {
alert('Invalid File Type');
return false;
}
uploadFile();
});
$("#choose-photo").on("click",function(){
$('#input-file').click();
});
function uploadFile()
{
$("#upload").ajaxSubmit({
dataType: 'json',
success: function(data, statusText, xhr, wrapper){
$('#display-image').prop("src","/assets/images/tmp/"+data);
//update relevent product form fields here
}
});
}
uploadfile.php is a standard upload file handler which renames the uploaded and displays the new name.