public static function uploadFile($access_token, $uploadFile, $fileName, $config) { if (!isset($access_token)) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth(\HttpReceiver\HttpReceiver::get('userId', 'int'), $config)); } if (!file_exists($uploadFile)) { return array('status' => 'error', 'fileNotExist'); } $dbxClient = new dbx\Client($access_token, "PHP-Example/1.0"); $f = fopen($uploadFile, "rb"); try { if (!isset($fileName) || strlen($fileName) == 0 || $fileName == '0') { $tmp = explode('/', $uploadFile); $fileName = $tmp[sizeof($tmp) - 1]; } else { $fileName .= '.pdf'; } $result = $dbxClient->uploadFile("/" . $config['SAVE_FOLDER'] . "/" . $fileName, dbx\WriteMode::add(), $f); } catch (Exception $e) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth(\HttpReceiver\HttpReceiver::get('userId', 'int'), $config)); } fclose($f); if (!isset($result) || !isset($result['size'])) { return array('status' => 'error', 'msg' => 'refreshToken'); } else { return array('status' => 'ok'); } }
public function upload($article_id) { $accessToken = Yii::$app->params['accessToken']; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); if ($this->validate()) { $image_name = Yii::$app->security->generateRandomString(); $this->file->saveAs('uploads/' . $image_name . '.' . $this->file->extension); $file_name = 'uploads/' . $image_name . '.' . $this->file->extension; $f = fopen("{$file_name}", "rb"); $result = $dbxClient->uploadFile("/{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f); fclose($f); $src = $dbxClient->createShareableLink($result['path']); $src[strlen($src) - 1] = '1'; $image = new Image(); $image->image_name = $image_name . '.' . $this->file->extension; $image->image_article = $article_id; $image->image_src_big = $src; //small $file_name = 'uploads/' . $image_name . '.' . $this->file->extension; $resizedFile = 'uploads/small_' . $image_name . '.' . $this->file->extension; smart_resize_image($file_name, null, 0, 100, true, $resizedFile, false, false, 100); $f = fopen("{$resizedFile}", "rb"); $result = $dbxClient->uploadFile("/small_" . "{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f); fclose($f); $src = $dbxClient->createShareableLink($result['path']); $src[strlen($src) - 1] = '1'; $image->image_src_small = $src; $image->save(); unlink($file_name); unlink($resizedFile); return true; } else { return false; } }
/** * @param string $path * @param string $string */ public function putFile($path, $string) { $stream = fopen('php://temp', 'w+'); fputs($stream, $string); rewind($stream); $this->dropbox->uploadFile('/' . $path, WriteMode::force(), $stream); }
/** * Save file for storage * * @param string $source Source File * @param string $path Remote path * @param bool $override Override * * @return bool * @throws */ public function upload($source, $path, $override = false) { $fd = fopen($source, "rb"); $writeMode = $override === true ? WriteMode::force() : WriteMode::add(); $metadata = $this->dropbox->uploadFile($this->pathRoot . $path, $writeMode, $fd); fclose($fd); return !is_null($metadata); }
function upload_file_to_dropbox($params = array()) { if (!$params) { return; } if (!($filename = pathinfo($params['source'], PATHINFO_BASENAME))) { return; } /* copy file to Dropbox */ echo "\naccessing Dropbox...\n"; if (!($dbxClient = new dbx\Client(@$params['dropbox_access_token'], "PHP-Example/1.0"))) { return; } /* $accountInfo = $dbxClient->getAccountInfo(); print_r($accountInfo); */ if ($f = Functions::file_open(CONTENT_RESOURCE_LOCAL_PATH . $filename, "rb")) { if ($info = $dbxClient->getMetadata($params['dropbox_path'] . $filename)) { $dbxClient->delete($params['dropbox_path'] . $filename); echo "\nexisting file deleted\n"; } else { echo "\nfile does not exist yet\n"; } if ($info = $dbxClient->uploadFile($params['dropbox_path'] . $filename, dbx\WriteMode::add(), $f)) { echo "\nfile uploaded OK\n"; return true; } else { echo "\nfile not uploaded!\n"; } fclose($f); } return false; }
protected function uploadStream($path, $resource, $mode) { if (!($result = $this->client->uploadFile($path, $mode, $resource))) { return false; } return $this->normalizeObject($result, $path); }
public function uploadFile(\Dropbox\Client $dropboxClient) { $remotePath = rtrim($this->folder, "/") . "/" . $this->file['name']; $fileHandle = fopen($this->file['tmp_name'], "rb"); $this->result = $dropboxClient->uploadFile($remotePath, \Dropbox\WriteMode::add(), $fileHandle); fclose($fileHandle); }
public function generate() { if (PHP_SAPI != 'cli') { throw new \Exception("This script only can be used in CLI"); } $config = $this->config->database; system('/usr/bin/mysqldump -u ' . $config->username . ' -p' . $config->password . ' -r /tmp/phosphorum.sql ' . $config->dbname); system('bzip2 /tmp/phosphorum.sql'); $sourcePath = '/tmp/phosphorum.sql.bz2'; if (!file_exists($sourcePath)) { throw new \Exception("Backup could not be created"); } list($accessToken, $host) = AuthInfo::loadFromJsonFile(APP_PATH . '/app/config/backup.auth'); $client = new Client($accessToken, "phosphorum", null, $host); $dropboxPath = '/phosphorum.sql.bz2'; $pathError = Path::findErrorNonRoot($dropboxPath); if ($pathError !== null) { throw new \Exception("Invalid <dropbox-path>: {$pathError}"); } try { $client->delete($dropboxPath); } catch (\Exception $e) { // ... } $size = null; if (\stream_is_local($sourcePath)) { $size = \filesize($sourcePath); } $fp = fopen($sourcePath, "rb"); $client->uploadFile($dropboxPath, WriteMode::add(), $fp, $size); fclose($fp); @unlink($sourcePath); }
public function upload(Attachment $attachment) { $file = $attachment->getFile(); $hash = $attachment->getHash(); try { if (!file_exists($file->getPathname()) || !is_readable($file->getPathname())) { throw new \RuntimeException('File does not exist'); } $f = fopen($file->getPathname(), 'rb'); $result = $this->client->uploadFile($this->getDropboxName($file, $hash), \Dropbox\WriteMode::add(), $f); fclose($f); } catch (\Exception $e) { $this->logger->error(sprintf("Failed to upload '%s'. Reason: %s Code: %s", $file->getFilename(), $e->getMessage(), $e->getCode())); throw new \RuntimeException(sprintf("Failed to upload %s.", $file->getFilename())); } return $file->getFilename(); }
/** * Do the actual upload of a file resource * * @param string $path * @param resource $resource * @param WriteMode $mode * @return array|false file metadata */ protected function uploadStream($path, $resource, WriteMode $mode) { $location = $this->prefix($path); if (!($result = $this->client->uploadFile($location, $mode, $resource))) { return false; } return $this->normalizeObject($result, $path); }
/** * Do the actual upload of a file resource. * * @param string $path * @param resource $resource * @param WriteMode $mode * * @return array|false file metadata */ protected function uploadStream($path, $resource, WriteMode $mode) { $location = $this->applyPathPrefix($path); // If size is zero, consider it unknown. $size = Util::getStreamSize($resource) ?: null; if (!($result = $this->client->uploadFile($location, $mode, $resource, $size))) { return false; } return $this->normalizeResponse($result, $path); }
/** * @return bool */ public function send() { $sent = true; $files = $this->backup->getFilesTobackup(); foreach ($files as $file => $name) { $file = fopen($file, 'r'); $upload = $this->dropbox->uploadFile($this->folder . '/' . $name, \Dropbox\WriteMode::force(), $file); if (!$upload) { $sent = false; echo 'DROPBOX upload manqu�e de ' . $file . ' vers ' . $this->folder . $name; } } $streams = $this->backup->getStreamsTobackup(); foreach ($streams as $stream => $name) { $upload = $this->dropbox->uploadFileFromString($this->folder . '/' . $name, \Dropbox\WriteMode::force(), $stream); if (!$upload) { $sent = false; echo 'DROPBOX upload manqu�e de ' . $file . ' vers ' . $this->folder . $name; } } return $sent; }
/** * {@inheritdoc} */ public function upload($archive) { $fileName = explode('/', $archive); $pathError = Dropbox\Path::findErrorNonRoot($this->remotePath); if ($pathError !== null) { throw new UploadException(sprintf('Invalid path "%s".', $archive)); } $client = new Dropbox\Client($this->access_token, 'CloudBackupBundle'); $size = filesize($archive); $fp = fopen($archive, 'rb'); $client->uploadFile($this->remotePath . '/' . end($fileName), Dropbox\WriteMode::add(), $fp, $size); fclose($fp); }
/** * [save_to_dbx description] * @param [type] $from [description] * @param [type] $to [description] * @return [type] [description] */ public static function save_to_dbx($from, $to) { if ($from && $to && \File::exists($from)) { try { $dbx_client = new Dbx\Client(\Config::get('my.dropbox.token'), "PHP-Example/1.0"); $f = fopen($from, "rb"); $result = $dbx_client->uploadFile($to, Dbx\WriteMode::add(), $f); fclose($f); } catch (\Exception $e) { print $e . "\n"; \Log::error($e); } } }
public function uploadFile() { $input = Input::all(); $client = new dbx\Client(Session::get("dropbox-token"), $this->_appName); $message = ""; $file = Input::file("file"); if (!$file->isValid()) { echo "ok what do i do now"; } try { $f = fopen($file->getRealPath(), "r"); $metadata = $client->uploadFile("/" . $file->getClientOriginalName(), dbx\WriteMode::add(), $f, $file->getSize()); fclose($f); #This might not be true at all. Dropbox seems to ignore some files. $message = "Successfully uploaded file: " . json_encode($metadata); } catch (Exception $e) { $message = "Could not upload file: " . $e->getMessage(); } return View::make("dropbox", ["message" => $message]); }
/** * Upload file to dropbox * @param init $comment_id * @param init $project_id * @param array $commentdata * @return void */ function upload_file_dropbox($post_id = 0, $attachment_id) { require_once MDROP_PATH . '/lib/dropbox/autoload.php'; $accesstoken = mdrop_get_token(get_current_user_id()); //'v1FIiYf35K4AAAAAAAADPLhrp-T8miNShTgeuJ5zrDmyb39gf411tgDJx22_ILSK'; //$this->dropbox_accesstoken; $dbxClient = new dbx\Client($accesstoken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); $post = get_post($post_id); $files = get_attached_file($attachment_id); $file_name = basename(get_attached_file($attachment_id)); $drop_path = '/EmailAttachment/' . $post->post_title . '/' . $file_name; $shareableLink = $dbxClient->createShareableLink($drop_path); if (!empty($shareableLink)) { return; } $f = fopen($files, "rb"); $uploaded_file = $dbxClient->uploadFile($drop_path, dbx\WriteMode::add(), $f); fclose($f); $dropbox_file_path = $uploaded_file['path']; $shareableLink = $dbxClient->createShareableLink($drop_path); $this->update_dropbox_shareablelink($attachment_id, $shareableLink); $this->update_dropbox_filepath($attachment_id, $dropbox_file_path); }
$callRecordings = $platform->get('/account/~/extension/~/call-log', array('type' => 'Voice', 'withRecording' => 'True'))->json()->records; $timePerRecording = 6; foreach ($callRecordings as $i => $callRecording) { if (property_exists($callRecording, 'recording')) { $id = $callRecording->recording->id; print "Downloading Call Log Record {$id}" . PHP_EOL; $uri = $callRecording->recording->contentUri; print "Retrieving {$uri}" . PHP_EOL; $apiResponse = $platform->get($callRecording->recording->contentUri); $ext = $apiResponse->response()->getHeader('Content-Type')[0] == 'audio/mpeg' ? 'mp3' : 'wav'; $start = microtime(true); // Store the file locally file_put_contents("/Recordings/sample_{$id}.{$ext}", $apiResponse->raw()); // Push the file to DropBox $f = fopen("/Recordings/sample_{$id}.{$ext}", "rb"); $result = $dbxClient->uploadFile("/sample.mp3", dbx\WriteMode::add(), $f); fclose($f); $end = microtime(true); // Delete the local copy of the file // unlink("/Recordings/sample_${id}.${ext}"); $time = $end * 1000 - $start * 1000; if ($time < $timePerRecording) { sleep($timePerRecording - $time); } } else { print "does not have recording" . PHP_EOL; } } } catch (HttpException $e) { $message = $e->getMessage() . ' (from backend) at URL ' . $e->apiResponse()->request()->getUri()->__toString(); print 'Expected HTTP Error: ' . $message . PHP_EOL;
<?php # Include the Dropbox SDK libraries require_once "vendor/dropbox-sdk/Dropbox/autoload.php"; use Dropbox as dbx; $appInfo = dbx\AppInfo::loadFromJsonFile("INSERT_PATH_TO_JSON_CONFIG_PATH"); $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); $authorizeUrl = $webAuth->start(); echo "1. Go to: " . $authorizeUrl . "\n"; echo "2. Click \"Allow\" (you might have to log in first).\n"; echo "3. Copy the authorization code.\n"; $authCode = \trim(\readline("Enter the authorization code here: ")); list($accessToken, $dropboxUserId) = $webAuth->finish($authCode); print "Access Token: " . $accessToken . "\n"; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); print_r($accountInfo); $f = fopen("working-draft.txt", "rb"); $result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f); fclose($f); print_r($result); $folderMetadata = $dbxClient->getMetadataWithChildren("/"); print_r($folderMetadata); $f = fopen("working-draft.txt", "w+b"); $fileMetadata = $dbxClient->getFile("/working-draft.txt", $f); fclose($f); print_r($fileMetadata);
# Include the Dropbox SDK libraries require_once ROOT_PATH . "plugins/dropbox-sdk/lib/Dropbox/autoload.php"; include_once ROOT_PATH . 'plugins/mysqldump-php-1.4.1/src/Ifsnop/Mysqldump/Mysqldump.php'; use Dropbox as dbx; try { date_default_timezone_set('Europe/Athens'); // run script only during working hours if (!App::isWorkingDateTimeOn()) { exit; } $filePath = ROOT_PATH . 'storage/excel/'; $curTerms = TermFetcher::retrieveCurrTerm(); foreach ($curTerms as $curTerm) { $curTermId = $curTerm[TermFetcher::DB_COLUMN_ID]; $curTermName = $curTerm[TermFetcher::DB_COLUMN_NAME]; $curTermStartDateTime = new DateTime($curTerm[TermFetcher::DB_COLUMN_START_DATE]); $curTermYear = $curTermStartDateTime->format('Y'); $fullPathFile = Excel::saveAppointments($curTermId); $fileName = pathinfo($fullPathFile)['filename'] . "." . pathinfo($fullPathFile)['extension']; $accessToken = DropboxFetcher::retrieveAccessToken(DropboxCon::SERVICE_APP_EXCEL_BACKUP)[DropboxFetcher::DB_COLUMN_ACCESS_TOKEN]; $dbxClient = new dbx\Client($accessToken, App::getVersion()); $adminAccountInfo = $dbxClient->getAccountInfo(); $f = fopen($fullPathFile, "rb"); $result = $dbxClient->uploadFile("/storage/excel/{$curTermYear}/{$fileName}", dbx\WriteMode::force(), $f); fclose($f); } exit; } catch (\Exception $e) { App::storeError($e); exit; }
<?php require_once "lib/Dropbox/autoload.php"; use Dropbox as dbx; $accessToken = "Your Access Token"; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; // using DIRECTORY_SEPARATOR constant is a good practice, it makes your code portable. // Adding timestamp with image's name so that files with same name can be uploaded easily. $mainFile = time() . '-' . $_FILES['file']['name']; $f = fopen($tempFile, "rb"); $result = $dbxClient->uploadFile('/' . $mainFile, dbx\WriteMode::add(), $f); //move_uploaded_file($tempFile, $mainFile); }
// Specify your sqlite database name and path echo $dbAvail[$fileNum]; echo " - size: "; $fileSize = filesize($dbAvail[$fileNum]); if ($fileSize >= 1073741824) { $fileSize = number_format($fileSize / 1073741824, 2) . ' GB'; } elseif ($fileSize >= 1048576) { $fileSize = number_format($fileSize / 1048576, 1) . ' MB'; } elseif ($fileSize >= 1024) { $fileSize = number_format($fileSize / 1024, 0) . ' KB'; } echo $fileSize; echo "<br />"; } echo "<br />"; for ($fileNum = 0; $fileNum < count($dbAvail); $fileNum++) { // Specify your sqlite database name and path $sourceFile = $dbAvail[$fileNum]; $destinationFile = '/' . substr($dbAvail[$fileNum], 10, 8); $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); $f = fopen($sourceFile, "rb"); $result = $dbxClient->uploadFile($destinationFile, dbx\WriteMode::force(), $f); fclose($f); echo "<b>Sending result " . substr($dbAvail[$fileNum], 10, 8) . ": </b>"; print_r($result[size]); echo "<br />"; } ?> </body> </html>
$password = "******"; // database name to backup $dbName = "cook"; // hostname or IP where database resides $dbHost = "localhost"; // the zip file will have this prefix $prefix = "sql_db_cook_"; // Create the database backup file $sqlFile = $tmpDir . $prefix . date('Y_m_d_h:i:s') . ".sql"; $backupFilename = $prefix . date('Y_m_d_h:i:s') . ".tgz"; $backupFile = $tmpDir . $backupFilename; echo $createBackup = "mysqldump -h " . $dbHost . " -u " . $user . " --password='******' " . $dbName . " --> " . $sqlFile; die; //echo $createBackup; $createZip = "tar cvzf {$backupFile} {$sqlFile}"; //echo $createZip; exec($createBackup); exec($createZip); //now run the DBox app info and set the client; we are naming the app folder SQL_Backup but CHANGE THAT TO YOUR ACTUAL APP FOLDER NAME; $appInfo = dbx\AppInfo::loadFromJsonFile(__DIR__ . "/config.json"); $dbxClient = new dbx\Client($accessToken, "SQL_Backup"); //now the main handling of the zipped file upload; //this message will send in a system e-mail from your cron job (assuming you set up cron to email you); echo "Uploading {$backupFilename} to Dropbox\n"; //this is the actual Dropbox upload method; $f = fopen($backupFile, "rb"); $result = $dbxClient->uploadFile('/SQL_Backup/' . $backupFilename, dbx\WriteMode::force(), $f); fclose($f); // Delete the temporary files // unlink($sqlFile); unlink($backupFile);
// Let user know of success //============================ $errorMsg = "The file " . basename($_FILES['File']['name']) . "has been uploaded"; //============================ // Copy file to dropbox //============================ $dropboxDirectory .= '/LTC-' . $thisYear; $dropboxDirectory .= '/' . trim($church[$SubmitterCong]); $dropboxDirectory .= '/' . trim($participant[$SubmitterID]); $dropboxDirectory = trim($dropboxDirectory); // print "[$dropboxDirectory]<br>[$target_name]<br>\n"; //Login to dropbox $dbxClient = new dbx\Client($accessToken, "LTCSW-Submit"); // Upload the file to dropbox $f = fopen($target_name, "rb"); $result = $dbxClient->uploadFile("{$dropboxDirectory}/" . $_FILES['File']['name'], dbx\WriteMode::force(), $f); fclose($f); //============================ // Send note to IS to process //============================ $toWho = '*****@*****.**'; $toWho .= ',blacksv@juno.com'; $toWho .= ',paul.lemmons@gmail.com'; //$toWho = '*****@*****.**'; $from = 'MIME-Version: 1.0' . "\r\n"; $from .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $from .= "From: LTCSW Seniors Information Upload <*****@*****.**>\r\n"; $subject = "LTC File Uploaded"; $message = "<html><body>\n" . "Hello, This note is to let you know that {$SubmitterName} has " . "uploaded the file:<br /><br />\n" . "<a href=\"http://ltcsw.org/files/" . basename($target_name) . "\">" . $_FILES['File']['name'] . "</a><br /><br />\n" . "You can click on the link above to download this file right now. " . "However, The file can also be found any time on the ltc " . "<a href=\"https://www.dropbox.com/login\">dropbox</a> account." . "Where it will be filed by church and participant for easier " . "reconciliation.<br><br>" . "If you need to contact the submitter they can be reached at: " . "{$SubmitterEmail} <br>" . "<br>" . "Congregation: " . $church[$SubmitterCong] . "<br>" . "Participant: " . $participant[$SubmitterID] . "<br>" . "Event: SeniorsFiles<br>" . "</body></html>\n"; $ret = mail($toWho, $subject, $message, $from); if ($ret == '' or $ret) {
/** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $dropboxPath = $this->path . $target->getFilename(); $client = new DropboxApi\Client($this->token, "phpbu/1.1.0"); $pathError = DropboxApi\Path::findErrorNonRoot($dropboxPath); if (substr(__FILE__, 0, 7) == 'phar://') { DropboxApi\RootCertificates::useExternalPaths(); } if ($pathError !== null) { throw new Exception(sprintf('Invalid \'dropbox-path\': %s', $pathError)); } $size = null; if (stream_is_local($sourcePath)) { $size = filesize($sourcePath); } try { $fp = fopen($sourcePath, 'rb'); $res = $client->uploadFile($dropboxPath, DropboxApi\WriteMode::add(), $fp, $size); fclose($fp); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done (' . $res['size'] . ')'); }
} //write part to file while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($out); @fclose($in); // Check if file has been uploaded if (!$chunks || $chunk == $chunks - 1) { // Strip the temp .part suffix off rename("{$filePath}.part", $filePath); //once file is on the server, server will upload the file to dropbox on the users current directory $referlink = $_SERVER['HTTP_REFERER']; //parses the query $peices = explode('?', $referlink); $pieces = explode('&', $peices[1]); $account = query("SELECT * FROM dropbox_accounts WHERE (id = ? AND dropbox_email = ?)", $_SESSION["id"], $pieces[0]); $client = new dbx\Client($account[0]["dropbox_accessToken"], "PHP"); $email = $account[0]["dropbox_email"]; $user = $account[0]["dropbox_id"]; $path = $pieces[1]; $path = urldecode($path); //open the file and upload it $fd = fopen("{$filePath}", "rb"); $md1 = $client->uploadFile("{$path}/{$fileName}", dbx\WriteMode::add(), $fd); fclose($fd); unlink($filePath); die(json_encode(print_r($md1))); } // Return Success JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
$dropboxPath = "/" . $_FILES['files']['name'][0]; } else { print '{"files":[{"id":' . $_POST['id'] . ',"name":"","size":"","error":"PHP upload error #' . $_FILES['files']['error'][0] . ' occurred."}]}'; die; } $pathError = dbx\Path::findErrorNonRoot($dropboxPath); if ($pathError !== null) { print '{"files":[{"id":' . $_POST['id'] . ',"name":"' . $dropboxPath . '","size":"","error":"Invalid <dropbox-path>: ' . $pathError . '"}]}'; die; } $size = null; if (\stream_is_local($sourcePath)) { $size = \filesize($sourcePath); } $fp = fopen($sourcePath, "rb"); $metadata = $client->uploadFile($dropboxPath, dbx\WriteMode::add(), $fp, $size); fclose($fp); if ($logging) { $logfile = tmpfile(); fwrite($logfile, "Upload date: " . date("F j, Y, g:i a") . "\nIP: " . $_SERVER['REMOTE_ADDR']); fseek($logfile, 0); $logsize = filesize(stream_get_meta_data($logfile)['uri']); $log_metadata = $client->uploadFile($dropboxPath . ".log", dbx\WriteMode::add(), $logfile, $logsize); fclose($logfile); } print '{"files":[{"id":' . $_POST['id'] . ',"name":"' . $metadata['path'] . '","size":' . $size . '}]}'; die; } catch (dbx\AuthInfoLoadException $ex) { print '{"files":[{"id":' . $_POST['id'] . ',"name":"' . $metadata['path'] . '","size":' . $size . ',"error":"An authentication problem occurred.}]}'; die; }
fclose($f); $csv1 = readCSV($first_csv_file); //Set path to CSV file $csvFile = $second_csv_file; $csv2 = readCSV($csvFile); foreach ($csv1 as $s) { $array = array(); $array[] = $s[0]; $array[] = $s[2]; $array[] = $s[4]; $array[] = $s[5]; $abc[] = $array; } $i = 0; foreach ($csv2 as $s1) { $array = array(); $abc[$i][] = $s1[0]; $abc[$i][] = $s1[2]; $abc[$i][] = $s1[3]; $i++; } //create new csv file on dropbox $file = fopen('final-raxis.csv', 'w'); fputcsv($file); foreach ($abc as $row) { fputcsv($file, $row); } //upload a file to dropbox $f = fopen("final-raxis.csv", "rb"); $result = $dbxClient->uploadFile("/final-raxis.csv", dbx\WriteMode::add(), $f); fclose($f);
if (strpos($e1->innertext, $row['nome']) !== false) { $taxa = str_replace(",", ".", $e1->parent()->children(2)->innertext()); echo $row['id'] . "\t" . $taxa . "<br>"; $stmt = $db->prepare('INSERT INTO taxa (titulo_id, valor, timestamp) VALUES (:titulo_id, :taxa, :timestamp)'); $stmt->bindValue(':titulo_id', $row['id'], SQLITE3_INTEGER); $stmt->bindValue(':taxa', strval($taxa)); $stmt->bindValue(':timestamp', time()); $stmt->execute(); break; } } } $f = fopen("../db/Tesouro.db", "rb"); if (flock($f, LOCK_EX)) { // acquire an exclusive lock $dbxClient->uploadFile("/Tesouro.db", dbx\WriteMode::force(), $f); fflush($f); // flush output before releasing the lock flock($f, LOCK_UN); // release the lock } else { echo "Couldn't get the lock!"; } fclose($f); $db->close(); unlink("Tesouro.db"); ?> </pre> </body> </html>
$fileMetadata_b = $dbxClient->getFile("/data-b.csv", $fb); fclose($fb); print_r($fileMetadata_b); /****** Get csv data from data-a.csv file ***********/ if (false !== ($ih = fopen('data-a.csv', 'r'))) { while (false !== ($data = fgetcsv($ih))) { $csvDataA[] = array($data[0], $data[2], $data[4], $data[5]); } } /****** Get csv data from data-b.csv file ***********/ if (false !== ($ih = fopen('data-b.csv', 'r'))) { while (false !== ($data = fgetcsv($ih))) { $csvDataB[] = array($data[0], $data[2], $data[3]); } } /****** Merge Data *********/ $final_csv = array(); foreach ($csvDataB as $key => $value) { $final_csv[] = array_merge((array) $csvDataA[$key], (array) $value); } /****** Create new csv after merge csv data *******/ $fp = fopen('result.csv', 'w'); foreach ($final_csv as $fields) { fputcsv($fp, $fields); } fclose($fp); // Uploading the file $f = fopen("result.csv", "rb"); $result = $dbxClient->uploadFile("/result.csv", dbx\WriteMode::add(), $f); fclose($f); print_r($result);
} */ // Allow certain file formats // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; ?> <button type = "button" value="Wind Speed" onclick="window.location.href='http://localhost:8000/upload'">Return</button><?php // if everything is ok, try to upload file } if ($uploadOk == 1) { $accessToken = "RhUHA_3bYAsAAAAAAAAAKFPP6W9Sv3yhCVVCun37FpkqOYSDvIYPanrtRw1GOFG7"; $dbxClient = new dbx\Client($accessToken, "Software_Methodologies_App"); ?> <button type = "button" value="Wind Speed" onclick="window.location.href='http://localhost:8000/upload'">Return</button><?php $f = fopen($_FILES["fileToUpload"]["tmp_name"], "rb"); $result = $dbxClient->uploadFile("/Software_Methodologies/Input/actual.csv", dbx\WriteMode::force(), $f); fclose($f); echo "Your file was a csv and was uploaded."; } /* else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; ?><button type = "button" value="Wind Speed" onclick="window.location.href='http://localhost:8000/upload'">Return</button><?php } else { echo "Sorry, there was an error uploading your file."; } }*/