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.
Related
Im trying to connect with my ssh server and download a file but i got a problem and i don't understand why. The file exist for sure, i search on internet but i didn't find anything to unbug this.
Error:
COPY ERROR: 2
ssh2_scp_recv() [function.ssh2-scp-recv]: Unable to receive remote file
My code:
public function ajaxdownloadfileAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->view->lib = $this->_labelsFile;
$connection = ssh2_connect($this->_configFile->ftp->hostname, $this->_configFile->ftp->port);
if ($connection) {
$login = ssh2_auth_password($connection, $this->_configFile->ftp->login, $this->_configFile->ftp->password);
if ($login) {
$content = true;
if ($content) {
$local = ' C:\Users\Public\Downloads ';
$fileName = "\\Talend\\PEC_DF6\\FluxSortantAdmissionPEC\\ARCHIVES\\XML\\wzadyyyy.0001054581.ap.xml";
if(!#ssh2_scp_recv($connection,$fileName,$local)){
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}
else {
echo "File copied from remote!";
}
//$filename = $this->getRequest()->getParam('name');
// $fileName = "\\Talend\\PEC_DF6\\FluxSortantAdmissionPEC\\ARCHIVES\\XML\\wzadyyyy.0001054581.ap.xml";
//$fileName = $this->_getParam('fileName');
//echo $fileName;die;
//ssh2_scp_recv($connection,$filename,$local);
}
$connection = null; unset($connection);
}
}
/* $result['status'] = 'OK';
$result['message'] = 'LE ficheir a bien ete telecharger';
echo json_encode($result);*/
}
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')))
i am encrypting my pdf but when i open it and enters the password it always says wrong error this is my code:
global $_dompdf_show_warnings;
global $_dompdf_debug;
global $_DOMPDF_DEBUG_TYPES;
$outfile = $id . '_qr_codes.pdf';
$save_file = TRUE; // Save the file or not
$buff = $this->qr_generate_pdf($id);
//echo $buff; die;
$dompdf = new DOMPDF();
$dompdf->load_html($buff);
if (isset($base_path)) {
$dompdf->set_base_path($base_path);
}
$dompdf->render();
$dompdf->get_canvas()->get_cpdf()->setEncryption('admin','ownerpass');
if ($_dompdf_show_warnings) {
global $_dompdf_warnings;
foreach ($_dompdf_warnings as $msg) {
echo $msg . "\n";
}
echo $dompdf->get_canvas()->get_cpdf()->messages;
flush();
}
if ($save_file) {
// if ( !is_writable($outfile) )
// throw new DOMPDF_Exception("'$outfile' is not writable.");
if (strtolower(DOMPDF_PDF_BACKEND) == "gd") {
$outfile = str_replace(".pdf", ".png", $outfile);
}
list($proto, $host, $path, $file) = explode_url($outfile);
if ($proto != "") // i.e. not file://
$outfile = $file; // just save it locally, FIXME? could save it like wget: ./host/basepath/file
//$outfile = dompdf_realpath($outfile);
// if ( strpos($outfile, DOMPDF_CHROOT) !== 0 )
// throw new DOMPDF_Exception("Permission denied.");
file_put_contents($outfile, $dompdf->output(array("compress" => 0)));
}
if (!headers_sent())
$dompdf->stream($outfile);
}
when i enter the password 'ownerpass' in the downloaded pdf it throughs an error-> The Password is incorrect. Please make sure that capslock is not on by mistake,and try again.
Thanks in advance
I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
<html>
<body>
<?php
if(isset($_FILES["uploaded"]))
{
print_r($_FILES);
if(move_uploaded_file($_FILES["uploaded"]["tmp_name"],"<root>/domains/sigaindia.com/public_html/reymend/".$_FILES["uploaded"]["name"]))
echo "FILE UPLOADED!";
}
else
{
print "<form enctype='multipart/form-data' action='fup1.php' method='POST'>";
print "File:<input name='uploaded' type='file'/><input type='submit' value='Upload'/>";
print "</form>";
}
?>
</body>
</html>
$host = "ftp.example.com";
$user = "anonymous";
$pass = "";
// You get this from the form, so you don't need to do move_uploaded_file()
$fname = "/public_html/new_file.txt";
$fcont = "content";
function ftp_writeFile($ftp, $new_file, $content, $debug=false) {
extract((array)pathinfo($new_file));
if (!#ftp_chdir($ftp, $dirname)) {
return false;
}
$temp = tmpfile();
fwrite($temp, $fcont);
rewind($temp);
$res = #ftp_fput($ftp, $basename, $temp, FTP_BINARY);
if ($debug) echo "a- '$new_file'".(($res)?'':" [error]")."<br/>";
fclose($temp);
return $res;
}
$ftp = ftp_connect($host);
if (!$ftp) echo "Could not connect to '$host'<br/>";
if ($ftp && #ftp_login($ftp, $username, $password)) {
ftp_writeFile($ftp, $fname, $fcont, true);
} else {
echo "Unable to login as '$username:".str_repeat('*', strlen($password))."'<br/>";
}
ftp_close($ftp);
http://au.php.net/manual/en/book.ftp.php
I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
If you're talking about PHP and forms than that's HTTP - HTTP is not FTP and vice versa.
WinSCP is an SSH client. SSH is a different protocol from HTTP. SSH is a different protocol from FTP.
If you want your PHP script to transfer files uploaded to the webserver to an FTP server, try something like:
foreach ($_FILES as $f) {
if (file_exists($f['tmp_name'])) {
$dest = 'ftp://' . $username . ':' . $password .
'#' . $ftpserver . $ftp_path;
file_put_contents($f['tmp_name'], $dest);
}
}
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.