remove time check in php script - php

I have a php script in prestashop that (should) downloads an xml file and then begin the import proccess. The script checks if the file that was downloaded the last time matches the time in the database entry and if they do not match the it downloads the new xml. This whole thing does not work as it should mainly because the whole if command is wrong. (Normaly it should first download the file and then check it the time mathces). Anyway this is all not required since the file is small. So instead I need to remove this if statement and download the file anyway replacing the previous downloaded file.
Can anyone please help me remove the if command that checks the date?
This is the script:
ini_set('display_errors', 0);
//ini_set('memory_limit', '812M');
set_time_limit(0);
include_once realpath(__DIR__.'/../../')."/config/config.inc.php";
include_once realpath(__DIR__)."/XmlFeedImporter.php";
if( Configuration :: get('CRONRUN_STATUS') && Configuration :: get('PRODUCTXML_URL')){
$remoteXmlFile = Configuration :: get('PRODUCTXML_URL');
$url_parts = parse_url($remoteXmlFile);
$isCLI = ( php_sapi_name() == 'cli' );
if( $isCLI){
// For live
$server_host = $url_parts['host'];
$server_root = _PS_ROOT_DIR_.'/';
} else {
$server_host = $_SERVER['HTTP_HOST'];
$server_root = $_SERVER['DOCUMENT_ROOT'].'/';
}
$outputLocalCsv = _PS_DOWNLOAD_DIR_.'products_output_'.date('Y-m-d').'.csv';
$objXmlFeedImporter = new XmlFeedImporter();
if(strpos($remoteXmlFile,$server_host) === false){
// CHeck whether same remote file was download or not ?
if (((int)Configuration :: get('PRODUCTXML_DOWNLOAD_DATE') && (int)Configuration :: get('PRODUCTXML_UPDATE_TIME')) && ((int)Configuration :: get('PRODUCTXML_DOWNLOAD_DATE') > (int)Configuration :: get('PRODUCTXML_UPDATE_TIME'))) {
$inputLocalXml = _PS_UPLOAD_DIR_.'products_input_'.date('Y-m-d', Configuration :: get('PRODUCTXML_DOWNLOAD_DATE')).'.xml';
} else {
$time = time();
$inputLocalXml = _PS_UPLOAD_DIR_.'products_input_'.date('Y-m-d', $time).'.xml';
$downloadedBytes = $objXmlFeedImporter->downloadRemoteFile($remoteXmlFile, $inputLocalXml);
Configuration :: updateValue('PRODUCTXML_DOWNLOAD_DATE', $time);
if($downloadedBytes == 0){
d('Nothing was downloaded from '.$remoteXmlFile.' !!');
}
}
} else {
$file_parts = explode($server_host, $remoteXmlFile);
if( $server_host == 'localhost'){
$server_root = str_replace(DS.'my-presta','',$server_root);
}
$inputLocalXml = $server_root.trim($file_parts[1],'/');
}
//d($inputLocalXml);
$objXmlFeedImporter->setInputFile($inputLocalXml);
// Get products in a csv
if(Configuration :: get('CREATE_XML2CSV')){
$objXmlFeedImporter->setOutputFile($outputLocalCsv);
}
//$objXmlFeedImporter->_justCount = true; // just count products
//$objXmlFeedImporter->_dump = true; // print product data
try{
$objXmlFeedImporter->runParser(); // run parser
} catch(Exception $e){
// Send Email
print_r($e);
}
}
?>

