I have a javscript function below which displays a message depending on on the result:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
return true;
}
The code below always displays the message "The file was uploaded successfully!"
<?php
$destination_path = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/")."ImageFiles";
$result = 0;
$target_path = $destination_path . basename( $_FILES['fileImage']['name']);
if(move_uploaded_file($_FILES['fileImage']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
<script type='text/javascript' language='javascript'>
window.top.window.stopImageUpload(1);
</script>
But if I change the last line to this below then it always displays the message "There was an error during file upload!". Why is this and how can it be fixed so it displays the right message depending on the result?
<script language="javascript" type="text/javascript">
window.top.window.stopImageUpload(<?php echo $result; ?>);
</script>
Find out what this <?php echo $result; ?> actually renders to. Just look in the page source.
Most likely, it will be 0. Then try to find out why move_uploaded_file returns false. Probably, there's something wrong happening while moving the file.
Related
What began here: PHP finding file where post INCLUDES portion of filename
I am trying to finish with this question.
Basically, now that I am able to post a variable to a PHP process, then use that process to find a file in a directory, I now need to be able to download the file if it exists.
Quick recap, after the user has entered a voyage number and the datatable has returned a list of voyages, the user then clicks the link, which is where I'll begin the code:
$('.voyageFileCall').on('click', function()
{
var voyage = $(this).attr('data-voyage');
$.post('fileDownload.php', {voyage:voyage}, function(data)
{
// here is where I need to where either display the file doesn't exist
// or the file downloads
});
});
The process 'fileDownload.php' looks like this:
<?php
if($_POST['voyage'] == true)
{
$voyage = $_POST['voyage'];
$files = scandir("backup/");
if(count($files) > 0)
{
$fileFound = false;
foreach($files as $file)
{
if((preg_match("/\b$voyage\b/", $file) === 1))
{
// I'm guessing the download process should happen here
echo "File found: $file \n"; // <-- this is what I currently have
$fileFound = true;
}
}
if(!$fileFound) die("File $voyage doesn't exist");
}
else
{
echo "No files in backup folder";
}
}
?>
I tried to use the answer found here: Download files from server php
But I'm not exactly sure where I should put the headers, or if I need to use them at all.
The quick solution which i can suggest you is: return path to file if it is exist, and return false if file doesn't exist.
After that in your JS code you can check, if your "data" == false, you can throw an error "file doesn't exist", and if it is not "false", you can call document.location.href = data; - it will redirect your browser to the file and it will be downloaded
Why don't you simply use download attribute:
<?php
if($_POST['voyage'] == true)
{
$voyage = $_POST['voyage'];
$files = scandir("backup/");
if(count($files) > 0)
{
$fileFound = false;
foreach($files as $file)
{
if((preg_match("/\b$voyage\b/", $file) === 1))
{
// I'm guessing the download process should happen here
echo 'File found: <a href="' . $file . '" download>' . $file . '</a> \n'; // <-- this is what I currently have
$fileFound = true;
}
}
if(!$fileFound) die("File $voyage doesn't exist");
}
else
{
echo "No files in backup folder";
}
}
?>
If you really want to use JavasScript to start download then use style="display:none;" for <a> and then in JS just click it:
echo 'File found: <a id="myDownload" style="display:none;" href="' . $file . '" download>' . $file . '</a> \n';
and call it:
$('.voyageFileCall').on('click', function()
{
var voyage = $(this).attr('data-voyage');
$.post('fileDownload.php', {voyage:voyage}, function(data)
{
if(document.getElementById("myDownload")){
document.getElementById("myDownload").click();
}else{
console.log("file does not exist");
}
});
});
I have some simple code to upload file using drop zone. It's uploading the file just fine but for some reason it doesn't echo "done uploading" at the end of the code.
Am I missing something obvious here?
<script type="text/javascript">
Dropzone.options.myDropzone = {
addRemoveLinks: true,
removedfile: function(file) {
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
</script>
<div id="dropzone">
<form id="myDropzone" action="#" class="dropzone" id="demo-upload">
<div class="dz-message">
Drop files here or click to upload.<br />
</div>
</form>
</div>
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
move_uploaded_file($tempFile,$targetFile); //6
echo "done uploading";
}
?>
Try this:
if(move_uploaded_file($tempFile,$targetFile)) {
echo "done uploading";
} else {
echo 'error!';
}
You can activate error_reporting to see the error from move_uploaded_file
Edit: Ugly hack, just for testing. DO NOT USE THIS IN PRODUCTION!!!
if(move_uploaded_file($tempFile,$targetFile)) {
$_SESSION["success"] = "upload done";
echo $_SESSION["success];
} else {
echo 'error!';
}
Since Dropzone uses AJAX to post requests to server you will not see the response line ordinary PHP response when you echo something.
Try in this way
<script type="text/javascript">
Dropzone.options.myDropzone = {
...
success: function(file, response){
alert(response); // Just to test, you can remove this
// Do what you want
// Like:
if(response == "success") {
// Uploaded ok
} else {
// Failed to upload
}
}
};
</script>
In this way after successful AJAX request you can catch the response and do whatever you want.
Ofcoruse, like #tftd said, You need to wrap move_uploaded_file like:
if(move_uploaded_file(...)) {
// done uploading
echo json_encode('success');
} else {
// failed moving
echo json_encode('error');
}
I am trying to add a URL to a image file name before uploading it to database. It seems that nothing worked out. Have searched Google and Stackoverflow. I guess I am missing something. Here's my code, please find the comment 'here is the issue'
I have a variable $value which pulls latest ID from database.
All I have to achieve is add path to the variable: "http://example.com/location/something/"
Desired Output : the image should be renamed as http://example.com/location/something/1.jpg
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$title = $_POST['title'];
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$folder="uploads/";
function execute_scalar($sql,$def="") {
$rs = mysql_query($sql) or die("bad query");
if (mysql_num_rows($rs)) {
$r = mysql_fetch_row($rs);
mysql_free_result($rs);
return $r[0];
mysql_free_result($rs);
}
return $def;
}
$value = execute_scalar("select max(ID)+1 from tablename");
$newname = "$value.".$ext; // Here is the issue.
$newname = "http://example.com/location/something/"."$value.".$ext; //did not work
$newname = "http://example.com/location/something/ $value.".$ext; //did not work
// even tried assingning url to variable still did not worked
if(move_uploaded_file($file_loc,$folder.$newname))
{
$sql="INSERT INTO tablename(id,title,image)VALUES('$value','$title','$newname')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
is it something with URL?
Try moving your quotes like below:
$newname = "http://example.com/location/something/". $value ."." . $ext;
The problem is that you are not allowed to use / (slash) in your file name, because it acts as directory path.
I found a solution :
$newname = "http:\\//www.example.com\/location\/something\/\/$value.".$ext;
It is working :D
I am trying to integrate fine uploader [ Jquery wrapper ] for my PHP project. In that, i am trying to upload a 25MB file by using chunking option.
But what is happening here is, It chunks file and stores as blob0, blob1, blob2...
I want to my original file to be stored in the location. But here, the chunks get stored with a different name. What i have tired so far is,
<div id="jquery-wrapped-fine-uploader"></div>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.fineuploader-3.5.0.js"></script>
<script>
$(document).ready(function () {
$('#jquery-wrapped-fine-uploader').fineUploader({
debug: true,
request: {
endpoint: 'upload.php',
},
chunking: {
enabled: true,
partSize: 2000000,
paramNames: {
partIndex: 'qqpartindex',
partByteOffset: 'qqpartbyteoffset',
chunkSize: 'qqchunksize',
totalFileSize: 'qqtotalfilesize',
totalParts: 'qqtotalparts',
filename: 'qqfile'
}
}
});
});
</script>
PHP
if ($_FILES["qqfile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["qqfile"]["error"] . "<br>";
} else {
$partIndex = $_POST["qqpartindex"];
$fileName = $_POST["qqfile"];
move_uploaded_file($_FILES["qqfile"]["tmp_name"], "data/" . $_FILES["qqfile"]["name"].$partIndex);
$result['success'] = true;
echo json_encode($result);
}
I don't know where i went wrong and what i have missed. Please someone guide me.
The point is, this is a feature of the fine uploader. The chunks are given as separate files so that in case your upload gets corrupted, you would have a way to compare and discard chunks that are invalid. If you wish to just get the file, what you need is the following:
if ($_FILES["qqfile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["qqfile"]["error"] . "<br>";
} else {
$partIndex = $_POST["qqpartindex"];
$fileName = $_POST["qqfile"];
move_uploaded_file($_FILES["qqfile"]["tmp_name"], "data/" . $_FILES["qqfile"]["name"].$partIndex);
// INSERT CODE HERE TO CHECK THE INTEGRITY OF "data/" . $_FILES["qqfile"]["name"].$partIndex
$file = fopen($filename, 'a');
$content = file_get_contents("data/" . $_FILES["qqfile"]["name"].$partIndex);
if (fwrite($file, $content)) $result['success'] = true;
fclose($file);
echo json_encode($result);
}
, where $filename is the name of the file you are uploading. I would tell you how to get it through this code, but it's probably easier to define it upstream. Also, depending on your upstream code, it will probably be more memory-efficient to do the fopen at the beginning of the upload, and fclose at the end of your code (e.g.
$file = FALSE;
if ($partIndex == 0) $file = fopen("filename");
instead of the line $file = fopen($filename, 'a'); But, in this case you need to fclose($file); only at the end of the upload (or not at all, it will be fclosed once the page loads). But once again, without seeing the rest of your code I cannot know what will work best in this particular case.
I have a JavaScript function below where it displays a message after file uploading is complete:
function stopVideoUpload(success) {
var namevideofile = $('.fileVideo').val();
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listVideo').append(namevideofile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script which is on another page which successfully uploads the files:
if( file_exists("VideoFiles/".$_FILES['fileVideo']['name'])) {
$parts = explode(".",$_FILES['fileVideo']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileVideo']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>
Now except having var namevideofile to retrieve the value from the file input value (.fileVideo is the class for the file input), what I want it to do is that when the uploading is complete, the name given to file in the server would be var namevideofile. So if I have 2 files known as video.png, as I stated in my php code that if file exists then add a number to end of file name so that would create video.png and video1.png in server.
So when I append namevideofile, it should display video.png and video1.png after uploading is completed for both files. The problem with var namevideofile = $('.fileVideo').val();, is that it displays both file names as video.png which is incorrect.
So does anyone know how to change var namevideofile so that it retrieves the file name from the server after uploading? The issue is that the php script is on a separate page (videoupload.php) to the JS function (QandATable.php) so does ajax need to be involved here or not.
Anyone who could provide an example of how this can be coded would be very helpful to me :)
you can echo and store the value in a javaScript variable:
var namevideofile = <php echo $filename; ?>;