Connecting Windows 8 applications with Apache Server : (Background transfers in Windows 8) - php

I have some problems during the upload of file on windows store application. I got Status 200, but when I check the server there's no file uploaded..I'm using apache server
I've checked the Sample of Microsoft Background Transfer sample but it work with a ASP .Net server.
any solution ?

I need to upload one single file at a time, It works for me, let me know:
upload.php:
<?php
$target = "data/";
$target = $target . basename( $_FILES['Filename']['name']) ;
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
C# code:
private async void StartMultipartUpload_Click(object sender, RoutedEventArgs e)
{
Uri uri;
if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
{
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
return;
}
// Verify that we are currently not snapped, or that we can unsnap to open the picker.
if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
{
rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
return;
}
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
IReadOnlyList<StorageFile> files = await picker.PickMultipleFilesAsync();
if (files.Count == 0)
{
rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
return;
}
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
for (int i = 0; i < files.Count; i++)
{
BackgroundTransferContentPart part = new BackgroundTransferContentPart("Filename", files[i].Name);
part.SetFile(files[i]);
parts.Add(part);
}
BackgroundUploader uploader = new BackgroundUploader();
UploadOperation upload = await uploader.CreateUploadAsync(uri, parts);
String fileNames = files[0].Name;
for (int i = 1; i < files.Count; i++)
{
fileNames += ", " + files[i].Name;
}
Log(String.Format("Uploading {0} to {1}, {2}", fileNames, uri.AbsoluteUri, upload.Guid));
// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
}
I used the same code of The SDK sample. data/ folder is in the same folder of upload.php and my Uri is http://mySite/myApp/upload.php

Ok so I found a full solution. Basically you need to upload as multipart on your SDK Samples ( doesn't matter if it is C# or C++ ) and the key is to the php file. Here is my PHP file that processes all of the selected files. Works as a charm! Also if you get error 1 it means that in your php.ini the maximum file upload size is too small! So look out for that too. Hope it helps, it surely took me some effort to get this done.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
foreach ($_FILES as $name) {
if ($_FILES[$name]["error"] > 0){
fwrite($fh, "Error: " . $_FILES[$name]['error'] . " on file: " . $_FILES[$name]['name']); // log the error
}
$target = "data/";
$target = $target . basename( $_FILES[$name]['name']) ;
if(move_uploaded_file($_FILES[$name]['tmp_name'], $target))
{
echo "The file ". basename( $_FILES[$name]['name']). " has been uploaded"; // succes, do whatever you want
}
else {
fwrite($fh, "File movement error on file: " . $_FILES[$name]['name']); // log the error
}
}
fclose($fh);
?>

Related

Upload fails "move uploaded file"

First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.

PHP SSH move file to another directory [duplicate]

I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'

Issue in secure file upload script using command line AV

I have a secure file upload function that's part of my website
and I'm using an antivirus to help me checking the file a user trying to upload.
This is my uploadprocess.php file
$target_tmp = "D:\avscan\u\\";
$file = basename( $_FILES['uploaded_file']['name']) ;
if($file != "")
$_SESSION['file'] = $file;
$target = 'C:\xampp\htdocs\ssd\Uploads\\';
$file_path = $target_tmp.$file;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
$safe_path = escapeshellarg($file_path);
$command = 'scancl'. $safe_path. ' --stdout';
$out = '';
$int = -1;
$output = exec($command, $out, $int);
echo "The output is" .$output;
echo $int;
exit(0);
//Checking for Virus.
if ($int == 0) {
$target = $target.$file;
//echo $target; exit(0);
copy($file_path, $target);
$uploaded = "The file ". $_SESSION['file']. "has been uploaded";
$clean = 'File is Clean.';
$_SESSION['status'] = $clean;
$_SESSION['upload'] = $uploaded;
header("location: ../upload.php");
exit(0);
}
// File is a virus.
else {
$mal = 'Contains Malware';
$deny_up = "Unable to Upload Your File!";
$_SESSION['status'] = $mal;
$_SESSION['upload'] = $deny_up;
header("location: ../upload.php");
exit(0);
}
}
else
{
echo "SORRY, There was a Problem Uploading Your File."; exit(0);
$err_upload = "SORRY, There was a Problem Uploading Your File.";
$_SESSION['err'] = err_upload;
header("location: ../upload.php");
exit(0);
}
It prints me value of 1 for the $int for all files (malicious and non ones) This is my second try with a different AV now I'm using Avira and before I was using clamscan
can someone share me some hints, and tell me what's going on
PS the system is installed on XAMPP if that makes any difference
Can you be more specific about what's not working here? In theory what you doing seems fine at least for ClamAV since it has these return codes (from man clamscan):
RETURN CODES
0 : No virus found.
1 : Virus(es) found.
2 : Some error(s) occured.
Maybe it want to log the output of the exec call, if you are not getting the exit code you expect the reason should be in the output (like missing a command line flag).

saving ms word docx file using edraw in php

I have used the following code for saving open docx file.
javascript:
function SavetoServer(){
OA1.Save();
OA1.CloseDoc();
OA1.HttpInit();
OA1.HttpAddPostFile("C:\wamp\www\rte\sample2.docx");
document.OA1.HttpPost("http://localhost/rte/actor2.php");
}
php code "actor2.php"
<?php
header("http/1.1 200 OK");
$handle = fopen($_FILES['trackdata']['name'],"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>
The file is not saving when we changed in browser. Can anyone see a problem with this?
The HttpAddPostFile can add only the file from the remote website. It does work for the local disk file.
function SavetoServer()
{
if(document.OA1.IsOpened)
{
document.OA1.SetAppFocus();
document.OA1.HttpInit();
var sFileName = document.OA1.GetDocumentName();
document.OA1.HttpAddPostOpenedFile (sFileName); //save as the same file format with the sFileName then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 16); //save as docx file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 0); //save as doc file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, -4143); //save as xls file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 51); //save as xlxs file then upload
document.OA1.HttpPost("upload_weboffice.php");
if(document.OA1.GetErrorCode() == 0 || document.OA1.GetErrorCode() == 200)
{
var sPath = "Save successfully! You can download it at http://www.ocxt.com/demo/" + sFileName;
window.alert(sPath);
}
else
{
window.alert("you need enable the IIS Windows Anonymous Authentication if you have not set the username and password in the HttpPost method. you need set the timeout and largefile size in the web.config file.");
}
}
else{
window.alert("Please open a document firstly!");
}
}
upload_weboffice.php
<?php
$sql = sprintf("username=%s passwd=%s param=%s", $_POST['user'],$_POST['password'],$_POST['param']);
echo $sql;
$filecount = count($_FILES["trackdata"]["name"]);
echo "\r\n";
echo "file account:";
echo $filecount;
echo "\r\n";
$sql = sprintf("file=%s size=%s error=%s tmp=%s", $_FILES['trackdata']['name'],$_FILES['trackdata']['size'],$_FILES['trackdata']['error'],$_FILES['trackdata']['tmp_name']);
echo $sql;
echo "\r\n";
$filen = $_FILES['trackdata']['name'];
//$filen = iconv("UTF-8", "GBK", $filen);
$handle = fopen($filen,"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
echo $data;
//file_put_contents($handle, "\xEF\xBB\xBF". $data);
//fwrite($handle,pack("CCC",0xef,0xbb,0xbf));
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>

Passing uploaded files to another part of the script for onward processing

I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}

Categories