I believe this is without that check:
ini_set('display_errors', 0);
//ini_set('memory_limit', '812M');
set_time_limit(0);
include_once realpath(__DIR__.'/../../')."/config/config.inc.php";
include_once realpath(__DIR__)."/XmlFeedImporter.php";
if( Configuration :: get('CRONRUN_STATUS') && Configuration :: get('PRODUCTXML_URL')){
$remoteXmlFile = Configuration :: get('PRODUCTXML_URL');
$url_parts = parse_url($remoteXmlFile);
$isCLI = ( php_sapi_name() == 'cli' );
if( $isCLI){
// For live
$server_host = $url_parts['host'];
$server_root = _PS_ROOT_DIR_.'/';
} else {
$server_host = $_SERVER['HTTP_HOST'];
$server_root = $_SERVER['DOCUMENT_ROOT'].'/';
}
$outputLocalCsv = _PS_DOWNLOAD_DIR_.'products_output_'.date('Y-m-d').'.csv';
$objXmlFeedImporter = new XmlFeedImporter();
if(strpos($remoteXmlFile,$server_host) === false){
// CHeck whether same remote file was download or not ?
$time = time();
$inputLocalXml = _PS_UPLOAD_DIR_.'products_input_'.date('Y-m-d', $time).'.xml';
} else {
$file_parts = explode($server_host, $remoteXmlFile);
if( $server_host == 'localhost'){
$server_root = str_replace(DS.'my-presta','',$server_root);
}
$inputLocalXml = $server_root.trim($file_parts[1],'/');
}
$downloadedBytes = $objXmlFeedImporter->downloadRemoteFile($remoteXmlFile, $inputLocalXml);
Configuration :: updateValue('PRODUCTXML_DOWNLOAD_DATE', $time);
if($downloadedBytes == 0){
d('Nothing was downloaded from '.$remoteXmlFile.' !!');
}
//d($inputLocalXml);
$objXmlFeedImporter->setInputFile($inputLocalXml);
// Get products in a csv
if(Configuration :: get('CREATE_XML2CSV')){
$objXmlFeedImporter->setOutputFile($outputLocalCsv);
}
//$objXmlFeedImporter->_justCount = true; // just count products
//$objXmlFeedImporter->_dump = true; // print product data
try{
$objXmlFeedImporter->runParser(); // run parser
} catch(Exception $e){
// Send Email
print_r($e);
}
}
?>
This seems to be the if you were talking about:
if (((int)Configuration :: get('PRODUCTXML_DOWNLOAD_DATE') && (int)Configuration :: get('PRODUCTXML_UPDATE_TIME')) && ((int)Configuration :: get('PRODUCTXML_DOWNLOAD_DATE') > (int)Configuration :: get('PRODUCTXML_UPDATE_TIME')))

Related

Base64_decoded image string saved to directory doesn't show image

I am trying to upload an image from my android application to a php script on my server. In my script, I am attempting to decode the image (using base64_decode) and then use file_put_contents() to save the image as a file in my directory. My problem is that the file 'appears' empty when I have .jpg at the end of the file name. When I removed that to see what was added for the image encoding, I see a very long string of characters, (65214 bytes specifically that were written to the file). When I run the code again, only this time uploading the $_POST['sent_image'] without decoding, I get the same exact string of text.
I am not sure what I am doing wrong... The end goal would be to save the image on the server, so it could be viewed elsewhere online, and also be able to retrieve it and get back into another activity in my android application.
All suggestions are appreciated!
NOTE: I have also tried imagecreatefromstring(), but that causes 0 bytes to be written.
My Code:PHP that gets encoded android image and tries to save to server directory:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
Thank you!
Using str_replace may be problematic if image format is other than jpg, for example.
Example code:
<?php
$photo = $_POST['newUnitStatusPhoto'];
if(substr($photo, 0,5) !== "data:"){
//do error treatment as it's not datauri
die("Error: no data: scheme");
};
$decodedPhoto = substr($photo, 5);
$mimeTerminator = stripos($decodedPhoto,";");
if($mimeTerminator === false){
die("Error: no mimetype found");
};
$decodedPhoto = substr($decodedPhoto, $mimeTerminator+8); //1<;>+4<base>+2<64>+1<,>
// $decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
// $decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$unitname = "testando";
$fileName = "".$unitname."_rej.jpg";
$target = 'img/';
$newFile = $target.$fileName;
if(file_exists($newFile))
unlink($newFile);
$success = file_put_contents($newFile, $newUnitStatusPhoto);
echo $success;

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

Dropbox API Redirection Loop

