How to get file from SFTP server - php

I've been working at this for the last 2 days to no avail. I've also searched on StackOverflow for a solution but I couldn't find one that works for me.
I'm trying to pull a .csv file from a SFTP server. I found out you cannot do this with a default installation of PHP. I found 2 solutions.
1) Enable the ssh2_sftp extension in my PHP. I couldn't get this to work. I downloaded the required files, put them in my php/ext folder as directed, and modified the line in php.ini as required. Wouldn't work.
2) Use phpseclib. Couldn't get this to work as you need to use composer with it and composer wont load my php.ini because I have curl enabled?
Are there any other solutions for logging into a sftp server?
Appreciate the help.

Since it sounds like you have root access on the machine you're working with, why not use scp? It's a native php function so long as you have shell_exec enabled, and the user www-data (or whatever you call your httpd user) has shell access.
<?php
$connection = ssh2_connect('your_remote_server', 22); //remote connection
ssh2_auth_password($connection, 'username', 'password'); //authentication
ssh2_scp_recv($connection, '/remoteServer/whatever/yourFile.csv', '/localServer/yourNewFilename.csv'); //remote file -> local file
?>
NOTE
I have used this, but I also store the "username" and "password" in a MySQL database using bcrypt with a minimum cost of 12. More about that Here

Related

file_get_contents doesn't work with SSH Tunnel

I have created an tunnel(SSH) in order to access URL's that are blocked from my local PC. This works really well, I can for example access from the browser this url http://localhost:8888 and I will get the intended content. This URL also works with the REST Client that I'm using for testing. However, if I call it from PHP:
file_get_contents('http://localhost:8888')
I get this error each time: failed to open stream: Connection refused
So my guess is that file_get_contents doesn't work well with SSH tunnels. Is there maybe an alternative function that I could use for this purpose ?
I solved this problem using php-ssh2 package.
Instalation on Ubuntu 16
sudo apt-get install php-ssh2
Usage with user name and password:
$conn = ssh2_connect($ip, 22);
ssh2_auth_password($conn, $user,$pass);
ssh2_scp_recv($conn, '/remote_path', '/local_path');
Usage with id_rsa (after ssh-copy-id)
I recommend use this method because of we probably do not want paste plain password in source code.
$conn = ssh2_connect($ip, 22);
ssh2_auth_pubkey_file($conn, $user,
"/home/{$user}/.ssh/id_rsa.pub",
"/home/{$user}/.ssh/id_rsa", 'secret')
ssh2_scp_recv($conn, '/remote_file', '/local_file');
Additional info
Old name of this package: libssh2-php
Docs:
http://php.net/manual/en/function.ssh2-scp-recv.php
Connected question:
How to SFTP with PHP?
Is there also possibility of use:
file_get_contents("ssh2.sftp://{$user}:{$pass}#{$ip}:22{$remote_path}"))
but I do not know how to use it with id_rsa.pub.

PHP SSH2 PECL extension issues

