I am downloading zip files from FTP server using PHP ftp function.I used binary and passive mode to get file.
The problem is that when I stopped the ftp operation before the completion of ftp operation(ie ftp_close() was not called) and when it was started again it shows the following Warning-
ftp_login() [http://php.net/function.ftp-login]: service unavailable
FTP connection has failed!
And the FTP operation was failed.I have written the following code for FTP operation.
$connId = ftp_connect($host);
$loginResult = ftp_login($connId, $user, $password);
if ((!$connId) || (!$loginResult)) {
echo "FTP connection has failed!";
exit;
}
ftp_pasv($connId, true);
if (!ftp_chdir($connId, $remoteDir))
return false;
if (!ftp_get($connId, $localDir.$localFile,$remoteFile,FTP_BINARY))
return false;
ftp_close($connId);
How to forcefully destroy ftp connection which has started getting files in binary mode and the connection is in passive mode?
Rebooting the machine or deleting the session cookies did not help me.What might be the possible solution for it?
Rebooting a machine always closes all connections made by or to that machine.
ftp_login() [http://php.net/function.ftp-login]: service unavailable
FTP connection has failed!
It looks like the remote FTP server is terminating the connection before you ever get to the login step. Check that your credentials are correct and check to make sure the FTP server is operating correctly.
This question is way old, but one I had some issues with recently. I put together a quick FTP helper class that will automatically and cleanly close connections. Hope this helps others looking for a simpler way to perform basic FTP operations.
//
define("SMOKE_TEST", TRUE);
//
// Define main FTP class.
//
class C_FTP {
// Connection handle.
//
public $h = FALSE;
// Close connection.
//
public function _Close() {
if ($this->h) {
ftp_close($this->h);
$this->h = FALSE;
}
}
// Connect.
//
public function __construct($sDNSName) {
$this->_Close();
$this->h = ftp_connect($sDNSName);
}
// Destructor.
//
public function __destruct() {
$this->_Close();
}
// Authenticate.
//
public function login($sUsername = "", $sPassword = "") {
$sError = "";
do {
//
if (!$this->h) {
$sError = "Not connected";
break;
}
if (!ftp_login($this->h, $sUsername, $sPassword)) {
$sError = "Unrecognized username or password";
break;
}
ftp_pasv($this->h, TRUE);
//
} while (0);
return ($sError);
}
// Change directory.
//
public function cd($sFolder) {
$sError = "";
do {
if (!ftp_chdir($this->h, $sFolder)) {
$sError = "Unable to change directory";
break;
}
} while (0);
return ($sError);
}
// List files in current directory.
//
public function dir(&$aFiles) {
$sError = "";
do {
if (($aFiles = ftp_nlist($this->h, ".")) === FALSE) {
$sError = "Unable to list files in current directory";
break;
}
} while (0);
return ($sError);
}
// Get file from remote site into specified local file.
//
public function get($sLocalFile, $sRemoteFilename) {
$sError = "";
do {
if (!ftp_get($this->h, $sLocalFile, $sRemoteFilename, FTP_BINARY)) {
$sError = "Could not perform file get";
break;
}
} while (0);
return ($sError);
}
// Put file from remote site into current directory.
//
public function put($sLocalFile, $sRemoteFilename) {
$sError = "";
do {
if (!ftp_put($this->h, $sRemoteFilename, $sLocalFile, FTP_BINARY)) {
$sError = "Could not perform file put";
break;
}
} while (0);
return ($sError);
}
// ...end FTP class.
//
}
// If we are running a stand-alone test of this class,
// set SMOKE_TEST to TRUE and invoke from CLI.
// For example: c:\php\php C_FTP.php
//
if (SMOKE_TEST) {
//
function IsError($sMessage) {
if (strlen($sMessage)) {
echo("Error: ".$sMessage);
return (true);
} else {
return (false);
}
}
//
do {
//
$aFiles = array();
//
$cFTP = new C_FTP(FTP_DNS_NAME);
if (IsError($cFTP->login(FTP_USER, FTP_PASSWORD))) { break; }
if (IsError($cFTP->cd("Env"))) { break; }
if (IsError($cFTP->get("foo.txt", "SomeRemoteFile.txt"))) { break; }
if (IsError($cFTP->dir($aFiles))) { break; }
var_dump($aFiles);
//
} while (0);
//
}
?>
Please note that this forces passive mode for data transfer, so if you need active, you'll need to adjust accordingly.
Related
I am getting data from a database and I want to check whether the data contains an image or not. I tried with following code and I want to know if is this a good solution for this.
$headers = get_headers('https://cdn.discordapp.com/attachments/999921405858680857/1011168600410820679/1656572127-blog-2.JPG', 1);
if (strpos($headers['Content-Type'], 'image/') !== false) {
echo "Work";
} else {
echo "Not Image";
}
No. When verifying files, you should never rely on headers. Headers can easily be modified by whomever is providing you with the file. A much more reliable option would be to use the PHP fileinfo extension.
<?php
// Fileinfo extension loaded
$finfoAvailable = false;
// Download the file
$imgUrl = 'https://cdn.discordapp.com/attachments/999921405858680857/1011168600410820679/1656572127-blog-2.JPG';
// Use basename() function to return the base name of file
$file_name = basename($imgUrl);
// Get the file with file_get_contents()
// Save the file with file_put_contents()
if (file_put_contents($file_name, file_get_contents($imgUrl)))
{
// Checks if fileinfo PHP extension is loaded.
if (!extension_loaded('fileinfo'))
{
// dl() is disabled in the PHP-FPM since php7 so we check if it's available first
if(function_exists('dl')
{
// Check if OS is Windows
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
if (!dl('fileinfo.dll'))
{
echo "Unable to load fileinfo.dll extension";
}
else
{
$finfoAvailable = true;
}
}
// OS is something else than Windows (like linux)
else
{
if (!dl('fileinfo.so'))
{
echo "Unable to load fileinfo.so extension";
}
else
{
$finfoAvailable = true;
}
}
}
else
{
echo "Unable to load PHP extensions as dl() function is not available";
}
}
else
{
$finfoAvailable = true;
}
// If fileinfo is available
if($finfoAvailable)
{
$finfo = finfo_open( FILEINFO_MIME_TYPE );
$mtype = finfo_file( $finfo, $file_name );
if(strpos($mtype, 'image/') === 0)
{
echo "File is an image";
}
else
{
echo "File is not an image";
}
}
else
{
echo "PHP extension fileinfo in not available";
}
}
else
{
echo "File downloading failed.";
}
?>
I have multiple sites, and have a text file on our main site with a list of domains to whitelist. I want to be able to edit this global file from each of the websites.
I have a couple of problems that I'm running into:
file_exists() and ftp_delete() are not finding the file even though it exists on the remote server.
ftp_fput() is adding a blank text file in the correct place with a zero filesize.
Here is my code:
// Check if we are updating the whitelist
if(isset($_POST['Submit'])){
// Make sure we have something to add or remove
if (isset($_POST['update']) && $_POST['update'] != '') {
// Get the text we need to add or remove
$add_or_remove_this = $_POST['update'];
eri_update_global_whitelist( $add_or_remove_this, 'add' );
// Say it was done
echo '<br>Script Completed...<br>';
}
}
echo '<form method="post">
<textarea name="update" cols="50" rows="10"></textarea><br><br>
<input name="Submit" type="submit" value="Update"/>
</form>';
function eri_update_global_whitelist( $string, $add_or_remove = 'add' ) {
// Validate the string
$domains = explode( ',', str_replace(' ', '', strtolower($string)) );
print_r($domains); // <-- WORKS AS EXPECTED
// Add invalid domains here
$invalid = [];
// Cycle
foreach ($domains as $key => $domain) {
// Check if it contains a dot
if (strpos($domain, '.') === false) {
// If not, remove it
unset($domains[$key]);
// Add it to invalid array'
$invalid[] = $domain;
}
}
print_r($domains); // <-- WORKS AS EXPECTED
// Only continue if we have domains to work with
if (!empty($domains)) {
// The whitelist filename
$filename = 'email_domain_whitelist.txt';
// File path on remote server
$file_url = 'https://example.com/eri-webtools-plugin/data/'.$filename;
// Get the file content
$file_contents = file_get_contents( $file_url );
// Only continue if we found the file
if ($file_contents) {
// Explode the old domains
$old_domains = explode( ',', str_replace(' ', '', $file_contents) );
print_r($old_domains); // <-- WORKS AS EXPECTED
// Are we adding or removing
if ($add_or_remove == 'add') {
// Merge the arrays without duplicates
$new_domains = array_unique (array_merge ($old_domains, $domains));
} else {
// Loop through them
foreach ($old_domains as $key => $old_domain) {
// Check if it matches one of the new domains
if (in_array($old_domain, $domains)) {
// If so, remove it
unset($old_domains[$key]);
}
}
// Change var
$new_domains = $old_domains;
}
print_r($new_domains); // <-- WORKS AS EXPECTED
// Include the ftp configuration file
require_once $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/eri-webtools-plugin/ftp_config.php';
// Establishing ftp connection
$ftp_connection = ftp_connect($ftp_server)
or die("<br>Could not connect to $ftp_server");
// If connected
if ( $ftp_connection ) {
// Log in to established connection with ftp username password
$login = ftp_login( $ftp_connection, $ftp_username, $ftp_userpass );
// If we are logged in
if ( $login ){
echo '<br>Logged in successfully!'; // <-- WORKS AS EXPECTED
// Make passive
ftp_pasv($ftp_connection, true);
// File path to delete
$file_to_delete = 'https://example.com/eri-webtools-plugin/data/'.$filename; // <-- NOT SURE HOW TO USE ABSOLUTE PATH ON REMOTE SERVER ??
// Delete the old file
if (file_exists($file_to_delete)) {
if (ftp_delete($ftp_connection, $file_to_delete)) {
echo '<br>Successfully deleted '.$filename;
} else {
echo '<br>There was a problem while deleting '.$filename;
}
} else {
echo '<br>File does not exist at: '.$file_to_delete; // <-- RETURNS
}
// Create a new file
$open = fopen($filename, 'r+');
// If we didn't die, let's implode it
$new_domain_string = implode(', ', $new_domains);
print_r('<br>'.$new_domain_string); // <-- WORKS AS EXPECTED
// Write to the new text file
if (fwrite( $open, $new_domain_string )) {
echo '<br>Successfully wrote to file.'; // <-- RETURNS
} else {
echo '<br>Cannot write to file.';
}
// Add the new file
if (ftp_fput($ftp_connection, '/eri-webtools-plugin/data/2'.$filename, $open, FTP_ASCII)) {
echo '<br>Successfully uploaded '.$filename; // <-- RETURNS
} else {
echo '<br>There was a problem while uploading '.$filename;
}
} else {
echo '<br>Could not login...';
}
// Close the FTP connection
if(ftp_close($ftp_connection)) {
echo '<br>Connection closed Successfully!'; // <-- RETURNS
} else {
echo '<br>Connection could not close...';
}
} else {
echo '<br>Could not connect...';
}
} else {
echo '<br>Could not find the file...';
}
} else {
echo '<br>No valid domains to add or remove...';
}
// Check for invalid domains
if (!empty($invalid)) {
echo '<br>Invalid domains found: '.implode(', ', $invalid);
}
}
Finally figured it out. I ditched ftp_fput() and replaced it with ftp_put(). Then I referred to the temporary file location on the local server instead of the fopen() like so:
ftp_put($ftp_connection, '/eri-webtools-plugin/data/'.$filename, $filename, FTP_ASCII)
So to explain what's going on (in case someone else runs into this):
// Name the temporary path and file, preferably the same name as what you want to call it.
// The path doesn't need to be specified. It just gets temporarily stored at the root and then deleted afterwards.
$filename = 'filename.txt';
// Create a new file by opening one that doesn't exist
// This will be temporarily stored on the local server as noted above
$fp = fopen($filename, 'w+');
// Write to the new file
fwrite( $fp, 'Text content in the file' );
// Add the file where you want it
ftp_put($ftp_connection, '/desination_folder/'.$filename, $filename, FTP_ASCII);
// Close the file
fclose($fp);
I ended up finding out that using ftp_put() will replace a file if it already exists, so there is no need to delete the old one like I was trying to.
I checked over some other answers before I came here to publish a question, I'm having trouble with the following script, no matter what i've tried it will not download a file from the FTP even after listing the files that are in directory (obviously)
Because I'm organised I like to simplify everything into a class,
class FTPHandler
{
private $connection;
public function FTPConnect($host, $user, $pass)
{
$ftp = ftp_connect($host);
$login = ftp_login($ftp, $user, $pass) or die("FTP: Login Failed");
if ($login) {
$this->connection = array("host" => $host, "user" => $user, "pass" => $pass);
return $ftp;
}
echo "FTP Login Failed";
}
public function ListAllFiles($stream, $dir)
{
ftp_pasv($stream, true);
$ls = ftp_nlist($stream, $dir);
return $ls;
}
public function get_conx_info() {
return $this->connection;
}
}
Using the following code:
define("APP_DIR", "./app/");
$ftp = new FTPHandler();
$handle = $ftp->FTPConnect("ftp.example.com.au", "exampleuser", "examplepass");
$files = $ftp->ListAllFiles($handle, APP_DIR);
foreach ($files as $val)
{
if ($val != "." && $val != ".." && $val != "processed") {
$local_file = $val;
$remote_file = APP_DIR.$val;
if (ftp_get($handle, $local_file, $remote_file)) {
echo "Successfully retrieved: $remote_file <br/>";
}
else
{
echo "Failed retrieving file: $remote_file <br/>";
}
}
}
My return is always:
Failed retrieving file: ./app/adsl-1989-csv.csv
Failed retrieving file: ./app/adsl-1989-sig.png
Failed retrieving file: ./app/dd-1964-csv.csv
Failed retrieving file: ./app/dd-1964-sig.png
Failed retrieving file: ./app/dd-1967-csv.csv
Failed retrieving file: ./app/dd-1967-sig.png
Failed retrieving file: ./app/dd-1972-csv.csv
Failed retrieving file: ./app/dd-1972-sig.png
Failed retrieving file: ./app/dd-1973-csv.csv
Failed retrieving file: ./app/dd-1973-sig.png
Failed retrieving file: ./app/dd-1974-csv.csv
Failed retrieving file: ./app/dd-1974-sig.png
Failed retrieving file: ./app/dd-1975-csv.csv
Failed retrieving file: ./app/dd-1975-sig.png
Failed retrieving file: ./app/dd-1978-csv.csv
Any assistance is highly appreciated as I have to have this automated to alleviate a few thousand per week off the employee budget.
I ended up discovering that the FTP server itself was at fault.
The error was fixed by changing from the default Active Ports as it was dropping majority of packets.
So if anyone out there is experiencing the same issue, worth taking a look at doing the same.
Thank you to Fred -ii- for your attempt in assisting me.
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.
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.