I am using php sdk provided by Dropbox Core API. I have a minor bug... My file is being redirected all the time even I click on the allow button... Below is my index file:
index.php
<?php
session_start();
ini_set("display_errors",1);
require_once __DIR__.'/dropbox-sdk/Dropbox/strict.php';
$appInfoFile = __DIR__."/AppInfo.json";
// NOTE: You should be using Composer's global autoloader. But just so these examples
// work for people who don't have Composer, we'll use the library's "autoload.php".
require_once __DIR__.'/dropbox-sdk/Dropbox/autoload.php';
use \Dropbox as dbx;
$requestPath = init();
echo "Request path = ".$requestPath."<br>";
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
echo "Path: ".getPath("dropbox-auth-start")."<br>";die;
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
$path = "/";//Debug completed
if (isset($_GET['path'])) $path = $_GET['path'];
$entry = $dbxClient->getMetadataWithChildren($path);
echo "Client<pre>";
print_r($dbxClient);
echo "</pre>";
echo "Entry".$entry;die;
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
else if ($requestPath == "/download") {
//die("Download");
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
if (!isset($_GET['path'])) {
header("Location: ".getPath(""));
exit;
}
$path = $_GET['path'];
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
}
else if ($requestPath === "/upload") {
//die("Upload");
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}
else if ($requestPath === "/dropbox-auth-start") {
//die("dropbox-auth-start");
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($requestPath === "/dropbox-auth-finish") {
//die("dropbox-auth-finish");
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
// We didn't pass in $urlState to finish, and we're assuming the session can't be
// tampered with, so this should be null.
assert($urlState === null);
}
catch (dbx\WebAuthException_BadRequest $ex) {
respondWithError(400, "Bad Request");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it could contain
// sensitive information.
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
respondWithError(403, "Unauthorized", "CSRF mismatch");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it contains
// sensitive information that could be used to bypass the CSRF check.
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!",
"Auth complete, <a href='".htmlspecialchars(getPath(""))."'>click here</a> to browse.");
}
else if ($requestPath === "/dropbox-auth-unlink") {
//die("dropbox-auth-unlink");
// "Forget" the access token.
unset($_SESSION['access-token']);
echo renderHtmlPage("Unlinked.",
"Go back <a href='".htmlspecialchars(getPath(""))."'>home</a>.");
}
else {
//die("else part");
echo renderHtmlPage("Bad URL", "No handler for $requestPath");
exit;
}
function renderFolder($entry)
{
// TODO: Add a token to counter CSRF attacks.
$upload_path = htmlspecialchars(getPath('upload'));
$path = htmlspecialchars($entry['path']);
$form = <<<HTML
<form action='$upload_path' method='post' enctype='multipart/form-data'>
<label for='file'>Upload file:</label> <input name='file' type='file'/>
<input type='submit' value='Upload'/>
<input name='folder' type='hidden' value='$path'/>
</form>
HTML;
$listing = '';
foreach($entry['contents'] as $child) {
$cp = $child['path'];
$cn = basename($cp);
if ($child['is_dir']) $cn .= '/';
$cp = htmlspecialchars($cp);
$link = getPath("?path=".htmlspecialchars($cp));
$listing .= "<div><a style='text-decoration: none' href='$link'>$cn</a></div>";
}
return renderHtmlPage("Folder: $entry[path]", $form.$listing);
}
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$redirectUri = "http://localhost/MyApi/Dropbox/";//success.php";//getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function renderFile($entry)
{
$metadataStr = htmlspecialchars(print_r($entry, true));
$downloadPath = getPath("download?path=".htmlspecialchars($entry['path']));
$body = <<<HTML
<pre>$metadataStr</pre>
Download this file
HTML;
return renderHtmlPage("File: ".$entry['path'], $body);
}
function renderHtmlPage($title, $body)
{
return <<<HTML
<html>
<head>
<title>$title</title>
</head>
<body>
<h1>$title</h1>
$body
</body>
</html>
HTML;
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
echo "Server values:<pre>";
print_r($_SERVER);
echo "</pre>";
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
?>
FYI: in my dropbox app I have set the redirect uri as : "localhost/MyApi/Dropbox/"... But it is going like loop... Can any one solve this? I thought to change the redirect uri to success.php but is there any other way to solve this?
Update:
I am also pasting my success.php file:
success.php
<?php
session_start();
ini_set("display_errors",1);
# Include the Dropbox SDK libraries
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$dbxClient = new dbx\Client($_SESSION['access-token'], "PHP-PicPixa/1.0");//This line is giving error
$accountInfo = $dbxClient->getAccountInfo();
echo "Account Info:<pre>";
print_r($accountInfo);
echo "</pre>";
$f = fopen("working-draft.txt", "a");
$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);
echo "<br>File meta data:<br><pre>";
print_r($fileMetadata);
echo "</pre>";
?>
To access my full project please download it from: https://www.dropbox.com/sh/ps90blb2uujbxxh/AABdbU39upJSOeiLwxSnjufFa
Thank You,
It looks like you commented out code that would have redirected to dropbox-auth-finish. Since you're never going there, you're never finishing the auth process and never setting $_SESSION['access-token'] to anything.

php Getting files list &(ampersand) character error

