I have a form with a file uploader. I want to display error messages without refreshing the page. I guess I need to display the errors with jQuery and pass the file to the PHP script with Ajax. I'm not sure how to approach this.
This is my current code. After submission, it redirects you to upload.php
and displays error/success messages there, but it isn't very user friendly.
<form method="post" action="upload.php" enctype="multipart/form-data">
<div id="file_upload">
<input type="file" name="file">
<input type="submit" value="Upload">
</div>
</form>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. Rename and try again.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "zip" ) {
echo "Sorry, only zip files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>