Secure FTP file download - download

I'm trying to download the most recent file with the extension add.zip via ftp
I'll preface this by saying I am not well versed in php and have created this frankenstein piece of code from a scattering of other codes.
here is my code
<?php
// set up basic ssl connection
$ftp = ftp_ssl_connect('myremotesite.com');
// login with username and password
$login_result = ftp_login($ftp, 'username', 'password');
if (!$login_result) {
// PHP will already have raised an E_WARNING level message in this case
die("can't login");
}
// get list of files on given path
$files = ftp_nlist($ftp, '/1668161919_DATA/*add.zip') or die("Could not find file");
$mostRecent = array(
'time' => 0,
'file' => null
);
foreach ($files as $file) {
// get the last modified time for the file
$time = ftp_mdtm($ftp, $file);
if ($time > $mostRecent['time']) {
// this file is the most recent so far
$mostRecent['time'] = $time;
$mostRecent['file'] = $file;
}
}
ftp_get($ftp, "/home/mysite/public_html/wp-content/uploads/data-zipped/target.zip", $mostRecent['file'], FTP_BINARY);
ftp_delete($ftp, $mostRecent['file']);
ftp_close($ftp);
?>
After some testing
<?php
// set up basic ssl connection
$ftp = ftp_ssl_connect('myremotesite.com');
// login with username and password
$login_result = ftp_login($ftp, 'username', 'password');
if ($login_result === TRUE) {
echo 'woot!';
} else {
echo 'doh!';
}
Returns a woot
but
// set up basic ssl connection
$ftp = ftp_ssl_connect('myremotesite.com');
// login with username and password
$login_result = ftp_login($ftp, 'username', 'password');
// get list of files on given path
$files = ftp_nlist($ftp, '/1668161919_DATA/*add.zip');
if ($files === TRUE) {
echo 'files found!';
} else {
echo 'doh! files not found';
}
?>
Cause a 504 error with no further information.
What am I doing wrong?
When I copy the URL to clipboard in FileZilla the data is sftp://username#myremotesite.com/1668161919_DATA
Am I even close to getting this right?
When I have tried using similar FTP file downloads in the past, it was with
ftp_connect
This is the first time I have been forced to use
ftp_ssl_connect
Ok, so I set up a testing environment and ran the script using ftp_connect instead of ftp_ssl_connect and the code worked fine.
I think I need to define my port as 22. But
$ftp = ftp_ssl_connect('myremotesite.com','22')
doesn't work. Can anyone assist?

Related

Can't open file created with Google Drive API

I need to create a document using Google Drive API, then give writer permission to logged in user and redirect them to created file. I'm trying to do it like this:
$credentials = storage_path('credentials.json');
$user = Socialite::driver('google')->stateless()->user();
$token = [
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
'expires_in' => $user->expiresIn
];
$client = new Google_Client();
$client->setApplicationName('Sheets');
$client->setScopes([Google_Service_Docs::DRIVE, Google_Service_Docs::DOCUMENTS]);
$client->setAccessType('offline');
$client->setAuthConfig($credentials);
$client->setAccessToken($token);
$service = new Google_Service_Docs($client);
$serviceDrive = new Google_Service_Drive($client);
$body = new Google_Service_Drive_DriveFile(array(
"name" => 'Testing ' . Lang::get('pls.export.name')
));
$doc = $serviceDrive->files->create($body);
$permission = $this->insertPermission($serviceDrive, $doc->id, $user->email, 'user', 'writer');
$url = "https://docs.google.com/document/d/" . $doc->id . "/edit#";
return Redirect::away($url);
This is the insertPermission function
function insertPermission($service, $fileId, $value, $type, $role)
{
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress($value);
$newPermission->setType($type);
$newPermission->setRole($role);
if ($role == 'owner') {
$permission = $service->permissions->create($fileId, $newPermission, array('fields' => 'id', 'transferOwnership' => 'true'));
} else {
$permission = $service->permissions->create($fileId, $newPermission);
}
if ($permission) {
return $permission;
}
return NULL;
}
After I run this code, I can see that the file was indeed created (I can get its id too), I also receive a notification on email that the file was shared with me, but I can't open the file itself. I'm getting a notification that page does not exist and "Sorry, unable to open the file at this time".
P.S. The same approach works perfectly fine when I'm creating a spreadsheet, instead of document. I can access the spreadsheet without any issues afterwards
After some research and testing I managed to fix the issue. The problem was I was using google drive api to create the file. Instead, I used Google Docs API like so:
$document = new Google_Service_Docs_Document(array(
'title' => 'Testing ' . Lang::get('pls.export.name')
));
$document = $service->documents->create($document);
Everything worked like a charm