I have code for getting files list in php, but if file name contain & character it doesn't display that file.
Here's the code:
Ps. I'm not php programmer and I really don't know what is this error.
All help will be very appreciated
Thanks so much in advance.
<?php
include_once('config.inc.php');
$current_dir = 'root';
if(array_key_exists('directory',$_POST)) {
$current_dir = $_POST['directory'];
}
// Creating a new XML using DOMDocument
$file_list = new DOMDocument('1.0');
$xml_root = $file_list->createElement('filelist');
$xml_root = $file_list->appendChild($xml_root);
// Setting the 'currentPath' attribute of the XML
$current_path = $file_list->createAttribute('currentPath');
$current_path->appendChild($file_list->createTextNode($current_dir));
$xml_root->appendChild($current_path);
// Replacing the word 'root' with the real root path
$current_dir = substr_replace($current_dir, $root, 0, 4);
$di = new DirectoryIterator($current_dir);
// Creating the XML using DirectoryIterator
while($di->valid())
{
if(false == $di->isDot())
{
if($di->isDir() && true != in_array($di->getBasename(),$h_folders))
{
$fl_node = $file_list->createElement('dir');
$xml_root->appendChild($fl_node);
}else if($di->isFile() && true !== in_array($di->getBasename(),$h_files)
&& true !== in_array(get_ext($di->getBasename()),$h_types))
{
$fl_node = $file_list->createElement('file');
$xml_root->appendChild($fl_node);
}else
{
$di->next();
continue;
}
$name = $file_list->createElement('name',$di->getBasename());
$fl_node->appendChild($name);
$path = substr_replace($di->getRealPath(), 'root', 0, strlen($root));
$path_node = $file_list->createElement('path', $path);
$fl_node->appendChild($path_node);
$di->next();
}else $di->next();
}
function get_ext($filename)
{
$exp = '/^(.+)\./';
return preg_replace($exp,'',$filename);
}
// Returning the XML to Flash.
echo $file_list->saveXML();
?>
The & character is used in HTML to write entities.
If you want to display arbitrary text in HTML, you need to escape it by calling htmlentities().
If you give some source I can help, file content not file name.
Example how get list of files:
$c = "/some/path/to/file/here";
if(is_dir($c)){
foreach(scandir($c) as $file){
if($file != '.' && $file != '..'){
$d = $c.DIRECTORY_SEPARATOR.$file;
echo " \"". realpath($d) ."\"\n";
}
}
}

Upload Entire Directory via PHP FTP

