SFTP disconnect() method not working with Laravel - php

I'm running the following script inside a Laravel job (OperatorSubmissionJob) to upload multiple files to the SFTP server. Everything working well. But I have to disconnect the SFTP connection to end the session after the uploading finished.
$count=1;
$sftp = Storage::disk('sftp');
foreach ($request['image'] as $key => $image) {
$image_array_1 = explode(";", $image);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = Carbon::now()->format('Ymd_his') . $key . '.jpeg';
// FTP server upload
$ftp_image_name = $ftp_path . "_" . $count . '.jpeg';
try {
$isUploaded = $sftp->put("$ftp_path/" . $ftp_image_name, $data, 'public');
if ($isUploaded) {
Log::info("FTP image uploaded (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
} else {
Log::info("FTP image upload failed (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
}
$count++;
} catch (\Exception $e) {
Log::error($e->getMessage());
}
}
// have to disconnect $sftp here. I have tried the following:
// $sftp->disconnect(); // error: undefined method disconnect
// $sftp->getDriver()->getAdapter()->disconnect(); // error: undefined method disconnect
// $sftp->getFilesystem()->getAdapter()->getClient()->disconnect();
//
Used techs:
Laravel 9 league/flysystem-sftp-v3
None of the disconnect scripts working in my case. Please help..
I have tried with the following scripts:
$sftp->disconnect();
$sftp->getDriver()->getAdapter()->disconnect();
$sftp->getFilesystem()->getAdapter()->getClient()->disconnect();

Related

PHP unlink() problem with files named with multiple extensions

I'm encountering an issue I've never come across before. I have some images uploaded as JPG or PNG with a duplicate of the image in WebP format, eg in this file naming convension:
https://example.com/uploads/memory-day.png >
https://example.com/uploads/memory-day.png.webp
If I delete a file through PHP using the unlink() function like normal, it works fine for everything else until I delete the PNG duplicate image. When I do that, the WebP file is also deleted and I can't see how it's happening -- is it a weird issue in the unlink() function with a file having a double extension? I can't seem to replicate it unless it's there's a WebP file involved.
For clarity, here's the PHP code that deletes the files (and yeah, I know it needs to be a prepare statement, I haven't updated it yet):
if(isset($_POST['delete'])) {
$countG = 0;
$err = 0;
foreach($_POST['delFile'] as $actionID) {
$action_id = $conn->real_escape_string($actionID);
$query = $conn->query("SELECT `filename`, `dir` FROM `fileuploads` WHERE `id` = '$action_id'");
$delF = $query->fetch_assoc();
$filenameDel = StripSlashes($delF['filename']);
$filenameDir = StripSlashes($delF['dir']);
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)){
if(unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel)) {
unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel);
}
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
$countG++;
} else {
$err++;
}
} else {
$err++;
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
//Remove from db if file is not there physically
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
}
}
}
if($countG > 0) {
$green = 1;
$message1 = "$countG File(s) Deleted!";
}
if($err > 0) {
$red = 1;
$message2 = "Error deleting $err files!";
error_log(print_r(error_get_last(), TRUE));
}
}

Mobile audio upload returning octet/stream

On desktop, the upload works correctly, but when I try to upload from a mobile device, it says that the extension is outside the array, and print returns octet-stream, any thoughts? I can't see what could be wrong. I have tried many audio extensions, checked MIME and tested with a few smartphones, no success.
if (isset($_POST['submit_atrack'])) {
$fileinfo=PATHINFO($_FILES["audio"]["name"]);
$newFilename=$fileinfo['filename'] . uniqid($usr_idLogged) . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["audio"]["tmp_name"],"atracks/" . $newFilename);
$location = 'atracks/' . $newFilename;
$formatos = array('audio/mpeg', 'audio/ogg', 'audio/mp3', 'audio/*', 'audio/wav');
$tamanho_max = 500000000; //500 mb
if (empty($_FILES['audio']['name']))
{
$upload_empty = urlencode("empty");
header("Location:playlist?newtrack=".$upload_empty . "&playlist=" . $selectedPlaylist);
exit;
}
else if (!in_array($_FILES['audio']['type'], $formatos))
{
$upload_incorrectformat = urlencode("incorrectext");
header("Location:playlist?newtrack=".$upload_incorrectformat . "&playlist=" . $selectedPlaylist);
exit;
}
else if (in_array($_FILES['audio']['type'], $formatos))
{
if($_FILES['audio']['size'] >= $tamanho_max)
{
$upload_maxsize = urlencode("maxsizereached");
header("Location:playlist?newtrack=".$upload_maxsize . "&playlist=" . $selectedPlaylist);
exit;
}
else
{
$atitle = mysqli_real_escape_string($connection, $_POST['atitle']);
$atag = mysqli_real_escape_string($connection, $_POST['atag']);
$atagcolor = mysqli_real_escape_string($connection, $_POST['atagcolor']);
mysqli_query($connection,"INSERT INTO tbl_users_atrack (atrack_title, atrack_path, atrack_tag, atrack_tagColor, atrack_playlistId) VALUES ('$atitle', '$location', '$atag', '$atagcolor', '$selectedPlaylist')");
$upload_success = urlencode("success");
header("Location:playlist?newtrack=" . $upload_success . "&playlist=" . $selectedPlaylist);
exit;
}
}
}

Connection from one EC2 instance to another EC2 instance using phpseclib

Hi I am using HANA on one EC2 and using by PHP which is already there in SUSE Linux to fetch the data from other Instance. The same code is working fine when i am trying t fetch data from my local system. But it is not working there neither it is showing any error. Please help. Here is my code:
error_reporting(1);
set_time_limit(0);
$date = date("d/m/Y-h:i:s") . "\n"; //to get today's date and time
$logfile = "file-transfer";
$fpath ="log/";
$filepath = $fpath .$logfile . '-log-' . date('Y-m-d') . '.csv'; //path of error log file
$fh1 = fopen($filepath, 'a'); //opening the error log file
fwrite($fh1, "Process Started#" .$date. "\n");
include('Net/SFTP.php');
include('Crypt/RSA.php');
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('key/private.ppk'));
$local_directory = 'sap/';
$remote_directory = '/var/www/';
$file = 'index.html';
$sftp = new Net_SFTP('ec2-XX-XXX-CCC-XX.ap-southeast-1.compute.amazonaws.com');
if (!$sftp->login('ubuntu', $key)) {
fwrite($fh1, "Login Failed" .$date. "\n");
}
else{
fwrite($fh1, "Login Successful#" .$date. "\n");
}
//$success = $sftp->put($remote_directory . $file,$local_directory . $file,NET_SFTP_LOCAL_FILE);
$success = $sftp->get($remote_directory . $file,$local_directory . $file);
if($success){
fwrite($fh1, "File Transferred Successfully#" .$date. "\n");
}
else{
fwrite($fh1, "Error:" .$date.error_get_last(). "\n");
}
Erroneously when i put wrong host name it throw Login failed message. But When i put the correct host name it is not working.
If you are using VPC for your networks inside AWS you need to open the ports in the Security Group so the EC2 instances in the same security group see and can access each other.
http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html

Why my PHP defined constants are not evaluated when file is executed using command line?

I am creating a plugin for a WP site and I have to make an initial import of a huge amount of files from another directory. (The plugin is working well, etc etc.) I want to run the import using command line. Everything is OK if executing on local (Windows), but when I execute from Linux bash the defined constants are not evaluated but printed as a string.
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
Is there any setting I have to make to enable evaluation of PHP defined constants? My website is running on Dreamhost server.
When I execute the folowing line:
[myserver]$ /usr/local/php5/bin/php /home/path/to/import.php
I get:
WordPress database error Table 'db_ro.ASCOR_RECORDINGS_TBL' doesn't exist for query INSERT INTO `ASCOR_RECORDINGS_TBL` ...........
The content of the file I execute:
<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/wp-load.php";
require_once "class/AscorDbHelper.php";
$origin = realpath("/path/to/files");
$upload_dir = wp_upload_dir();
$subdir = $upload_dir['subdir'];
mkdir(ASCOR_UPLOAD_DIR . "/" . $subdir, 777, true);
require_once $origin . "/classes/PConfFiles.inc.php";
$db = new AscorDbHelper();
$cf = new PConfFiles('/^PC_([0-9\-]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
$catPC = $db->addCategory("Special");
$catOther = $db->addCategory("Other");
if($list){
$pc = $db->addAuthor("Ciprian V.");
foreach($list as $rec){
$fileUrl = $subdir . "/" . $rec[0];
$desc = str_replace("-", " ", $rec[2]);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catPC->id, $pc->id, $desc, null, $rec[1]);
echo "Added: " . $rec[0] . "\n";
}
}
$cf = new PConfFiles('/^([0-9\-]+)\_([^\_]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
if($list){
foreach($list as $rec){
$authorName = str_replace("-", " ", $rec[2]);
$date = $rec[1];
$desc = str_replace("-", " ", $rec[3]);
$fileUrl = $subdir . "/" . $rec[0];
$authorId = $db->getAuthorIdOrSaveIt($authorName);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catOther->id, $authorId, $desc, null, $date);
echo "Added: " . $rec[0] . "\n";
}
}
echo "done";
The constants are defined in the main file of the plugin:
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
define("ASCOR_RECORDINGS_AUTHORS_TBL", $wpdb->prefix . "recordings_authors");
define("ASCOR_RECORDINGS_CATEGORIES_TBL", $wpdb->prefix . "recordings_categories");
define("ASCOR_RECORDS_PER_PAGE", 50);
define("ASCOR_EXTEND_DIR", dirname(__FILE__));
define("ASCOR_EXTEND_URL", plugins_url("", __FILE__));
define("ASCOR_NOTIFY_UPDATED", "updated");
define("ASCOR_NOTIFY_ERROR", "error");
define("ASCOR_UPLOAD_DIR", ABSPATH . "/wp-content/uploads/recordings");
Is the file loaded? Introduce a parse error into it and see if it fails. And try it on Windows too.

Delete system tmp file with COM and Word

I am using COM to convert dynamically created word docx to PDFs. Everything is working perfectly, but our c:\windows\temp\ directory is getting extremely large (and we have limited disk space on our C drive). Below is the code I am using to generate the PDF. Is there a way to delete the temp file that gets added to the system's temp directory after the file is closed? In addition, after the word doc is converted to pdf, we no longer need it (so it doesn't matter if deleting the tmp file corrupts the word doc).
/Word Doc to PDF using Com
ini_set("com.allow_dcom","true");
try{
$word = new com('word.application');
}
catch (com_exception $e)
{
$nl = "<br />";
echo $e->getMessage() . $nl;
echo $e->getCode() . $nl;
echo $e->getTraceAsString();
echo $e->getFile() . " LINE: " . $e->getLine();
$word->Quit();
$word = null;
die;
}
$word->Visible = 0; //don't open word gui on server
$word->DisplayAlerts = 0; //don't allow any alerts to open
//open doc
try{
$doc = $word->Documents->Open(DOC_LOCATION . "temp_doc/" . $filename . ".docx");
}
catch (com_exception $e)
{
$nl = "<br />";
echo $e->getMessage() . $nl;
echo $e->getCode() . $nl;
echo $e->getFile() . " LINE: " . $e->getLine();
$word->Quit();
$word = null;
die;
}
try{
$doc->ExportAsFixedFormat(DOC_LOCATION . "temp_pdf/" . $filename . ".pdf", 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
}
catch (com_exception $e)
{
$nl = "<br />";
echo $e->getMessage() . $nl;
echo $e->getCode() . $nl;
echo $e->getTraceAsString();
echo $e->getFile() . " LINE: " . $e->getLine();
$word->Quit();
$word = null;
die;
}
$word->Quit();
$word = null;
Don't say what version, but for XP- you can use a simple batch file to delete the files in \Documents and Settings\USER\Local Settings\temp\. Example:
C:
cd \Documents and Settings\USER\Local Settings\Temp
attrib -R -S -H *.* /S /D
DEL /S /F /Q *.*
Modify accordingly.

Categories