Before I begin, I'm aware of phpseclib and from what I've ready it's the way you should normally go. Unfortunately I'm working on an older script, and I'm trying to avoid the time needed to set up phpseclib, test on local environment, put on production, test on production, refactor my script, etc. I'm hoping someone can help resolve my issue with ssh2.
I've used the following script to ssh a file to a client's server. It has worked fine for years.
<?php
$url = 'their.url.com';
$userName = 'name';
$password = 'pass';
$conn = ssh2_connect($url, 22);
$auth = ssh2_auth_password($conn, $userName, $password);
// Determine whether this is a file path that needs to be opened or not
$localFilePath = 'test123.txt';
$openFile = fopen($localFilePath, "r");
$fileName = 'test.txt';
// Their server path
$remoteFilePath = "/Orders/".$fileName;
if ($auth === true) {
// Transfer file
$sftp = ssh2_sftp($conn);
file_put_contents("ssh2.sftp://".$sftp.$remoteFilePath, $openFile);
}
WHAT HAPPENED:
My client moved his stuff to a different server. It broke the connection, he freaked out, etc., etc. He gave me updated credentials to the new server, and I have confirmed the protocal is SFTP - SSH File Transfer Protocal.
THE ISSUE:
The file transfer is no longer working after updating the ssh combo url/credentials.
WHAT I'VE TRIED:
I tried a test file transfer using Linux (not PHP) and it worked. I also ssh'd in using Filezilla and transferred a file that way, no problem. so I have confirmed that the host/user/pass combo is correct.
I dumped out the result of the file_put_contents, and it is false.
I dumped out $conn, $auth, and $sftp, and what "ssh2.sftp://".$sftp.$remoteFilePath looks like, and the results are (in order)
resource(27) of type (SSH2 Session)
bool(true)
resource(30) of type (SSH2 SFTP)
ssh2.sftp://Resource id #30/Orders/test.txt
Note that test.txt is a very tiny file to rule out file size issues.
I have also uninstalled and reinstalled the ssh2 PECL extension.
I am convinced this is due to an issue on their end, because this script has always worked before, I'm just baffled as to why things are failing now that they're on their new server, and I'm not sure what to do further to diagnose the problem. I can't think of any change that's been made to my server that would affect this.
Any ideas would be greatly appreciated.
Why not just use the ssh2.sftp:// stream directly?
file_put_contents("ssh2.sftp://{$userName}:{$password}#{$url}:22/{$remoteFilePath}", $openFile);
It should work without all the ssh connection, authentication, moving to sftp, etc..

WordPress Error establishing a database connection

I am new to WordPress, and I am trying to setup it at my local machine.
I am getting error like "Error establishing a database connection".
I tried all solutions from WP blogs,
created new user with all privileges
tired with root user.
created and deleted the target database multiple times.
Nothing is working.
Does anyone know anything else I can try?
Error establishing a database connection doesn't get any simpler than that. Your password, database name, user name, or host is wrong. See http://codex.wordpress.org/Common_WordPress_Errors#Error_Establishing_Database_Connection
Are you sure about using localhost as the server? Are you using MAMP or WAMP?
Try using Adminer http://www.adminer.org/ on your PC/Mac to find the database name, etc., and to admin the database when needed.
If you know can use a shell, try logging into the MySQL server and trying
mysql> show databases;
to list all databases to check your database name.
And try
mysql> mysqlserverinfo --server=root:pass#localhost -d --format=vertical
to get port info, etc. See http://dev.mysql.com/doc/mysql-utilities/1.6/en/mysqlserverinfo.html
I used MAMP for the MySQL server, and used its phpMyAdmin interface to create the database for WordPress and specify its user and password.
Host, for the new database, was "%" on the "User" tab of phpMyAdmin, which it said was supposed to allow any value, and did let me get a certain way through the process. But, I ended up going into "Login Information" under the "User" tab in phpMyAdmin, and changing "%" to "localhost".
That allowed me to finish setting up WordPress.
For future readers, if you are on OSX Yosemite (possibly other versions of OSX as well) and get "Error establishing a database connection" with a local WordPress installation, you may need to do the following:
sudo mkdir /var/mysql
sudo chmod 755 /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
Yosemite looks in the wrong location for the mysql.sock file, so creating this symlink to the correct location solves the problem.
The reason the missing symlink is a problem for WordPress specifically is because in your wp-config.php file, define('DB_HOST', 'localhost'); will not work. An alternative workaround is to change this value in your wp-config file to define('DB_HOST', '127.0.0.1');.
The OP didn't say what details they changed in their wp-config file to solve the problem (perhaps it was this DB_HOST parameter) so I just thought I'd post this since I wasted a lot of time trying to figure it out!
I tried all these suggestions and still couldn't get it to work. However, I had installed MySQL v8.0.12 and noticed that in the 'Users and Privileges' section, under the user I had set up, the 'Authentication Type' for the password was set to some kind of 'sha2' setting.
After trying 100 different things, I eventually fixed this by uninstalling then re-installing MySQL, and during the re-installation, specifically choosing the option button that refers to maintaining compatibility with previous versions of MySQL.
I think this resulted in my passwords not being automatically hashed, which enabled Wordpress to successfully connect to my MySQL database.
What worked for me:
-I moved the wp-config.php file into another folder
-Refreshed the browser and Wordpress will try to re-install
-choose a language
-A message should say Wordpress is already installed and will take you to the database setup page.
-Enter the same db name, username, password, and host (usually localhost).
-Got to www.yoursite.com/admin and you should be able to log in.
I had this issue and I have searched a lot but no one mentioned a fix like mine!
I checked my disk size and I found that my disk size was 100% used. I tried to clean up some of the files but still there were very large files taking up a lot of space. I kept looking and found that the mysql ./data folder occupied 90% of my disk space. It was the binlog files! Very large files I ended up cleaning them up using the Reset Master method. There is another method PURGE BINARY LOGS which didn't work for me. I had to use Reset Master. Just follow the steps and make sure you have a good backup. Good Luck.
Try this before anything! It fixed my issue.
sudo service mysql restart

