Using PHP to set up SSH connection and SFTP - php

I'm trying to set up a ssh connection, and later a sftp connection to transfer file via FTP to my server. I have used FileZilla to upload files successfully before.
These are my login terminal command and FileZilla login information:
ssh b0xxxxx#linux7.aa.bb.cc.dd
Host: sftp://linux7.aa.bb.cc.dd
Username: b0xx
Port: 22
Here is my php code:
<?php
$ftp_server = "b0xx#linux7.aa.bb.cc.dd";
$ftp_port = 22;
$ftp_user = "b0xx";
$ftp_pass = "##";
$connection = ssh2_connect($ftp_server, $ftp_port);
echo "Successful!\n";
if (ssh2_auth_password($connection, $ftp_user, $ftp_pass)) {
echo "Successful\n";
} else {
die ('Failed...');
}
$sftp = ssh2_sftp($connection);
ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>
Question 1: Can I just use ftp functions to upload/download file from my server?
Or do I must set up ssh?
Question 2: When I execute the code, the website only displays
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
which means that the code does not execute connection successfully. Does anyone know the cause of the bug?
Very much appreciate the help.

Seems SSH2 PECL extension is not installed. Install the extension and then try your code.

$ftp_server = "b0xx#linux7.aa.bb.cc.dd";
"b0xx#linux7.aa.bb.cc.dd" isn't a hostname. Hostnames can't have "#" in them. This is probably intended to be a "username#hostname" string, but ssh_connect() doesn't accept a string in this form.
Remove the username portion:
$ftp_server = "linux7.aa.bb.cc.dd";

Related

PHP ftp_put returning "Unable to build data connection: Connection refused"

I have a PC that is running some FTP via PHP that I know used to work 1-2 months ago, but now I return to it I find that the PC is no longer working. I know I have been using the PC but I cannot think of what might have changed.
The PHP is throwing out error messages reading
Unable to build data connection: Connection refused
...when I use the ftp_put() function.
The cut down code I am using is:
<?php
$trackErrors = ini_get('track_errors');
ini_set('track_errors', 1);
$server="***.***.***.***";
$port=21;
echo "<LI>Connecting to $server:$port<BR>";
$conn_id = ftp_connect($server,$port,9999999) or die("<BR>Unable to connect to ".$server.":$port server.");
if ( !$conn_id ) {
$errmsg = $php_errormsg;
echo "<BR><LI>ERR:$errmsg";
}
else {
$passive=false;
echo "<LI>Setting Passive Mode=$passive";
ftp_pasv($conn_id, $passive);
$user="*********";
$pass="*********";
echo "<LI>Connecting as $user/*****";
if (!ftp_login($conn_id, $user, $pass)) {
$msg = "Failed to login to $selected_server as $user; <BR>check logincredentials in the Settings";
echo "<BR><LI>$msg";
$errmsg = $php_errormsg;
echo "<LI>ERR:$errmsg";
return $msg;
}
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10000);
if (!#ftp_put($conn_id, "test.txt", "C:......test.txt", FTP_BINARY)) {
echo "<BR><LI>ftp_put failed";
$errmsg = $php_errormsg;
echo "<LI>ERR:$errmsg";
}
echo "<HR>Done";
}
?>
the output when running this as a webpage is
Connecting to ***.***.***.***:21
Setting Passive Mode=
Connecting as *******/*****
ftp_put failed
ERR:ftp_put(): Unable to build data connection: Connection refused
Done
The result is that the ftp_put() gives the error message and leaves a zero (0) byte file with the right filename on the server.
The strange thing is is that
the same code/connection info works on another laptop ok
the same connection info works ok using FileZilla when pushing a file
the problem occurs on several servers (ie. it's not just one specific destination that has the problem)
Also, this doesn't seem to have anything to do with the passive mode (it fails with and without this enabled)
Does anyone have any suggestions?
Thanks
Abe
You are using the active FTP mode. In the active mode the server tries to connect to the client. In most network configurations, that's not possible as the client machine is usually behind a firewall.
That's why the server fails with:
Unable to build data connection: Connection refused
It's specifically ProFTPD error message for this situation.
See my article on the active and passive FTP connection modes for details.
The code can work on other machines, if they have firewall disabled or if they have rules that allow incoming traffic on unprivileged ports.
FileZilla works because it defaults to the passive mode (as most modern FTP clients do).
You have claimed to try the passive mode too, yet to get the same error message.
That's because you are using the ftp_pasv call incorrectly.
You have to move the ftp_pasv call after the ftp_login.
$user = "*********";
$pass = "*********";
echo "<LI>Connecting as $user/*****";
if (!ftp_login($conn_id, $user, $pass)) {
// ...
}
$passive = true;
echo "<LI>Setting Passive Mode=$passive";
ftp_pasv($conn_id, $passive);
The documentation clearly suggests it:
Please note that ftp_pasv() can only be called after a successful login or otherwise it will fail.
For a similar issue (just with Pure-FTPd), see PHP upload via FTP - ftp_put() I won't open a connection to x.x.x.x (only to y.y.y.y).

Need help a simple php script to login to FTP to delete file via custom port

I got disconnected while applying Firewall rules via SSH. So, I can not SSH to my virtual server. As I have access to frontend, port 80, port 443 are open, PHP is running, best way to edit the /etc/ssh/sshd_config file's port. As I have the username/password for the root user, I saw the StackOver other questions. I am not great about PHP coding. I guess, this snippet can connect :
<?php
$ftp_server = "127.0.0.1";
$ftp_port = "443";
$ftp_user_name = "username";
$ftp_user_pass = "password";
$conn_id = ftp_ssl_connect($ftp_server, $ftp_port, "30");
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
echo ftp_pwd($conn_id);
echo "hello";
ftp_close($conn_id);
?>
I need help in modification to delete & upload or overwrite the /etc/ssh/sshd_config file. Thanks in advance.
FTPS (FTP over TLS/SSL) is not SFTP (over SSH).
You need to use PHP SSH2 functions, not FTP functions.
See for example How to SFTP with PHP?
You can also use phpseclib.

Why does SFTP via PHP fail, but succeeds in FileZilla on my Windows 8.1 machine?

In PHP, I cannot even get the SFTP connection to work. I have tried to use the native SFTP functionality (ssh_connect), and it fails to connect. I have also tried to use phpseclib, but it fails as well. Neither of my aforementioned attempts have provided much in the way of log info.
The native code:
if (!function_exists('ssh2_connect')) {
echo "dll not loaded properly"; //never see this, so I know it works
return false;
}
$connection = ssh2_connect('sftp.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
phpseclib library code:
include('Net/SFTP.php');
$sftp = new Net_SFTP('sftp.example.com');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
I have also tried to track all of the transactions via Fiddler to see if I at least see a connection being made, and I do see an error in the browser (below) that from googling may mean that a connection was made to the server, but no responses.
[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 17139 bytes.
Why am I able to connect to the URL with the username and password via FIleZilla, but not from within php? Do I need some other DLLs in PHP's /ext folder (e.g. php_openssl.dll, etc.)?
Thanks,
Sean

PHP Script Won't Upload to FTP Server -

Having spent hours on this, I am out of luck. This script worked perfectly until yesterday. The script generates XML and dumps it as a file (5kb) to a remote FTP server. The script has not changed, nor has our host changed anything. The FTP server company has changed something (they said IP change yesterday) (but claims nothing apart from this). This IP resulted in a different ftp_server which has worked fine.
When I attempt to run the script, I get the following error regardless of whether "ftp_pasv($conn_id, true);" is there or not / disabled:
Warning: ftp_fput() [function.ftp-fput]: Opening ASCII mode data connection in ...
Then it gives the line which contains "FTP_ASCII" below.
When I have the ft_pasv section there only (as per original script), an additional error of the following still appears with the following:
Warning: ftp_fput() [function.ftp-fput]: data_accept: SSL/TLS handshake failed in ...
This is for the same line as the above error.
They were originally on a self-signed SSL. Now, due to my issue, they are now on a 'correct' SSL issued by a well known company. No errors display on Filezilla upon connecting.
Importantly, I can upload via Filezilla with no issues, with or without passive mode
Code above the below code in the script is correct for generating the file as it appears on the script page, once loaded. It just won't dump the file on the server. Here is the connecting to the server bit:
//Connect to the FTP server
$ftp_server = 'import.ftpserverdomain.com';
$ftp_user_name = 'CORRECT-USERNAME';
$ftp_user_pass = 'CORRECT-PASSWORD';
// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server) or die("CONNECTION ERROR");
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("LOGIN ERROR");
$directory = ftp_pwd($conn_id); // /
ftp_pasv($conn_id, true);
$fp = fopen($filename, 'w');
fputs($fp,$file_contents);
fclose($fp);
$fp = fopen($filename, 'r');
$path_with_file = $directory.$filename;
if (ftp_fput($conn_id, $path_with_file, $fp, FTP_ASCII)) {
echo "Successfully Uploaded $File\n";
} else {
echo "There was a problem while uploading $File\n";
}
fclose($fp);
unlink($filename);
ftp_close($conn_id);
Any help is much appreciated. Sorry if I lacked any information. I'll be happy to provide any.
It sounds to me like PHP can't find your CA Certs, if you are running this on a linux box, this is something I have encountered before. Some searching should help but basically PHP's OpenSSL integration needs pointing at your cacerts directory so it can use these to validate the SSL connection it is attempting to make.
I fixed this issue. Hopefully this helps someone. The issue turned out to be server (HostGator). They do not allow FTP over TLS on a shared account.
Despite this working for a year, switching hosts resolved the issue.

php script on Windows hosting does not list ftp files (ftp_rawlist issues)

I'm trying to list some files from an external FTP server using php ftp functions on a Windows shared hosting, but I'm having several problems.
I firstly tried with a couple of web applications like ajaxplorer and net2ftp, but I got frustrated and I decided to make a very basic script for testing..
<?php
$ftp_server = "alinuxftpserver";
$ftp_user = "user";
$ftp_pass = "pass";
// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
// change temp folder (windows)
putenv("TMP=D://inetpub//webs//domain//net2ftp//tmp");
echo getenv('TMP');
// try to login
if (#ftp_login($conn_id, $ftp_user, $ftp_pass))
{
echo "Connected as $ftp_user#$ftp_server\n";
}
else
{
echo "Couldn't connect as $ftp_user#$ftp_server\n";
}
if(ftp_pasv( $conn_id, true ))
echo "Passive mode, it worked<br/>";
else
echo "Passive mode, it didn't work<br/>";
$contents = ftp_rawlist($conn_id, ".");
var_dump($contents);
ftp_close($conn_id);
die;
?>
On my localhost (linux) it returns an array, while on the windows hosting it returns:
Warning: ftp_rawlist() [function.ftp-rawlist]: php_connect_nonb() failed: No such file or directory (2) in D:\inetpub\webs\domain\ftp.php on line 26
bool(false)
Can't understand.. the directory should be "/" on the external ftp server and of course there are some files & folders (2 folders and 1 file).. In fact on my MAMP installation it works well.
Hosting guys told me that the server configuration is ok.
use ftp_pasv($conn_id, true); some ftp connections will work in passive mode only
I'm not 100% sure, but I guess, you should use $contents = ftp_rawlist($conn_id, "/");
instead of $contents = ftp_rawlist($conn_id, ".");
Check your FTP server logs. In my case, the pasv_address was set to a wrong IP address.
Better late than never... I had the same problem. With a Linux server everything worked great, but with Windows Server (many versions) we had many problems, including with ftp_nlist() returning an empty array. This worked for us, but I don't know why!
ftp_nlist($handler, '*');

Categories