In Drupal, how to validate the contents of a file uploaded using webforms and *not* upload if it fails validation?

I am implementing a site that accepts archives with directory structure in a specific fashion. I want to check the directory structure in the zipfile before accepting it. I tried the following (please see comments inline):
<?php
Using Webform Validation:
// using the webform validation module and its hooks
function testsuite_ziptest_webform_validation_validators()
{
return array(
"validate_zip_file"=> array(
'name' => "testsuite: Validate Zipfile" ,
'component_types' => array(
'select',
'file',
),
'description' => t('Verifies that the contents of the zipfile adhere to the specifications of testsuite.'),
)
);
}
function testsuite_ziptest_webform_validation_validate($validator_name, $items, $components, $rule)
{
$errors = array();
if($items)
{
switch($validator_name)
{
case "validate_zip_file":
drupal_set_message(t('Validate function called'));
foreach($items as $key=>$value)
{
drupal_set_message($key);
$v = _webform_validation_flatten_array($value);
drupal_set_message($v);
}
// tried to get the $fid and access the file using the fid.
// item_6 is the key of the file field that I selected while
// enabling webform validation.
// This fails saying no such file exists when the ziparchive
// object tries to open it.
$fid = $items['item_6'];
if(!empty($fid))
{
$za = new ZipArchive();
$file = file_load($fid);
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
break;
}
}
return $errors;
}
Using hook_file_validate
// this works, but there might be other files that may
// be uploaded to the site and I only want it to trigger
// when the file is uploaded as a part of a webform, not
// for all file uploads.
function testsuite_ziptest_file_validate($file)
{
if(!empty($file->filename))
{
$za = new ZipArchive();
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
}
Using Forms API (?)
// The following two methods that uses the form api on the webform
// has the same issue as the webform validation module. I can't get
// any reference to the file.
// There is a reference through a "completed form" key but I don't know
// if this is best practice
// die statements were used for debugging
function testsuite_ziptest_form_alter(&$form, &$form_state, $form_id)
{
if($form_id == 'webform_client_form_1')
{
array_unshift($form['#validate'], 'testsuite_ziptest_form_validate');
return $form;
}
}
function testsuite_ziptest_form_validate($form, &$form_state)
{
echo '<pre>'; print_r($form_state); echo '</pre>';
die();
$fid = $form_state['values']['submitted']['attachment'];
if(!empty($fid))
{
$za = new ZipArchive();
$file = file_load($fid);
$za->open($file->uri);
for($i = 0; $i < $za->numFiles; $i++)
{
$stat = $za->statIndex($i);
drupal_set_message($stat['name']);
}
$za->close();
}
else
{
}
die();
return;
}
Thanks!
I think you miss a point when you've done your function. You simply forgot to send the error back.
In the Webforms validation process, you have to send back some elements in the $errors array if something gone wrong.
$errors[$key] = t('%item is not good', array('%item' => $components[$key]['name']));
Here is an example of using this method.
In the Drupal form validation process, you have to use form_set_error if something is not good, with the combo name and the error message. The validation then stop automatically and the form will not be submitted...
And in the hook_file_validate method, you also have to send back an array of errors, witch will be use by the validator to stop the submission (with form_set_error).
Its Working Example :
function yourmoduleNma_file_validate($file,$validators)
{
$errors = array();
$filename = $file->filename;
$isValid_Extention_Size = explode('.',$filename);
if(count($isValid_Extention_Size) > 2){
$errors[] = 'Extention is not valid of this file';
}
elseif($file->filesize <= 0)
{
$errors[] = 'File size should be greater than 0 Bytes and less than 5 MB';
}
return $errors;
}

Session not remember, and why the session created each time I load the page?

I start to work with my project using laravel 5. I realized that it work fine in my local directory with session after I login to my site, But I just know that I got problem when I hosted my project to server. After I login each time, the session could not remember and recreated each time I loan the page. That cause the problem to me.
Laravel Login
public function postLogin(){
$hit = 0;
if(Request::ajax()){
$pw = Request::input('pw');
if(!empty($pw)){
$admin_pass = AdminPassword::first(['admin_pass']);
$ip_address = Request::ip();
if(!empty($admin_pass) && trim($admin_pass->admin_pass) == trim($pw)){
if(Auth::attempt(['username' => Request::input('username'), 'password' => Request::input('password'),'status'=>1])){
try{
$user = Auth::user();
$user->last_login = date('Y-m-d H:i:s');
$user->login_ip = $ip_address;
$user->save();
$permissions = Auth::user()->permission;
if(!empty($permissions) && count($permissions) >0){
session(['ROLE_PERMISSION'=>$permissions]);
}
$failed = FailedLogin::whereRaw('ip_address = INET_ATON(\''.$ip_address.'\')')->first();
if(!empty($failed)){
$failed->delete();
}
}catch (\Exception $ex){}
$url = Request::session()->pull('url.intended', '/');
return ['url'=>$url,'msg'=>'Successfully.','status'=>true,'hit'=>$hit];
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}
}else{
return redirect()->route('login');
}
return ['url'=>'','msg'=>'Try again.','status'=>false,'hit'=>$hit];
}
Please help me out. This is the final step of my project.
Thank you in advanced.
It's possible you have SESSION_DRIVER in your .env set to file - depending on your hosting environment, this could mean that your session isn't persisting due to each request being served from a different file server (common in cloud environments).
Try changing your SESSION_DRIVER to database.
Did you put the
session_start();
in all your pages?
If not it might be your problem, I d suggest you to add this in your index directly

Check if a file exist on remote server and save th url path in a magento attribute

Hi im trying to check if a file exist on a remote server and then save the url path to the file in a attribute on the product in magento.
This is how far i have got . i use some code from another function i have that imports images to my magento store. But i have never tested to only get the url path .
<?php
ini_set('display_errors', 1);
require_once('app/Mage.php');
Mage::app();
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$url = "http://www.imonline.se/media42/trailers/199151abe/swinks/hkmedia/";
foreach($_productCollection as $product)
{
//if(file_exists($serverurl))
{
$thispro = Mage::getModel('catalog/product')->load($product->getId());
$attributeValue = $thispro->getFaktaId();
$imgupdate = $thispro->getImgupdate();
if($thispro->getFaktaId()=="" || $thispro->getImage()=="no_selection")
{
if($attributeValue != "")
{
copy($url.$attributeValue );
$im = $attributeValue.".mp4";
if(file_exists)
{
$product->setFilmUrl($url.$im);
$product->save();
}
}
}
}
}
?>
file_exists - Checks whether a file or directory exists
To Check if Remote File Exists using PHP
$url = $url.$im;
$exist = file_exists_remote($url);
if($exist) {
echo 'File Exists';
$product->setFileUrl($url.$im);
$product->save();
} else {
echo 'File not found';
}

Session expiring for twitter oAuth

I am using Abraham Williams' oAuth library to update a status. The application does not have a UI (other than the prompt from Twitter for credentials. Instead, the user enters a URL in the browser.
When the URL is called, I get an error: "Could not post Tweet. Error: Reason: 1".
I inserted some test code, and it seems as if the session is getting lost in between transitions: $_SESSION['tweetmsg'] is set on initial call in index.php, but then when the switch to connect.php happens, it seems as if the session is lost. Any ideas?
Following is the source code:
index.php
<?php
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
session_start();
if (empty($_SESSION['access_token'])) {
$_SESSION['tweetmsg'] = create_tweet_text();
print "<script>self.location='./connect.php');</script>";
}
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
if (!isset($_SESSION['tweetmsg'])) {
exit('No tweet value in session or from form');
}
$tweetmsg = $_SESSION['tweetmsg'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
echo 'Tweet Posted: '.$tweetmsg;
}
else {
echo 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
session_destroy();
}
function create_tweet_text () {
return 'this is a test';
}
connect.php
?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK.'callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
print "<script>self.location='$url';</script>";
callback.php
<?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
$_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
print "<script>self.location='index.php';</script>";
}
Recently Twitter deactivated a number of http urls for oAuth and replaced them with https equivalents. If you can see the URL string http://twitter.com/oauth/request_token in the includes then it means you need to follow https://dev.twitter.com/discussions/10803 and change all the calls to https...

Resources