Skip to content

Instantly share code, notes, and snippets.

@sdmg15
Last active May 22, 2016 13:07
Show Gist options
  • Save sdmg15/b4c4e69e306f058ccfcb to your computer and use it in GitHub Desktop.
Save sdmg15/b4c4e69e306f058ccfcb to your computer and use it in GitHub Desktop.
A simple way to upload file combining JavaScript and PHP
<!doctype html>
<html>
<head>
<title> Upload-file</title>
<meta charset="utf-8">
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data" action="script.php" target="uploadFrame" method="post">
<label for="uploadFile">Image :</label>
<input id="uploadFile" name="uploadFile" type="file" />
<br /><br />
<input id="uploadSubmit" type="submit" value="Upload !" />
</form>
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe id="uploadFrame" name="uploadFrame" charset="utf-8"></iframe>
</div>
<script>
function uploadEnd(error,path){
if(error !== false){
document.getElementById('uploadStatus').innerHTML = ' Upload bien éffectué du fichier <img src=" uploads/'+ path + '"> '
}else {
document.getElementById('uploadStatus').innerHTML = 'Une erreur est survenue lors de l^upload';
}
document.getElementById('uploadForm').addEventListener('submit',function(){
document.getElementById('uploadStatus').innerHTML = 'Chargement en cours ...............';
},true);
}
</script>
<?php
$error = false;
$fileName = false;
function upload($index,$destination,$maxsize=FALSE,$extensions=FALSE)
{
//Test1: fichier correctement uploadé
if (!isset($_FILES[$index]) OR $_FILES[$index]['error'] > 0)
return FALSE;
//Test2: taille limite
if ($maxsize !== FALSE AND $_FILES[$index]['size'] > $maxsize)
return FALSE;
//Test3: extension
$ext = substr(strrchr($_FILES[$index]['name'],'.'),1);
if ($extensions !== FALSE AND !in_array($ext,$extensions))
return FALSE;
//Déplacement
return
move_uploaded_file($_FILES[$index]['tmp_name'],$destination. '/'.basename($_FILES[$index]['name']));
}
$upload = upload('uploadFile','uploads/',143099,['png','php','jpg','gif','txt','php']);
if($upload){
$error = true;
$fileName = $_FILES['uploadFile']['name'];
}else {
return $error = false;
}
?>
<script>
window.top.window.uploadEnd("<?= $error ?>","<?= $fileName ?>");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment