corrupt files after upload in php - php

I have written php script for upload file. It seems to work properly but when open uploaded file in upload folder i get this error:
unknown format or damaged
my code:
HTML:
<form method="POST" action="<?=URL?>user/homework" enctype="multipart/form-data">
<input type="hidden" id="csrf" name="csrf" value="<?= $_SESSION['csrf'] ?>" />
<table class="table table-responsive">
<tr>
<td><label>file</label></td>
<td><input multiple="multiple" type="file" name="file"/></td>
</tr>
</table>
<input type="submit" name="sub" value="submit" class="btn btn-success"/>
</form>
PHP:
if (isset($_POST['sub'])) {
if (Security::chekCsrf($_POST['csrf']) == FALSE) {
$data = array('', 'dan');
$this->render('homework', $data);
exit();
}
if (!empty($_FILES['file'])) {
$name = time() . '_' . $_FILES['file']['name'];
if ($_FILES['file']['size'] > 20971520) {
$data = array('size high', 'war');
$this->render('homework', $data);
exit();
}
$valid = array('application/octet-stream', 'application/x-rar-compressed', 'application/zip');
$type = $_FILES['file']['type'];
if (!in_array($type, $valid)) {
$data = array('wrong format', 'war');
$this->render('homework', $data);
exit();
}
$dir = 'upload/' . $name;
if (move_uploaded_file($_FILES['file']['tmp_name'], $dir)) {
$data = array('ok', 'suc');
$this->render('homework', $data);
exit();
} else {
$data = array('problem', 'dan');
$this->render('homework', $data);
exit();
}
}
}

Had the same issue. Turns out i had two trailing spaces Outside of the quotations on a php file i use as a handler. Not knowing this can actually corrupt a file on upload. Then this 'unrecognised format' error is given upon attempting to open a downloaded file.

Related

Codeigniter - Upload multiple files and displaying files

