Stream php output to javascript callback - javascript

I am making a javascript XMLHttpRequest() request to execute some php in the background. Now I know the callback will only receive the first response from php. How can I get output to send back what php is echoing as it is happening to show it on the main page as php is running in the background?
javascript
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var phpResponse = this.responseText
// i know this will only be the first thing echoed by php
}
};
xhttp.open("GET", "scan.php?scanRoot=yes", true);
xhttp.send();
php run in the back ground
function rootDirFileSort($scanDir,$getID3){
//Sort stray files in root directory. Put them in a dir named by artist
$printFix = str_repeat(" ", 8157);
$files = array_diff(scandir($scanDir), array('.', '..'));
//Get files in dir. Only get flac and mp3 files
$FilesArray = array_diff(scandir($scanDir), array('.', '..'));
$FilesArray = preg_grep('~\.(flac|mp3)$~', $FilesArray);
$files = array_values($FilesArray);
foreach ($files as $file){
$file_Basename = basename($file);
// Get the metadata from file. Returns as an array
$metaDataArray = $getID3->analyze($scanDir.$file);
//Check for ID3v1 metadata container
if (isset($metaDataArray['tags']['id3v1']['artist'][0])){
$artist = $metaDataArray['tags']['id3v1']['artist'][0];
$artist = str_replace(array('.',',','?','/','\\','$'), array('','','','','',''), ucwords($artist));
}else{
$artist = '';
}
//Check for vorbis comment metadata container
if(isset($metaDataArray['tags']['vorbiscomment']['artist'][0])){
$artist = $metaDataArray['tags']['vorbiscomment']['artist'][0]; echo $artist;
$artist = str_replace(array('.',',','?','/','\\','$'), array('','','','','',''), ucwords($artist));
}else{
$artist = '';
}
//If the artist meta tag is present move the file
if(!empty($artist)){
//Check if diretory exists before making one
if(!is_dir($scanDir.$artist)){
//If file DOES NOT exist
mkdir($scanDir.$artist, 0755, true);
rename($scanDir.$file, $scanDir.$artist.'\\'.$file);
echo $file.'<br>'.$artist.'<br>Moved To: '.$scanDir.$artist.'\\'.$file.'<br><br>'.$printFix;
}else{
//If file exists
rename($scanDir.$file, $scanDir.$artist.'\\'.$file);
echo $file.'<br>'.$artist.'<br>Moved To: '.$scanDir.$artist.'\\'.$file.'<br><br>'.$printFix;
}
}else{
//Put failures in an array to show which failed when done
$notProcessed[] = array('musicFile'=>$file_Basename);
}
}
//Show all the failures if they exist
if(count($notProcessed) >= 1){
echo '<strong>***** These items failed as they don\'t contain ID3v1, ID3v2 or Vorbis Comment meta container. Manually process directories. *****</strong><br><br>';
foreach($notProcessed as $value){
echo '<strong>File:</strong> '.$value['musicFile'].'<br><br>'.$printFix;
}
}
echo '<br><br>------------------------- Root File Scan Finished! -------------------------'.$printFix;
}

Related

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

appending a text file in php using JSON, not working and no error message being displayed