How to update/replace php script on server

I am working on update feature for a CMS. But I stuck on this. The scenario is user will able to upload a zip file, the updater script will extract it and replace the old one.
I have a problem with replacing, I've done the following
<?php rename($old, $new);
I always get "Permission Denied"
using ftp_rename:
<?php
$conn = ftp_connect($host);
ftp_login($conn, 'user', 'pass');
ftp_rename($conn, $src, $dest);
I always get
Warning: ftp_rename(): Rename Failed. on....
Is there a proper way to do this ? thanks.
Depending on your linux distro, php actually executes command as a specific user. Check your apache (or whatever server you are using) settings and put the permission accordingly
For example in apache, it is set
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
You can then change that upload folder to be owned by www-data
For more information you can read this useful discussion
https://unix.stackexchange.com/questions/30879/what-user-should-apache-and-php-be-running-as-what-permissions-should-var-www

PHP Read/Write files on remote server

I'm making a utility that provides a GUI to easy edit certain values in a csv file on a remote server. My boss wants the utility in php running on the private webserver. I'm new to php, but I was able to get the GUI file modifier working locally without issues. The final piece now is rather than the local test file I need to grab a copy of the requested file off of the remote server, edit it, and then replace the old file with the edited one. My issue is uploading and downloading the file.
When I searched for a solution I found the following:
(note in each of these I am just trying to move a test file)
$source = "http://<IP REMOTE SERVER>/index.html";
$dest = $_SERVER['DOCUMENT_ROOT']."index.html";
copy($source, $dest);
This solution ran into a permissions error.
$source ="http://<IP REMOTE SERVER>/index.html";
$destination = $_SERVER['DOCUMENT_ROOT']."newfile.html";
$data = file_get_contents($source);
$handle = fopen($destination, "w");
fwrite($handle, $data);
fclose($handle);
This also had a permissions error
$connection = ssh2_connect('<IP REMOTE SERVER>', 22);
ssh2_auth_password($connection, 'cahenk', '<PASSWORD>');
ssh2_scp_recv($connection, '/tmp/CHenk/CHenk.csv', 'Desktop/CHenk.csv');
This solution has the error Fatal error: Call to undefined function ssh2_connect() which I have learned is because the function is not a part of the default php installation.
In closing, is there any easy way to read/write files to the remote server through php either by changing permissions, having the php extension installed, or a different way entirely that will work. Basically I'm trying to find the solution that requires the least settings changes to the server because I am not the administrator and would have to go through a round about process of getting any changes done. If something does need to be changed instructions on doing so or a link to instructions would be greatly appreciated.
Did you set the enable-url-fopen-wrapper in your php.ini?(only if your php version is older)
Please look # php remote files storing in example 2

Categories