I'm trying to write a script that will upload the entire contents of a directory stored on my server to other servers via ftp.
I've been reading through the documentation on www.php.net, but can't seem to find a way to upload more then one file at a time.
Is there a way to do this, or is there a script that will index that directory and create an array of files to upload?
Thanks in advance for your help!
Once you have a connection open, uploading the contents of a directory serially is simple:
foreach (glob("/directory/to/upload/*.*") as $filename)
ftp_put($ftp_stream, basename($filename) , $filename, FTP_BINARY);
Uploading all files in parallel would be more difficult.
So, I took #iYETER's code, and wrapped it as a class object.
You can call this code by these lines:
$ftp = new FtpNew("hostname");
$ftpSession = $ftp->login("username", "password");
if (!$ftpSession) die("Failed to connect.");
$errorList = $ftp->send_recursive_directory("/local/dir/", "/remote/dir/");
print_r($errorList);
$ftp->disconnect();
It recursively crawls local dir, and places it on remote dir relative. If it hits any errors, it creates a array hierarchy of every file and their exception code (I only capture 2 so far, if it's another error, it throws it default route for now)
The class this is wrapped into:
<?php
//Thanks for iYETER on http://stackoverflow.com/questions/927341/upload-entire-directory-via-php-ftp
class FtpNew {
private $connectionID;
private $ftpSession = false;
private $blackList = array('.', '..', 'Thumbs.db');
public function __construct($ftpHost = "") {
if ($ftpHost != "") $this->connectionID = ftp_connect($ftpHost);
}
public function __destruct() {
$this->disconnect();
}
public function connect($ftpHost) {
$this->disconnect();
$this->connectionID = ftp_connect($ftpHost);
return $this->connectionID;
}
public function login($ftpUser, $ftpPass) {
if (!$this->connectionID) throw new Exception("Connection not established.", -1);
$this->ftpSession = ftp_login($this->connectionID, $ftpUser, $ftpPass);
return $this->ftpSession;
}
public function disconnect() {
if (isset($this->connectionID)) {
ftp_close($this->connectionID);
unset($this->connectionID);
}
}
public function send_recursive_directory($localPath, $remotePath) {
return $this->recurse_directory($localPath, $localPath, $remotePath);
}
private function recurse_directory($rootPath, $localPath, $remotePath) {
$errorList = array();
if (!is_dir($localPath)) throw new Exception("Invalid directory: $localPath");
chdir($localPath);
$directory = opendir(".");
while ($file = readdir($directory)) {
if (in_array($file, $this->blackList)) continue;
if (is_dir($file)) {
$errorList["$remotePath/$file"] = $this->make_directory("$remotePath/$file");
$errorList[] = $this->recurse_directory($rootPath, "$localPath/$file", "$remotePath/$file");
chdir($localPath);
} else {
$errorList["$remotePath/$file"] = $this->put_file("$localPath/$file", "$remotePath/$file");
}
}
return $errorList;
}
public function make_directory($remotePath) {
$error = "";
try {
ftp_mkdir($this->connectionID, $remotePath);
} catch (Exception $e) {
if ($e->getCode() == 2) $error = $e->getMessage();
}
return $error;
}
public function put_file($localPath, $remotePath) {
$error = "";
try {
ftp_put($this->connectionID, $remotePath, $localPath, FTP_BINARY);
} catch (Exception $e) {
if ($e->getCode() == 2) $error = $e->getMessage();
}
return $error;
}
}
Do it in a loop, iterating through all the files in the folder
$servername = $GLOBALS["servername"];
$ftpUser = $GLOBALS["ftpUser"];
$ftpPass = $GLOBALS["ftpPass"];
$conn_id = ftp_connect($servername) or die("<p style=\"color:red\">Error connecting to $servername </p>");
if(ftp_login($conn_id, $ftpUser, $ftpPass))
{
$dir_handle = #opendir($path) or die("Error opening $path");
while ($file = readdir($dir_handle)) {
ftp_put($conn_id, PATH_TO_REMOTE_FILE, $file)
}
}
I coded it, the script uploads whole folder with it's subfolders and files.
I hope it will help you.
<?php
ob_start();
set_time_limit(0);
//r10.net fatal
$anadizin="uploadedeceginizdizin"; //this is the folder that you want to upload with all subfolder and files of it.
$ftpsunucu="domain.com"; //ftp domain name
$ftpusername="ftpuser"; //ftp user name
$ftppass="ftppass"; //ftp passowrd
$ftpdizin="/public_html"; //ftp main folder
$arkadaslarlabardaydik = ftp_connect($ftpsunucu);
$ictikguldukeglendik = ftp_login($arkadaslarlabardaydik, $ftpusername, $ftppass);
if((!$arkadaslarlabardaydik) || (!$ictikguldukeglendik))
{
echo "cant connect!";
die();
}
function klasoruoku($dizinadi)
{
global $nerdeyiz,$fulldizin,$ftpdizin,$arkadaslarlabardaydik,$ftpdizin;
chdir($dizinadi."\\");
$dizin = opendir(".");
while($bilgi=readdir($dizin))
{
if ($bilgi!='.' and $bilgi!='..' and $bilgi!="Thumbs.db")
{
$tamyol="$dizinadi\\$bilgi";
$lokalkla=str_replace("".$nerdeyiz."\\","",$dizinadi)."";
$lokaldosya="$lokalkla\\$bilgi";
$ftpyeyolla=str_replace(array("\\\\","\\"),array("/","/"),"$ftpdizin\\".str_replace("".$fulldizin."","",$dizinadi)."\\$bilgi");
if(!is_dir($bilgi))
{
$yükleme = ftp_put($arkadaslarlabardaydik, $ftpyeyolla, $tamyol, FTP_BINARY);
if (!$yükleme)
{
echo "$lokaldosya <font color=red>uploaded</font>"; echo "<br>"; fls();
}
else
{
echo "$lokaldosya <font color=green>not uploaded</font>"; echo "<br>"; fls();
}
}
else
{
ftp_mkdir($arkadaslarlabardaydik, $ftpyeyolla);
klasoruoku("$dizinadi\\$bilgi");
chdir($dizinadi."\\");
fls();
}
}
}
closedir ($dizin);
}
function fls()
{
ob_end_flush();
ob_flush();
flush();
ob_start();
}
$nerdeyiz=getcwd();
$fulldizin=$nerdeyiz."\\$anadizin";
klasoruoku($fulldizin);
ftp_close($arkadaslarlabardaydik);
?>
If you want to have multiple files uploaded at once, you'll need to use thread or fork.
I'm not sure of a Thread implentation in PHP, but you should take a look at the PHP SPL and/or PEAR
Edit: Thanks to Frank Farmer to let me know that there was a fork() function in PHP known as pcntl_fork()
You'll also have to get the whole content directory recursively to be able to upload all the file for a given directory.

Categories