Saturday, May 26, 2012

Single file upload php


Before writing scripts for file upload make a Folder named "science" in your htdocs  or www (web root) then below contains a file in html format in which creates uploading interface and posting the uploaded file into php file called "upload.php". 
html interface looks as below



Select a file to upload
Science:


 
Fallowing Codes creates the above file upload interface.

<html>
<head>
<script type="text/javascript" language="JavaScript"><!--
function ExtensionsOkay() {
var extension = new Array();
var fieldvalue = document.Myform.file.value;
extension[0] = ".doc";
extension[1] = ".docx";
extension[2] = ".jpg";
extension[3] = ".jpeg";
extension[4] = ".pdf";
extension[5] = ".xls";
var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
 for(var i = 0; i < extension.length; i++) {
 if(thisext == extension[i]) { return true; }
 }
 alert("Your upload form contains an unapproved file name."); return false;
}
//--></script>
</head>
<body>
<center> <br><br><br> Select a file to upload<br><br>
<table >
<tr>
<td> <form name= "Myform" enctype="multipart/form-data" action="upload.php" method="POST" onsubmit="return ExtensionsOkay();"/>
 <input type="hidden" /> Science:</td><td> <input name="file" type="file" /></td><td> <input type="submit" value="Upload File" /> </form></td>
</tr>
</table>
</center>
</body>
</html>

upload.php is shown below.

<html>
 <body>
<?php
$target_path = "science/";
 $target_path = $target_path . basename( $_FILES['file']['name']);
 if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else
{
echo "There was an error uploading the file, please try again!";
}
 ?>
</br></br>
<a href="view.php">View Uploaded files</a>
</body>
</html>

view.php is shown below.

<?PHP
 $folder = "science/";
$handle = opendir($folder);
while ($file = readdir($handle))
{
 $files[ ] = $file;
}
closedir($handle);
foreach ($files as $file)
 {
 echo '<li><a href="science/'.$file.'">'.$file.'</a></li>';
}
?>

2 comments: