move_uploaded_file() can't upload files in a Hosting Server - php

In my localhost server, with apache installed, I can upload files fine. But when I move everything to a hosting server (like Altervista.org) files doesn't upload.
Here's the html code:
<form id="fileupload" action="" method="POST">
<input id="filesupload" type="file" multiple name="files" accept=".jpg" accessKey="PDF"/>
<button id="MegaUpload" type="button" class="btn btn-primary start" onclick="conversion()">
</form>
Assuming that HTML Works well, I transfer everything in an AJAX and I can connect fine to the server.
PHP code can receive the input file as well, but when I try to do the upload, it doesn't work.
Here's PHP code:
if (isset($_FILES['fileToUpload'])) {
if (!isset($_COOKIE['users'])) {
setcookie('users', md5(time()/1234), time() + (86400), "/");
}
if (!file_exists('files/uploads/' . $_COOKIE['users'] . '/')) {
mkdir("files/uploads/" . $_COOKIE['users'], 0755);
mkdir("files/uploads/" . $_COOKIE['users'] . "/tmp", 0755);
}
$target_dir = 'files/uploads/' . $_COOKIE['users'] . '\/tmp\/';
for ($s=0; $s <= 10; $s++) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$s]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$s],
$target_file)) {
//ok
}
else{
//something wrong
}
}
}
Again: Assuming that AJAX works fine (because I tested, and server receives the files I input), why in the hosting server it doesn't work?
It creates directories perfectly fine, there are directory permissions too, as you can see, and I checked in FileZilla if every .php files is setted to '0755'.
If you can't understand what's going on, I can post the AJAX part if you wish.
Thank you.
EDIT:
I edited the PHP part, so you know is a loop.
I added the enctype='multipart/form-data' as you said but still no result.
I forgot to put the multiple part on the HTML too.
Here's the AJAX part as you asked:
$("#filesupload").change(function(evnt) {
var fd = new FormData();
for (var s = 0; s < ins; s++) {
fd.append("fileToUpload[]", document.getElementById('filesupload').files[s]);
}
$.ajax({
url: 'upload.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: fd,
type: 'post',
async: false,
success: function(result){
alert(result);
},
error: function(result) {
alert(result);
}
});
}
I tested with alerts and echos, and I know the servers receives the file(s), but it doesn't upload.

Create a
<?php phpinfo(); ?>
file on the hosting server and check the section file_uploads. This should be on ON.
If it is OFF or FALSE you may have no rights for a file upload. For this you should contact the admin of the hosting server. If you are the root, you can set this status to ON using this link: here

Related

move_uploaded_file is not working in MAMP

I'm running into an issue using move_uploaded_file, specifically that it... doesn't work.
I have an input to upload the pdf:
<div>
Upload Resources
<input type="text" id="doc-name" name="doc-name">
<input type="file" id="doc-upload" name="doc-upload" accept="application/pdf">
<button id="upload-button">Upload</button>
</div>
And some jquery that sends a POST request with that file:
$("#upload-button").click(function() {
if ($('#doc-name').val() == '') {
var formData = new FormData();
var filename = $('#doc-name').val();
var uploaded = $('#doc-upload').val().split('\\');
var path = uploaded[uploaded.length - 1];
var file = $('#doc-upload').prop('files')[0];
formData.append("functionCall", "document-upload");
formData.append("filename", filename);
formData.append("path", path);
formData.append("file", file);
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(e) {
console.log(e);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorMessage);
}
});
)};
This sends to my functions file, which is set up kind of odd (it might actually be standard practice, I've just never seen it like this) in that it's one big switch statement; which case gets run is dependent on the functionCall variable passed in. So here is the function code for that specific case statement:
.
.
.
case "doc-upload":
$filename = $_POST['filename'];
$path = $_POST['path'];
$file = $_FILES['file'];
$uploadQuery = "INSERT INTO uploads (filename, path) VALUES ('$filename', '$path')";
$upload = mysql_query($uploadQuery);
if (move_uploaded_file($_FILES['file']['tmp_name'], 'test/' . $_FILES['files']['name'])) {
echo 'yay';
} else {
echo 'such is life';
}
Everything above the move_uploaded_file line works great, but I keep getting the 'such is life' line returned, and the transferred file does not show up in 'test/'. I know both the test folder and uploaded file are present thanks to a file_exists check. Any ideas about what I might have done wrong?

Showing docx without page refresh

I am curious to know that is it possible to show a docx file (which is available on server) inside a div without refreshing that page (using google doc viewer API or any other possible way).
Let me clear my requirement:-
HTML+JQUERY code:
<div class="browse-flie col-md-7">
<div class="alert alert-danger" style = "display:none;"></div>
<input type="file" id="uploaddocfile">
<button name="upload" value="Upload" class="btn EditBtn uplaod_file">Upload</button>
</div>
<div id = "myid" style = "height:500px;width:600px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$('.uplaod_file').on('click', function() {
var file_data = $('#uploaddocfile').prop('files')[0];
var ext = file_data.name.split('.').pop();
if(ext == 'docx'){
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.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){
var response = $.parseJSON(php_script_response);
if(response.status == 'error'){
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file upload failed please try again');
}
if(response.status == 'success'){
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
}
});
}else{
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file extension must be docx'); return false;
}
});
</script>
PHP code:
<?php
// A list of permitted file extensions
$allowed = array('docx');
//echo "<pre/>";print_r($_FILES); die;
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
Now:
I have simple file upload code through jquery and php (working perfectly fine).
Now what I want is, after upload file when it comes success as a response then I want to show a doc file using API to my <div id = "myid" style = "height:500px;width:600px;"></div> (without refresh)
So what I tried:
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
(link changed for security reason but docx is available on server and I am able to open it directly)
But obviously it's not going to work.
So how can I do that?
Normally you'd do :
if(response.status == 'success'){
$('#myid').load("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
Instead of .html (which does something else).
However it's unlikely to work because the document you are accessing is not one that is managed by GoogleDocs (there may be cross-origin issues), so make sure you're allowing remote requests from Google to be made.
Instead you could try
if(response.status == 'success'){
$('#myid').html("<iframe src=\"http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true\"></iframe>");
}
In case Google allows embedding of gview in iframes (though they may not).

PHP file uploaded showing false

I have a form that has multiple file uploads and each input is uniquely named, however, when attempting to get the uploaded file, my test if showing false.
Please find the code below. I am at a loss as to why this is happening.
<label class="label" for="uploadfile">Contract:</label>
<input name="'.$ICP.'_uploadedfile" id="'.$ICP.'_uploadedfile" type="file" />
The $ICP var is looped out, as there can be multiple instances, so this way each name is unique and on the server side, the POST is requested for each loop of the ICP.
while($icp_details = mysqli_fetch_array($ICP_exist_qry)){
$ICP_ID = stripslashes($icp_details['ICP_ID']);
if(!file_exists($_FILES[$ICP_ID."_uploadedfile"]['tmp_name']) || !is_uploaded_file($_FILES[$ICP_ID."_uploadedfile"]['tmp_name'])) {
echo false;
} else {
echo true;
}
}
I am not having any problems retrieving the values of the other posted inputs, just the files uploaded part.
Any help on this one is appreciated. :)
Note: Form is being submitted by Ajax.
To upload the file correctly using Ajax (and in this case JQuery) you need to use the FormData object. The code snippet below illustrates how it can be used. It is used instead of the .serialize() or .serializeArray() methods.
$('#file-form').submit(function(e) {
$.ajax({
url: 'http://example.com/upload/',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false
});
e.preventDefault();
});

jQuery upload running but not uploading file

I was wondering if i could get a bit of advice.
Im trying to upload a file using jquery while keeping the user on the same page.
Whatever i try isnt working. I was wondering if someone could have a look and tell me where im going wrong.
My HTML is
<form id="import" enctype="multipart/form-data" action="/ajax/postimport" method="POST">
<div class="form-group">
<input type="file" name="filename" id="filename" />
</div>
<button type="button" id="importSave">Import</button>
</form>
This is my jquery
$("#importSave").click(function()
{
$.ajax({
url: '/ajax/postimport',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {file: $(#filename).val()},
success: function(data)
{
alert(data.result)
},
error: function(textStatus, errorThrown)
{
}
});
});
and then my PHP, which is Laravel 4
if (Input::hasFile('filename')) {
$file = Input::file('filename');
$destPath = public_path() . '/uploads/';
$filename = str_random(10) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destPath, $filename);
}
It is not possible to upload files by just using the jQuery ajax function. You will need to use a FormData object to do this. The problem with Formdata is that it is not supported in all browsers. If you do want to use it, you can always find plenty tutorials like this one.
You can also use a jQuery plugin that does the work for you. :)
It is not possible to do like this. you are just making post ajax request with only one field file: $(#filename).val().
So you need to use ajax upload library like.
There are several alternatives. But I like most are
http://www.plupload.com/
http://www.uploadify.com/

Drag and Drop Jquery upload to PHP

I have seen many topics about this problem but none of them got a legit answer or a including PHP file.
I want to make a drag & drop saving tool. The problem is that my files are not getting uploaded to my ftp folder.
I got the following code:
HTML:
<div id="drop_zone">
<p>Drop Here</p>
</div>
<form enctype="multipart/form-data" id="yourregularuploadformId">
<input type="file" name="files[]" multiple="multiple">
</form>
JS:
$(function() {
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
etc.... dropping part
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
files = evt.dataTransfer.files;
uploadFile(files);
etc... getting file to my method
function uploadFile(droppedFiles){
// add your files to the regular upload form
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) { // checks if any files were dropped
for(f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
uploadFormData.append("files[]",droppedFiles[f]); // adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "php/uploadFile.php", // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
}
Got the above code from another topic. (alert(uploadFormData); -> gives me a Formdata aboject)
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"],
"ftp/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
Can't make it work :<
The message i get from the callback function in my JS is:
Undefined index: file
Your PHP code needs to iterate over all of the files in the request. Based on your javascript, your PHP code should look something like this:
foreach ($_FILES["files"] as $file) {
move_uploaded_file($file['tmp_name'], $target);
}
The $target variable must point at the local destination for your file. See the PHP manual for more details.

Categories