saving ms word docx file using edraw in php - 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);
?>

Related

How do I copy a file thant contains random filename

How do I copy files in a directory with filename contains.. see sample below
file_123_XXXXXX.zip where XXXXXX is a random numbers..
I want to copy file_123_XXXXXX.zip from server to same file name to my local folder
the code is working operational if I set the filename exactly the same in the server but what if the file name randomly changes everyday.
thanks in advance..
here is my code:
include("./config.php");
$local_file1 = 'C:\Destination\file_123_XXXXXX.zip'; //how to copy the original filename XXXXX
if(file_exists($local_file1))
{
echo "
$('#getUpdts').attr('disabled','disabled')
.addClass('ui-state-disabled');
$('#proc').removeAttr('disabled')
.removeClass('ui-state-disabled');
";
echo "infoMsg('File is already downloaded..')";
}
else
{
$ftp_user = ftp_user;
$ftp_pw = ftp_pw;
$conn_id = ftp_connect('192.xxx.xxx.xxx') or die("Couldn't connect to 192.xxx.xxx.xxx");
$server_file1 = "/fromlocation/file_123_XXXXXX.zip"; //the filename with random that i want to get
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pw);
if(!file_exists($local_file1))
{
$contents = ftp_size($conn_id, $server_file1);
if ($contents >0) {
if (ftp_get($conn_id, $local_file1, $server_file1, FTP_BINARY)) {
echo "infoMsg('Successfully downloaded');";
} else {
echo "alertMsg('Unable to download');";
}
}else{
echo "alertMsg('Does not exist.');";
}
}
else
{
echo "alertMsg('does not exists');";
}
// close the connection
ftp_close($conn_id);
}
List the directory and match the filename using preg_match()
ftp_chdir($conn_id, "/fromlocation/");
foreach (ftp_nlist($conn_id, ".") as $server_file1) {
if (!preg_match('/^file_123_\d{6}\.zip/i', $server_file1)) continue;
if (is_file($server_file1)) continue;
// then the rest of your code...
$contents = ftp_size($conn_id, $server_file1);
if ($contents > 0) {
if (ftp_get($conn_id, $local_file1, $server_file1, FTP_BINARY)) {
echo "infoMsg('Successfully downloaded');";
} else {
echo "alertMsg('Unable to download');";
}
} else {
echo "alertMsg('Does not exist.');";
}
}
As I proposed in comment you could consider :
Connect to the server
Find the last modified file in your server file directory
Check IF (Local Side) the file already exists
Function's Code :
function get_last_modified_file($dir)
{
$path = $dir;
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read()))
{
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime)
{
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
return $latest_filename;
}
Using your code - It shoud looks like :
include("./config.php");
// Copy - Pasterino the function get_last_modified() here
// Fill variables $server_dir & $local_dir
$ftp_user = ftp_user;
$ftp_pw = ftp_pw;
$server_dir = "the path we will search into the last file/";
$local_dir = " the destination path/";
$conn_id = ftp_connect('192.xxx.xxx.xxx') or die("Couldn't connect to 192.xxx.xxx.xxx");
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pw);
// Get last modified file
$last_ctime_file = get_last_modified_file($server_dir);
if(file_exists($local_dir . $last_ctime_file"))
{
// We don't download it / echo Warning, etc..
echo "blalbllalba";
}
else
{
// We download it - Same code you used
$contents = ftp_size($conn_id, $server_dir . $last_ctime_file);
if ($contents >0)
{
if (ftp_get($conn_id, $local_dir . $last_ctime_file,
$server_dir . $last_ctime_file, FTP_BINARY))
echo "infoMsg('Successfully downloaded');";
else
echo "alertMsg('Unable to download');";
}
else
echo "alertMsg('File is empty.');";
}
ftp_close($conn_id);
Source : Stackoverflow : Get the lastest file in a directory

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

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);
?>

Uploading a File from a Remote Server to an FTP Server with PHP

How can I upload a remote file from a link for example, http://site.com/file.zip to an FTP server using PHP? I want to upload 'Vanilla Forum Software' to the server and my mobile data carrier charges high prices, so if I could upload the file w/o having to upload it from my mobile I could save money and get the job done too.
Made you this function:
function downloadfile($file, $path) {
if(isset($file) && isset($path)) {
$fc = implode('', file($file));
$fp = explode('/', $file);
$fn = $fp[count($fp) - 1];
if(file_exists($path . $fn)) {
$Files = fopen($path . $fn, 'w');
} else {
$Files = fopen($path . $fn, 'x+');
}
$Writes = fwrite($Files, $fc);
if ($Writes != 0){
echo 'Saved at ' . $path . $fn . '.';
fclose($Files);
}
else{
echo 'Error.';
}
}
}
You may use it like this:
downloadfile("http://www.webforless.dk/logo.png","folder/");
Hope it works well, remember to Chmod the destination folder 777.
((If you need it to upload to yet another FTP server, you could use one of the FTP scripts posted in the other comments))
Best regards. Jonas
Something like this
$con=ftp_connect("ftp.yourdomain.com");
$login_result = ftp_login($con, "username", "password");
// check connection
if ($conn_id && $login_result) {
// Upload
$upload = ftp_put($con, 'public_html/'.$name, "LOCAL PATH", FTP_BINARY);
if ($upload) {
// UPLOAD SUCCESS
}
}
More info: http://php.net/manual/en/function.ftp-put.php
A ) download the file via an url :
$destination = fopen("tmp/myfile.ext","w");
//Myfile.ext is an example you should probably define the filename with the url.
$source = fopen($url,"r");
while (!feof($source)) {
fwrite($destination,fread($source, 8192));
}
fclose($source);
fclose($destination);
B) Upload the file on FTP :
$file = 'tmp/myfile.ext';
$fp = fopen($file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
echo "UPLOAD OK";
} else {
echo "ERROR";
}
ftp_close($conn_id);
fclose($fp);
This just a quick example , there is probably lot of improvement which can be done on this code , but the main idea is here.
Note : if you have a dedicated server it's probably faster and easier to download the file with a call to wget.
More info on FTP can be found in the doc
Simply:
copy('ftp://user:pass#from.com/file.txt', 'ftp://user:pass#dest.com/file.txt');
The PHP server will consume bandwidth upload and download simultaneously.
Create a php script in a web-accessible folder on your target server, change the values of $remotefile and $localfile, point your browser to the script url and the file will be pulled.
<?php
$remotefile="http://sourceserver.com/myarchive.zip";
$localfile="imported_archive.zip";
if(!copy($remotefile, $localfile)) {
echo("Transfer Failed: $remotefile to $localfile");
}
?>

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;
}
}

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//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'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //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 {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories