move_uploaded_file doesn't move image to permanent folder || PHP - php

I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help

Related

Form field input isn't received by JSON AJAX script

I am unable to catch the $productid from the form. Not sure what I'm doing wrong. Any ideas?
The selected files do upload, but not to the product folder specified, and nothing about the success is returned to index.php
It's strange but stackoverflow also mentions when trying to post "It looks like your post is mostly code; please add some more details", but I have no more info to add?
Thanks
index.php
<form method='post' action='' enctype="multipart/form-data">
<input type="hidden" id='productid' name="productid" value="<?=$productid?>">
<input type="file" id='files' name="files[]" multiple><br>
<input type="button" id='submitphotos' value='Upload'>
<!-- Preview -->
<div id='successupload'></div>
<div id='preview'></div>
<script>
$(document).ready(function(){
$('#submitphotos').click(function(){
var form_data = new FormData();
// Read selected files
var totalfiles = document.getElementById('files').files.length;
var productid= $("#productid").val();
for (var index = 0; index < totalfiles; index++) {
form_data.append("files[]", document.getElementById('files').files[index]);
}
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
for(var index = 0; index < response.length; index++) {
var src = response[index];
// Add img element in <div id='preview'>
$('#preview').append('<img src="'+src+'" width="400px;">');
}
$('#successupload').append('<h6>Successfully uploaded</h6>back');
files.style.display = "none";
submitphotos.style.display = "none";
}
});
});
});
ajaxfile.php
// Count total files
$countfiles = count($_FILES['files']['name']);
// Get product id
$productid = $_POST['productid'];
//Create request id folder if doesn't exist
if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/')) {
mkdir($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/', 0777, true);
}
// Upload directory
$upload_location = $_SERVER['DOCUMENT_ROOT']."/images/products/".$productid."/";
// To store uploaded files path
$files_arr = array();
// Loop all files
for($index = 0;$index < $countfiles;$index++){
if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
// File name
$filename = $_FILES['files']['name'][$index];
// Get extension
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Valid image extension
$valid_ext = array("png","jpeg","jpg","svg");
// Check extension
if(in_array($ext, $valid_ext)){
// File path
$path = $upload_location.$filename;
// Upload file
if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
$files_arr[] = $path;
}
}
}
}
echo json_encode($files_arr);
die;
</script>
You haven't passed the productid to the ajax call so just before ajax call add this:
form_data.append('productid', productid);
and your code should work fine.

Upload File - 500 Internal Server Error

I'm going straight to the point here.
I'm trying to upload a 400mb+ zip file using jquery and codeigniter.
however, when the progress bar completes it gives me 500 Internal Server Error on the console log don't know what's causing this. I've tried it on my local files everything works fine. but when I put it online it gives me this 500 internal server error.
my hosting and my local have the same settings already.
upload_max_filesize 500M
post_max_size 500M
max_execution_time 3000
Here's my code:
HTML
<h1>Upload File</h1>
<hr />
<form method="post" name="upload_file" data-base-url="<?php echo site_url(array("main", "upload")); ?>" id="upload_file" action="<?php echo site_url(array("main", "do_upload")); ?>" enctype="multipart/form-data">
<p>File Type: <strong>(*)All</strong></p>
<!-- <p>File Type: <strong>doc, docx, pdf, xls, xlsx</strong> and <strong>txt</strong>.</p> -->
<input type="file" name="myfile" class="form-control" required><br>
<input type="submit" name="cmd_file_upload" id="cmd_file_upload" value="Upload File to Server" class="btn btn-default">
</form>
<br />
<p>File Uploaded: <?php echo $result['original_filename']; ?></p>
<div class="progress" style="display: none;">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
0% Complete (success)
</div>
</div>
JQUERY
$("#upload_file").on("submit", function(e){
e.preventDefault();
$("#cmd_file_upload").attr("disabled","disabled");
$(".progress").hide().show();
var $this = $(this);
var $url_transaction = $this.attr('action');
var $base_url = $this.data('base-url');
var formData = new FormData($this[0]);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$(".progress-bar").attr('style','width:'+percentComplete+'%');
$(".progress-bar").html(percentComplete+'%');
if (percentComplete === 100) {
$(".progress-bar").html(percentComplete+'% Complete (Success)');
}
}
}, false);
return xhr;
},
beforeSend:function(){
$(".progress-bar").attr('style','width:0%');
$(".progress-bar").html();
},
url: $url_transaction,
type: "POST",
data: formData,
contentType: false,
processData: false,
// dataType: "json",
success: function(result) {
console.log(result);
setTimeout(function(){
if(result == 0){
window.location.href = $base_url;
}else{
window.location.href = $base_url+"/"+result;
}
}, 500);
}
});
});
PHP CODE
public function do_upload(){
$filename = "file_".md5(date('Y-m-d H:i:s'));
$config['file_name'] = $filename;
$config['upload_path'] = './uploaded_files';
$config['allowed_types'] = '*';
// $config['allowed_types'] = 'doc|docx|pdf|xls|xlsx|txt';
$config['max_size'] = 500000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('myfile'))
{
$error = array('error' => $this->upload->display_errors('<span>','</span>'));
$err = array("status_id" => "0", "message" => $error['error']);
$_SESSION['type'] = "warning";
$_SESSION['message'] = $error['error'];
echo 0;
}
else
{
$data = array('upload_data' => $this->upload->data());
$prev_filename=$data['upload_data']['client_name'];
$file_ext = $this->upload->data("file_ext");
$new_filename = $filename.$file_ext;
$result = $this->main_m->insert_data('uploaded_file', array('original_filename' => $prev_filename, 'new_filename' => $new_filename));
$_SESSION['type'] = "success";
$_SESSION['message'] = "File's Successfully Uploaded!";
echo $result;
}
}
thanks in advance.
The first thing you should check is the permissions on the upload-to folder If it doesn't have read/write access (775 for example), then you'll get a 500 error.
If that doesn't work initially, I suggest you clear your browser cookies and cache, reload and try again. You should still rectify the 500000/512000k error however, it's an easy (and commonly-made ) mistake. In this instance you multiply 500 * 1024 ( kb in a mb) then by 1024 (b in a kb) to get 524,288,000
(b)
Ensure your post_max_size is greater than your upload_file_size and that your memory_limit is greater than the post_max_size (the default memory limit is 128MB)
Hope this helps.
I assume you're performing an AJAX request. If so, and if you're using Chrome, do not check console, but the Network tab. There, it should show you the last request made, with the headers, the response, the output and all that. Check there and tell us what you see first. That's the proper way to debug AJAX.

upload array of files with ajax

I have form that allow me to submit text + number of files. the form submitted with AJAX.
Because it's a number of files my upload function give me error:
Warning: move_uploaded_file(images/usersFiles/14367317720-101.JPG) [function.move-uploaded-file]: failed to open stream: No such file or
directory in C:\Program Files
(x86)\wamp\www\new-site\func\global.func.php on line 134
line 134 is:
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
files' var should be array (because I can load number of files).
How can I fix the error?
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<textarea class="form-control" name="post[text]"></textarea>
<input type='file' name='file[]' class='multi form-control' maxlength='1' accept='gif|jpg|png|bmp' id="files"/>
<a class="btn btn-primary" id="submit">submit</a>
</form>
JS:
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file[]', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('post[text]', $("#addCommentForm").find("textarea").val());
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
server:
function upload_files ($ownerID, $msg, $files, $type)
{
$dateLX = get_current_linuxTime();
///////// Upload files //////////////
if(!empty($files))
{
foreach($files['file']['name'] as $i => $fileName)
{
$fileSurffix = pathinfo ($_FILES['file']['name'][$i]);
$fileSurffix = $fileSurffix['extension'];
$files['file']['name'][$i] = str_replace(' ','',$files['file']['name'][$i]);
$files['file']['name'][$i] = $dateLX.$i."-".$ownerID.".".$fileSurffix;
$fileName = $files['file']['name'][$i];
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
{
$uploadFilesQuery = "INSERT INTO `files` (ownerID, name, type)
VALUES('$ownerID', '$fileName', '$type')";
$res = mysql_query($uploadFilesQuery);
if (!$res)
$msg['error']['uploadFile'] = "error <br />".mysql_error();
}
elseif ($files['file']['error'][$i] != 4)
$msg['error']['uploadFile'] = "ERROR ";
}
}
return ($msg);
}
USER_FILES must be an absolute path like
"C:\Program Files (x86)\wamp\www\new-site\images\usersFiles\"

Not able to upload image via jquery, ajax and PHP

I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.

PHP file upload not working. Getting error:

To start things off, I've looked at a few similar problems on here but still can't resolve my issue here.
HTML:
<input type="file" name="filename" multiple="multiple" data-classIcon="icon-plus" data-buttonText="Upload Your File">
PHP:
$name = $_FILES['filename'];
$temp_name = $_FILES['filename']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'uploaded';
}
}
} else {
echo 'error: not uploaded';
}
JS:
$('#cc-submit').on('click', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "balanced/example.php",
data: $('#creditcardpost').serialize(),
success: function(data)
{
alert(data);
}
});
});
Error:
Undefined index: filename in /public_html/script.php on line xx (the two lines that collect the $_FILES variables.
"error: not uploaded"
You must use:
$name = $_FILES['filename']['name'];
I used print_r on $_FILES and found my files were coming through as "file-0". I'm not doing multi file uploads, so this works for me. And here is the solution. PHP:
$name = $_FILES['file-0']['name'];
$temp_name = $_FILES['file-0']['tmp_name'];
$location = '../uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
}
print_r($name);
And the JS that sends it needed to be worked a bit:
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: 'balanced/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
$('#creditcardpost').append('<input type="hidden" value="' + data + '" name="filename" />');
}
});
I've got it working. Thanks for helping out guys.

Categories