My web app only allows for one file upload which is an issue because users want to be able to submit 2 or more files when necessary.
Please how do I allow multiple file uploads and displaying those files to be downloaded by another type of users?
MODEL
public function upload_docs($data)
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$q = $this->db->get('submit_assignment');
if ( $q->num_rows() > 0 )
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$this->db->update('submit_assignment',$data);
} else {
$this->db->insert('submit_assignment',$data);
}
}
CONTROLLER
public function upload_docs()
{
$homework_id = $_REQUEST['homework_id'];
$student_id =$_REQUEST['student_id'];
$data['homework_id'] = $homework_id;
$data['student_id'] = $student_id;
$data['message'] = $_REQUEST['message'];
// $data['id']=$_POST['assigment_id'];
$is_required=$this->homework_model->check_assignment($homework_id,$student_id);
$this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');
$this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');
if ($this->form_validation->run() == FALSE) {
$msg=array(
'message'=>form_error('message'),
'file'=>form_error('file'),
);
$array = array('status' => 'fail', 'error' => $msg, 'message' => '');
}else{
if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
$time = md5($_FILES["file"]['name'] . microtime());
$fileInfo = pathinfo($_FILES["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$_FILES["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
public function handle_upload($str,$is_required)
{
$image_validate = $this->config->item('file_validate');
if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {
$file_type = $_FILES["file"]['type'];
$file_size = $_FILES["file"]["size"];
$file_name = $_FILES["file"]["name"];
$allowed_extension = $image_validate['allowed_extension'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$allowed_mime_type = $image_validate['allowed_mime_type'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mtype, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
return false;
}
if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
return false;
}
if ($file_size > $image_validate['upload_size']) {
$this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
return false;
}
return true;
} else {
if($is_required==0){
$this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
return false;
}else{
return true;
}
}
}
VIEW
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">
<div class="modal-body pt0">
<div class="row">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" id="homework_id" name="homework_id">
<input type="hidden" id="assigment_id" name="assigment_id">
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('message'); ?></label>
<textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
<input type="file" id="file" name="file" class="form-control filestyle">
</div>
</div>
<p id="uploaded_docs"></p>
</div>
</div>
<div class="box-footer">
<div class="" id="footer_area">
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='Please wait...'><?php echo $this->lang->line('save'); ?></button>
</div>
</div>
</form>
This is displayed like this
controller
public function assigmnetDownload($doc)
{
$this->load->helper('download');
$name = $this->uri->segment(5);
$ext = explode(".", $name);
$filepath = "./uploads/homework/assignment/" . $doc;
$data = file_get_contents($filepath);
force_download($name, $data);
}
view
<table class="table table-hover table-striped table-bordered example">
<thead>
<tr>
<th><?php echo $this->lang->line('name') ?></th>
<th><?php echo $this->lang->line('message') ?></th>
<th class="text-right"><?php echo $this->lang->line('action') ?></th>
</tr>
</thead>
<tbody id="homework_docs_result">
</tbody>
</table>
Thanks to all helping me out. I did as you guys directed. However, I noticed I'm able to select multiple files now but gets stuck on the save button.
When I click, nothing happens. Data is not submitted.
This is what I have done so far
controller
if (isset($_FILES["file"])){
foreach($_FILES["file"] as $file){
if(!empty($file["name"])){
$time = md5($file["file"]['name'] . microtime());
$fileInfo = pathinfo($file["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($file["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$file["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
}
}
view
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="uploaded_docs">
<input type="file" multiple="" id="file" name="file[]" class="form-control filestyle">
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text=' Please wait'><?php echo $this->lang->line('save'); ?></button>
</form>
HTML
<input type="file" id="file" name="file[]" class="form-control filestyle">
Setting name to file[] will accept array of files
PHP
if (isset($_FILES["file"]){
foreach($_FILES["file"] as $file){ //this loop will get one file from 'file[]' array at a time
if(!empty($file["name"])){
//your alreay written code
//replace $_FILES["file"] with $file
}
}
}
Hope this helpful :)
Some tips, if help. Do not forget the vote to strengthen. Let's go...
<form method="post" action="upload_docs" enctype="multipart/form-data">
<input name="filesToUpload[]" type="file" multiple="" />
</form>
On your controller it's simple ...
if(isset($_FILES['filesToUpload'])) {
foreach ($_FILES['filesToUpload'] as $fileUp) {
$time = md5($fileUp["file"]['name'].microtime());
$fileInfo = pathinfo($fileUp["file"]["name"]);
$img_name = "{$time}.{$fileInfo['extension']}";
$data['docs'] = $img_name;
move_uploaded_file($fileUp["file"]["tmp_name"], "./uploads/homework/assignment/{$data['docs']}");
$data['file_name']=$fileUp["file"]['name'];
$this->homework_model->upload_docs($data);
}
}
To display multiple files you need to use the same concept as uploading working with
foreach($files as $file){ ... }
I hope I helped. Success!
Setting attribute multiple will allow selecting multiple files at once by pressing ctrl, setting the name as an array(file[]) will allow more than files name to be stored.
<input type="file" id="file" name="file[]" class="form-control filestyle" multiple>
However, if you don't want the user to upload multiple files at once then you'll have to make multiple input fields with the same name as an array(file[])
<input type="file" id="file" name="file[]" class="form-control filestyle">
<input type="file" id="file1" name="file[]" class="form-control filestyle">
...
...
In your controller, you'll have to traverse through each element as it is now an array.
foreach($_FILES["file"]['name'] as $file){ //single element
echo $file; // returns the name of file
// your-logic-to-upload
}
If you're having trouble uploading multiple files, see here, here and here.
Hope it helps you.

File upload with php issue moving file

I can't upload a file in my server using php. The problem is that I can't find see which is the error, or I don't know how see it. By the way, I think is something about the file moving. This is the php code
<!-- upload -->
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' .$myFileExt;
$fileDestination = "/var/www/upload".$newFileName;
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
Here is the form:
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>
Any idea?
Your issue is very Minor...
You just missed a Slash(/) after the /www/uploads.
Try this:
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' . $myFileExt;
$fileDestination = "/var/www/upload/{$newFileName}"; //YOU WERE ONLY MISSING A SLASH (/) HERE AFTER /upload
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>

Loading file to server

I have two forms on one page that should give users posibility to load file to server(from URL or from user's PC)
<form method="post" action="bigorder.php" name="photourl">
<label for="photoorig">URL</label>
<input type="url" name="photoorig" placeholder="">
<input type="submit" value="Load" name="photoload">
<br>
</form>
<form method="post" action="bigorder.php" name="photofile" enctype="multipart/form-data">
<label for="photoloc">Load own file</label>
<input type="file" name="photoloc" id="photoloc">
<input type="submit" value="Load" name="photoload2">
</form>
And php
<?php
$tmpname=rand().".jpg";
if ($_POST['photoorig']) {
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if ($_POST['photoloc']) {
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
?>
First form loads files fine, but the second one doesn't work at all. I even don't receive any error message.
What am I doing wrong? Or missing something?
Here is the correct code,it is working.In your code curly braces was missing in second form and isset() function should use to check posted data set or not.
<?php
$tmpname=rand().".jpg";
if (isset($_POST['photoload'])) {
echo '1st';
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if (isset($_POST['photoload2'])) {
echo '2nd';
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>

Image uploader with preview didn't work

I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $name);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["images"]["tmp_name"][$key], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>
You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories