My php website is hosted in Debain Machine and I want to move a file from that Machine to another Debain which is connected through VPN.
I tried shell_exec and scp , as mentioned here.
<?php
$output = shell_exec('scp file1.txt dvader#deathstar.com:somedir');
echo "<pre>$output</pre>";
?>
I also tried using SFTP
<?php
class SFTPConnection
{
private $connection;
private $sftp;
public function __construct($host, $port=22)
{
$this->connection = #ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception("Could not connect to $host on port $port.");
}
public function login($username, $password)
{
if (! #ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username " .
"and password $password.");
$this->sftp = #ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function uploadFile($local_file, $remote_file)
{
$sftp = $this->sftp;
$stream = #fopen("ssh2.sftp://$sftp$remote_file", 'w');
if (! $stream)
throw new Exception("Could not open file: $remote_file");
$data_to_send = #file_get_contents($local_file);
if ($data_to_send === false)
throw new Exception("Could not open local file: $local_file.");
if (#fwrite($stream, $data_to_send) === false)
throw new Exception("Could not send data from file: $local_file.");
#fclose($stream);
}
}
try
{
$sftp = new SFTPConnection("localhost", 22);
$sftp->login("username", "password");
$sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
echo $e->getMessage() . "\n";
}
?>
Simply My problem is that I am not able to move a file from one machine, where my php applicaton is working , to another machine which is connected through VPN.
I installed proftpd and created a user as mentioned here,
Please note default port is 21. And make sure you restart proftpd:
service proftpd restart
The code I used to upload a file is:
index.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'a.txt';
$remote_file = 'b.txt';
$conn_id = ftp_connect('www.xxx.com',21);
$login_result = ftp_login($conn_id, "username","password");
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
die();
}
ftp_close($conn_id);
?>
Here a.txt is present in the same directory of index.php.
It will copy the file to the folder you mentioned for that particular user to access and name it b.txt.
Related
I am able to connect normally to filezilla (ftp). But the return from the ftp_fput () method returns false. This means that you were unable to upload the file.
Here is my code:
$server = "host.host.ws";
$user = "username";
$pass = "password";
// call function
$conn = uploadFTP($server, $user, $pass, $local_file, $remote_file);
function uploadFTP($server, $username, $password, $local_file, $remote_file) {
$connection = ftp_connect($server);
if (#ftp_login($connection, $username, $password)){
ftp_pasv($connection, true) or die("Unable switch to passive mode");
$fp = fopen('php://temp', 'r+');
fwrite($fp, 'content within the file');
rewind($fp);
// the file is not generated in the remote directory: /App/data/Json/File.json
if (ftp_fput($connection, '/App/data/Json/File.json', $fp, FTP_ASCII))
echo 'generated file!';
fclose($fp);
ftp_close($connection);
return true;
} else {
return false;
}
The file will only be generated when it displays the message: "generated file!", But it is not what is happening.
The code doesn't show any explicit errors, my question is, why doesn't this code generate the file in the directory? Could you share a solution to this problem?
Perhaps FTP gives access to the root directory and you need to provide the full path /var/www/App/data/Json/File.json
ftp_fput($connection, '/var/www/App/data/Json/File.json', $fp, FTP_ASCII)
The error is not visible because suppression is on.
Remove symbolically here "#" and use error_get_last() To see error information
if (ftp_login($connection, $username, $password)) {
echo 'Connected!';
if (ftp_fput($connection, '/App/data/Json/File.json', $fp, FTP_ASCII)) {
echo 'generated file!';
} else {
print_r(error_get_last());
}
} else {
return false;
}
You need to make sure the directory structure is created on the server /App/data/Json/ If not, then create it
I think it will be useful
php ftp make multiple directories
File is created on the FTP server, but its always 0 bytes large. Please give me a solution so that the file upload will working success.
I keep getting this warning:
Warning: ftp_put (): PORT command successful in C: \ xampp \ htdocs \ mailing \ teskirim-file-simpan2.php on line 30
FTP upload has failed!
My script is:
<?php
$ftp_server = "********";
$ftp_serverpath = "ftp.".$ftp_server;
$ftp_user_name = "********";
$ftp_user_pass = "***********";
$email_dir = "*******#*********";
$nyambungkeftp = ftp_connect($ftp_server);
if (false === $nyambungkeftp) {
throw new Exception('Unable to connect');
}
$loggedInnyambungkeftp =
ftp_login($nyambungkeftp, $ftp_user_name, $ftp_user_pass);
if (true === $loggedInnyambungkeftp) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
if ((!$nyambungkeftp) || (!$loggedInnyambungkeftp)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$dest = 'detectip.txt';
$source = 'C:\xampp\htdocs\persuratan\file2\detectip.txt';
echo $dest;
echo $source;
$upload = ftp_put($nyambungkeftp, $dest, $source, FTP_ASCII);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// close the FTP stream
ftp_close($nyambungkeftp);
?>
PHP defaults to the active FTP mode. The active mode hardly ever works these days due to ubiquitous firewalls/NATs/proxies.
You almost always need to use the passive mode.
For that call the ftp_pasv after the ftp_login:
ftp_pasv($nyambungkeftp, true);
See my article on FTP connection modes, to understand, why you typically need to use the passive mode.
Try two things:
Try FTP_BINARY instead of FTP_ASCII
Try to use passive mode doc here
I want to download file from SFTP so i created page which looks like it.
<?php
$username = "XYZ";
$password = "ABC";
$url ='FTP.abc.COM';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files))
{
foreach ($files as $file) {
if ($file != '.' && $file != '..')
{
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
?>
When i will call this page from browser. It will show error look like it.
Fatal error: Call to undefined function ssh2_connect() in page.php on line 6
if this method is correct then what should i edit in this page?
and if there is another method then suggest me that method. Thanks in advance.
You'll probably have better success with phpseclib, a pure PHP SFTP implementation. eg.
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');
?>
It has a number of advantages over libssh2:
http://phpseclib.sourceforge.net/ssh/compare.html
SSH2 functions are not standard functions in PHP. You have to install them first. See http://php.net/manual/en/ref.ssh2.php for more details.
Hi I have been struggling on this for one day. My ftp connection through putty is working file where i am passing public DNS and then upload .pem key for password. But when i am trying to do so through PHP it is not able to connect. Any help would be highly appreciated.
My PHP Code is:
$server='AMAZON EC2 Public DNS';
$username='root';
$password='**i copy pasted key from .pem file**';
try {
$con = ftp_connect($server);
ftp_pasv($con, true);
if (false === $con) {
throw new Exception('Unable to connect');
}
$loggedIn = ftp_login($con, $username, $password);
if (true === $loggedIn) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
ftp_close($con);
} catch (Exception $e) {
echo "Failure: " . $e->getMessage();
}
<?php
$ftp_server = 'your_amazon_instance_url';
$ftp_user_name = 'username';
$ftp_user_pass = 'password for ftp instance for user';
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name <br/>";
}
Thanks everyone for your effort. I had solved this using SSH Connection to Amazon Ec2
I am writing a PHP page, which stores FTP Account's address, Username and Password.
I need to validate them against the server and tell user if the credentials provided are working.
It is possible to fire system commands, System commands are preferable so that a reusable script could be written.
So can anybody tell me how do I validate the ftp credentials on bash? I am CentOS.
You can use ftp_connect() and ftp_login() :
<?php
$conn = ftp_connect($ftp_server);
$result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);
if ((!$conn) || (!result)) {
echo "Failed";
} else {
echo "Success";
}
ftp_close($conn);
<?php
function testFtpCredentials($server, $username, $password){
if(!is_string($server) or !strlen($server = trim($server))){
return null;
}
if(!is_string($username) or !strlen($username = trim($username))){
return null;
}
if(!is_string($password) or !strlen($password = trim($password))){
return null;
}
if(!$connection = ftp_connect($server)){
return false;
}
$result = ftp_login($connection, $username, $password);
ftp_close($connection);
return (bool)$result;
}
// How to use it.
var_dump(testFtpCredentials('ftp.server', 'username', 'password'));
?>
A function. Use it! Don't do system calls for such easy task.
You can use this code
try {
$con = ftp_connect($server);
if (false === $con) {
throw new Exception('Unable to connect');
}
$loggedIn = ftp_login($con, $username, $password);
if (true === $loggedIn) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
print_r(ftp_nlist($con, "."));
ftp_close($con);
} catch (Exception $e) {
echo "Failure: " . $e->getMessage();
}
PHP Has an FTP Module you can use to validate the credentials
Basic example from the docs
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// close the FTP stream
ftp_close($conn_id);
?>
Of course, if you really want to FTP on the command line via exec() or something, there are resources like these docs which will help.
A working example I just tried:
file: ftp.sh
#! /bin/bash
USER=user#domain.com
PASS=xxxxxxxxxxxx
ftp -inv domain.com <<EOF
user $USER $PASS
ls -l
file: index.php
$result = shell_exec('sh ftp.sh');
var_dump($result);