I have a JavaScript function which is called with a parameter when someone clicks a div. The JavaScript function makes a JSON string out of the parameter and then makes a XMLHttpRequest (AJAX) to the php file that takes this JSON string, finds the number within the JSON string and then stores the number in a text file on the server.
However when i run this on my server, no number is appended to the text file and nothing seems to happen. No error message is displayed. The "Thank You!" message does get displayed in the div, which means the readystate does become 4 and the status does become 200.
The html code that calls the JavaScript function with a parameter:
<li id="star1" onclick="saveRating(1)"><i class="fa fa-star" aria-hidden="true"></i></li>
The javaScript function that creates a JSON string and calls the php file:
function saveRating(num){
obj = { "score":num };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//a "Thank You!" message is displayed in the div
}
};
xmlhttp.open("GET", "php/storeRating.php?x=" + dbParam, true);
xmlhttp.send();
}
The PHP file that opens a text file, searches the JSON string for a number and appends the number to the text file:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false); //gets the param that was sent and stores it in $obj
//opens text file and sets to appending the file.
$myfile = fopen("ratingNumbers.txt", "a");
//goes through string and if it finds a number it adds it to the text file.
while(false !== ($char = fgetc($obj))){
if($char == 1){
fwrite($myfile, $char);
}if($char == 2){
fwrite($myfile, $char);
}if($char == 3){
fwrite($myfile, $char);
}if($char == 4){
fwrite($myfile, $char);
}if($char == 5){
fwrite($myfile, $char);
}
}
//closes the file
fclose($myfile);
?>
[edit] The text file and PHP file both have write permissions.
I found 2 mistakes on your script.
Place the file handle in given line
while(false !== ($char = fgetc($myfile))){
$myfile = fopen("ratingNumbers.txt", "a+"); // Open for reading and writing;

Need Help Handling a XML HTTP File Upload Request

So, I looked up a tutorial for uploading and sending files to a server with an XML HTTP Request. I followed the tutorial, however, I think I must be missing something. While the file appears to be uploaded and sent, nothing in the "handler" file is ever accessed. Is there a PHP function I need to write to process it? For context, here is what I wrote:
$(document).ready(function()
{
$('#upload-button').click(function(event)
{
$('#upload-button').removeClass("btn-danger");
});
$( "#report-form" ).submit(function( event )
{
var form = document.getElementById('report-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
event.preventDefault(); // Stop the event from sending the way it usually does.
uploadButton.value = 'Submitting...'; // Change text.
var files = fileSelect.files;
var maxfiles = <?php echo $config['Report_MaxFiles'] ?>;
var mfs = <?php echo $config['Report_MaxFileSize'] ?>;
if(files.length > maxfiles) // Make sure it's not uploading too many.
{
uploadButton.value = 'You uploaded too many files. The limit is ' + maxfiles + '.'; // Update button text.
$('#upload-button').addClass('btn-danger'); // Make the button red, if so.
return;
}
var formData = new FormData(); // Make a "form data" variable.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
if(file.size / 1000 > mfs)
{
uploadButton.value = 'One of the files is too big. The file size limit is ' + (mfs) + 'kb (' + (mfs / 1000) + 'mb).';
$('#upload-button').addClass('btn-danger');
return;
}
formData.append('files[]', file, file.name); // Not really sure what this does, to be honest,
// but I think it makes a file array.
}
var xhr = new XMLHttpRequest(); // Construct an XML HTTP Request
xhr.open('POST', 'assets/class/FileHandler.php', true); // Open a connection with my handler PHP file.
xhr.onload = function ()
{
if (xhr.status === 200)
{
uploadButton.value = 'Files Submitted!'; // NOTE: I do get this message.
}
else
{
uploadButton.value = 'An error occurred.';
$('#upload-button').addClass("btn-danger");
}
};
xhr.send(formData); // I think this is where it dies.
});
});
At the "send(formData)" line, I'm not actually sure if it's sending. Do I set up some sort of listener in FileHandler.php that is activated when the files are sent via XML HTTP request? Or more specifically, how to I save the uploaded files to the server using my FileHandler.php file?
EDIT: I haven't been able to come up with any other PHP code in the FileHandler.php file than this, which I thought might be called when the form is sent (but it isn't):
EDIT 2: Okay, now I have something, but it isn't working (didn't expect it to). I think I may be using the variables wrong:
<?php
$uploaddir = 'data/reports/uploads/' . $_POST['id'] . "/";
$uploadfile = $uploaddir . basename($_FILES['files']['name']);
echo "<script>console.log('RECEIVED');</script>";
echo '<pre>';
if (move_uploaded_file($_FILES['files']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
It's not saving the file to the directory, nor is it printing the script message. How do I get my report.php file to execute these things in FileHandler.php?
Thanks to the help and patience of #Florian Lefèvre, I got it fixed. :)
The problem was with the path. It wasn't locating the path to the folder data/uploads/ and wasn't making the directory. Here is what I did:
$uploaddir = '../../data/reports/uploads/' . $_POST['id'] . "/";
echo "NAME: " . $_FILES['files']['name'][0] . "\n";
foreach($_FILES['files']['name'] as $filenumber => $filename)
{
$uploadfile = $uploaddir . basename ($filename);
echo "UploadDir " . $uploaddir . "\n";
echo "UploadFile " . $uploadfile . "\n";
echo '<pre>';
echo "MKDir for UploadDir which is: ". $uploaddir . "\n";
mkdir ($uploaddir);
if (move_uploaded_file ($_FILES['files']['tmp_name'][$filenumber], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print "</pre>";
}
var_dump ($_FILES);
I haven't gotten rid of some of the debug stuff yet, but that's the general solution.

Multiple files in to folder

Hello I have a view file and controller, what makes multiple inputs where I can upload files in to folder, but its uploading only one file in to folder. I know what is problem, but I dont know how to fix this or how to do this.
My Controller:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
//print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
My View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
And this script what Im using in View :
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I think that, the problem is in input names. If Im doing more inputs, then the inputs names are same, and thanks to this its uploading only one file in to webroot/files folder, but I want these all.
Can anybody help me or give me some tips.
Thanks !
Here is someone with almost exactly the same issue as you have:
Create multiple Upload File dynamically
Try doing the same. I haven't programmed PHP for quite some time, but I guess you should replace data[files] to just data[], so it creates a new array item for each field. Now you are giving each field the same name.
Then you can loop over them in your controller by using:
foreach($_FILES['data'] as $file){
//do stuff with $file
}
EDIT 2:
As you are saying, you want to upload the files (not to a db). So I guess this should work:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $file)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
}
Try this function:
function multi_upload($file_id, $folder="", $types="") {
$all_types = explode(",",strtolower($types));
foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
if(!$_FILES[$file_id]['name'][$key]){
$return[$key]= array('','No file specified');
continue;
}
$file_title = $_FILES[$file_id]['name'][$key];
$ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
$ext = strtolower($ext_arr); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,5);
$file_name = $uniqer . '_' . $file_title;//Get Unique Name
if($types!=''){
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
$return[$key]= array('',$result);
continue;
}
}
//Where the file must be uploaded to
if($folder) $folder .= '/';//Add a '/' at the end of the folder
$uploadfile = $folder . $file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
}
else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
}
else {
#chmod($uploadfile,0777);//Make it universally writable.
}
}
$return[$key]=array($file_name,$result);
}
return $return;
}
html: <input type="file" name="data_file[]" id="uploadFilefiles">
Call by multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")

