PHP - File Upload spitting out error - php

I was working on a simple file upload exercise i've gotten from my WebDev Class - We actually only had to copy the code and integrate it to fit our needs.
I tried to do so for my project, sadly it will keep on echoing out the same error.
<?php
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
$max_filesize = 524288;
$upload_path = 'uploads/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
var_export($_FILES, $ext);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['usrfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here';
else
echo 'There was an error during the file upload. Please try again.';
?>
It keeps on giving me the 'wrong filetype' error, with all of defined types in the array.
<form id='upload' action="uploadfile.php" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td >Choose a File to Upload</td>
</tr>
<tr>
<td >Select File</td>
<td ><input type="file" name="userfile"></td>
</tr>
<tr>
<td colspan=2 id="sub"><input type="submit" name="submit" value="submit" ></td>
</tr>
</Table>
</form>

$filename = $_FILES['usrfile']['name'];

The 'tmp_name' index contains a temporary file name, not the one the file really had. That's stored in 'name'. See this page for information.
Additionally, you should:
check for errors in the 'error' index.
use pathinfo to get the extension,
lowercase it before searching the array,
add some randomness to the uploaded file name to avoid overwriting existing files.

You can use this as firstly you have to always echo the $_FILES array then start debuging.
change this line from
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
to
$allowed_filetypes = array('jpg','gif','bmp','png', 'jpeg');
change the follwing line
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
to
if(filesize($_FILES['usrfile']['size']) > $max_filesize)
and remove the line
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
and change this line
if(!in_array($ext,$allowed_filetypes))
to
if(!in_array($_FILES['usrfile']['type'],$allowed_filetypes))

Related

Upload file trouble in PHP

I have made an upload image a couple times before and I never have problems. And I just copy the script and it worked fine, but after I copy I don't know why it keep shows that I'm not using the right extension. Can you spot the mistake?
This is the form script:
<tr height="30">
<td> </td>
<td align="right">Gambar Barang </td>
<td><input type="file" name="gambar" /></td>
</tr>
and its the action,
$errors= array();
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILES['gambar']['name']);
$gambar = $_FILES['gambar']['name'];
$gambar_size = $_FILES['gambar']['size'];
$gambar_type = $_FILES['gambar']['type'];
$gambar_tmp = $_FILES['gambar']['tmp_name'];
$gambar_ext=strtolower(end(explode('.',$_FILES['gambar']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($gambar_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($gambar_size > 4097152){
$errors[]='File size must be excately 4 MB';
}
if(empty($errors)==true){
copy($_FILES['gambar']['tmp_name'], $uploadfile);
}else{
print_r($errors);
}
There are several things that could cause file upload to fail:
does the upload form have enctype="multipart/form-data"?
is file_uploads = On in php.ini?
what is the max post/upload limit in php.ini?
did you check the permissions for the upload folder?
Your code works fine, just make sure your form uses:
method='post'
and(as already mentioned by Reto) - enctype="multipart/form-data"
i.e. something along the lines of:
<form method='post' action='#' enctype='multipart/form-data'>

How to Prevent an Upload Script to Move the File AGAIN on Page Reload?

The Form:
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
</div>
The Script:
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script also uses javascript for multiple image upload.
When clicking on "page reload" in the web browser, after the first upload has been done, then the script assigns the same file a new ID code for the name and moves the image files a second time into the "uploads" folder.
How to prevent the script from moving the image files (with a new ID code assigned for the name) a second time into the "uploads" folder?
Any suggestions are much appreciated.
EDIT:
So, I opted for a "redirect" to the same page, where the form gets cleared out, after the submission has been done.
It looks like, this is the way to do it.
Before upload (where you displays the upload FORM) you can create a key (random) and store it on your server somehere. (temp folder) (using a serial number is even more safe)
You can include this as "hidden" value in the upload form.
The script, which is processing the upload, should look first for this key, if it exists, you can delete it and proceed with the rename / upload / whatever you want to do.
If the key is gone, you can be sure it's a duplicated request and simply ignore it.
Don't forget to clean your temp folder every time (let's say delete every keys which is older than an hour or so)

The footer div is not showing when an error comes up on upload

The footer is included in the index file with the include code leading to this page like this
<?php include "footer.php" ?>
<center><div id="content"><br>
<form method="post" enctype="multipart/form-data">
<input type="file" class="file" name="userfile"/><br>
<br>
<button name="upload" type="submit" value="Submit" class="upload">Upload</button>
</form>
<?php
if(isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_filesize = 10485760;
$upload_path = 'useruploads/';
$description = $_POST['imgdesc'];
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('<h4>The file you attempted to upload is not allowed.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('<h4>The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('<h4>You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
$query = "INSERT INTO uploads (name, description) VALUES ($filename, $description)";
mysql_query($query);
echo '<h5>Your file upload was successful!';
} else {
echo '<h4>There was an error during the file upload. Please try again.';
}
}
?>
</div>
If you want to see for you're self i have temporary uploaded this script to my site so you can see the error for you're self try and upload something that is not a image file and you will see the error, and i was seeing if it was possilbe to add a button after the upload is complete to link it to the image
Website Link
Here is also the footer code
<center><div id="footer">
<p>Copyright © OSPICTUREVAU 2014</p>
</div>
You are using die to output your errors which will stop execution of all code after the die statement. This means that your footer code is never executed.
Redirecton error:
if (!in_array($ext, $allowed_filetypes))
{
header("Location: errorpage.php");
exit;
}
You could pass error codes to the errorpage.php to give the user a meaningful error message.

php file uploader not uploading

I'm making an uploader for a website which is designed to upload videos. As of now, it doesn't check if they're videos, it's simply uploads them. I do this through a simple form that selects a file and submits it to upload.php. Here is the HTML which I do this with:
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();">
Video Name: <input type="text" name="name" class="maininput" style="width:300px;" maxlength="80"><br>
File: <input name="myfile" type="file" class="mainbutton"/ style="clear:both;"><br>
Description: <br><textarea cols="43" rows="10"></textarea><br>
<input type="submit" name="submitBtn" value="Upload" class="mainbutton"/>
</form><br><br><br>
<p id="f1_upload_process">Loading...<br/><img src="/images/loader.gif" width="20" height="20" /></p>
<p id="result"></p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;">
<script language="javascript" type="text/javascript">
window.top.window.stopUpload(<?php echo $result; ?>);
</script> </iframe>
Here are my javascript functions which accompany this:
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
document.getElementById('result').innerHTML =
'<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
document.getElementById('result').innerHTML =
'<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
return true;
}
And finally, here is the contents of upload.php, which I use for actually uploading the file:
<?php
$result = 0;
$target_path = "videos/";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
I believe that the issue is with the upload.php. The problem is not with anything client side, it's the fact that in the client, it uploads the file, but I can't find the file in the videos folder, or any folder in the server directory.
Any help is greatly appreciated. Thanks!
This is what I use, you can customize it to suit your script:
Simply change the *path and *variables.
<?php
// Configuration - Your Options
$allowed_filetypes = array('.mov','.mp3','.mp4','.flv'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>

PHP & Jquery Image Upload - No file issue

I am using an old script I used on previous projects to upload images. The project only used HTML and PHP making uploading easier to handle as such! :)
I am quite new to Jquery and Ajax handlers and due to my current projects high use of handlers I need to upload things without refreshing entire page, perhaps just a div.
My Script:
function postfile() {
var filename = $("#image").val();
$.ajax({
type: "POST",
url: "pages/minutes1.php",
secureuri:false,
fileElementId:'image',
enctype: 'multipart/form-data',
data: "submit=yes&image=" + {file: filename},
success: function(msg5){
$("#upform").html(msg5);
}
});
}
My PHP and HTML:
<?
/**
* The following uploader was not originally suited for text based files<br>
* Copied and Re-used from previous projects<br>
*/
$submit = $_POST['submit'];
if($submit=="yes")
{
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","100");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs.
//If the error occurs the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
if(!$image){
?>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="tabcol1 font1" style="text-align: center;">
There was no minutes file attached!
</td></tr>
<tr>
<td class="tabcol4 font1" style="text-align: center;">
Please wait as you are directed back
</td></tr>
</table>
<?
}elseif($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension != "doc") && ($extension != "txt") && ($extension != "pdf") && ($extension != "odt") && ($extension != "docx") && ($extension != "rtf"))
{
?>
<b>The file type uploaded is not supported!</b><br><br>
<b>Supported formats:</b> doc, docx, pdf, odt, txt, rtf
<?
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
?>
File size, too large! (if you need lieniency please contact webmaster)
<?
}else{
//we will give an unique name, for example the time in unix time format
$exam = substr("$filename", 0, -2);
function MakeRandom($minLength, $lastNr){
$i = 0;
while ($i <= $minLength){
$randomnr = ($i === $minLength) ? 1 : rand(0, 9);
$strNumber = (!$strNumber) ? $strNumber = $randomnr : $strNumber .= $randomnr;
$i++;
}
return $strNumber;
}
// show the number
$num = MakeRandom(5, 1);
$col = "$exam$num";
$image_name = $col.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="minutes/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied){
?>
File uploaded and E-mail sent!
<?
}
}
}
}
}else{
?>
<div id="upform">
<form method="post">
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="font1 tabcol1">
<!-- begin 2 column table -->
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td class="font1">
<b>Choose a file to upload:<br> <input id="image" name="image" type="file" /><br />
<input type="button" id="submit" name="submit" value="submit" onclick="postfile()">
</td>
<td class="font1"></td>
</tr>
</table>
<!-- End 2 column table -->
</td></tr>
</table>
</form>
</div>
<?
}
?>
The problem I am getting is, even when I have added a file and pressed submit,
it gives me my no image error.
I believe I have written the script wrong but I could not find any syntax errors.
All help would be appreciated!
Thank you in advance :)
$.ajax doesn't support file uploads the same way that a normal form submission does. The usual suggestion to get around this is to embed your upload script into an iframe so it doesn't reload the page when you upload.
Here's an example.

Categories