PHP move_uploaded_file uploads only one file

I'm testing uploads on 3 files on my desktop test.xlsx, test - Copy.xlsx, and test - Copy (2).xlsx. My PHP script is breaking at the line where my move_uploaded_files statement is. I get the error move_uploaded_file(uploads/test - Copy.xlsx): failed to open stream: No such file or directory. BUT test - Copy (2).xlsx is uploaded when I check my uploads folder. My PHP is as follows:
foreach($_FILES['file']['name'] as $key=>$value){
$fileName = $_FILES['file']['name'][$key];
$fileTmpLoc = $_FILES['file']['tmp_name'][$key];
$fileErrorMsg = $_FILES['file']['error'][$key];
$type = $_FILES['file']['type'][$key];
if(){
//validation
} else{ //if validated
if(move_uploaded_file($fileTmpLoc, 'uploads/'.$fileName)){
//do more stuff
} else{
echo "Upload failed.";
}
}
}
The //do more stuff actually runs once for test - Copy (2).xlsx (the only file uploaded successfully). My JS script is below but I doubt that's the part that's breaking since when I print_r($_FILES) in PHP, all files appear in the output.
var upload = function(event){
var file = document.getElementById('file').files;
var data = new FormData();
for (i=0; i<file.length; i++){
data.append('file[]', file[i]);
}
var request = new XMLHttpRequest();
request.addEventListener('load', completeHandler, false);
request.addEventListener('error', errorHandler, false);
request.addEventListener('abort', abortHandler, false);
request.open('POST', 'php/excel_upload_read.php');
request.send(data);
};
What am I doing wrong?
Looks like you are using the multi-dimensional array in the wrong order. Try this:
foreach($_FILES['file'] as $key=>$value){
$fileName = $_FILES['file'][$key]['name'];
$fileTmpLoc = $_FILES['file'][$key]['tmp_name'];
$fileErrorMsg = $_FILES['file'][$key]['error'];
$type = $_FILES['file'][$key]['type'];
...
}
The problem is the way $_FILES global is structured, it does not let you iterate easily.
You can use this function it s meant to reorganize the data structure
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Then you can use foreach easily:
if(isset($_FILES['file']['tmp_name'], $_POST)) {
$files = reArrayFiles($_FILES['file']);
foreach ($files as $file) {
$temp = $file['tmp_name'];
$path = 'uploads/'.$file['name'];
if(move_uploaded_file($temp, $path)){
echo 'Upload succesful';
}else{
echo 'failed to upload';
}
}
}else{
echo 'file not uploaded';
}
This function reArrayFiles was posted by someone in the PHP documentation:
http://php.net/manual/en/features.file-upload.multiple.php

Categories