run a from php / apache where sftp perform connection and upload

Hi All, assume that I have a that runs perfectly if launched from a root shell.

sftp -oPort=22 user@localhost<<EOF
put /var/www/html/xml/file.xml /var/www/html/destination/file.xml

what I need is to run this script from php / apache, I’ve just try a lot and what give me the possibility to see something of what happen is a code like that :

$cmd = '/bin/sh /var/www/html/';

    if(exec("$cmd  2>&1", $output, $return_var)) {
    $upl.= "<br>";

I receive that : Array ( [0] => Could not create directory ‘/usr/share/httpd/.ssh’. [1] => Host key verification failed. [2] => Couldn’t read packet: Connection reset by peer ) 255

note the my key is just accept from the destination server because I can run the script in shell by root and I’m not sure to make something bad making the .ssh dir onto /usr/share/httpd/ where the sys after can make the know_hosts because in all the case in local continue to not work.

I think this is not the exact approach in CentOS suggestions ? always thanks Gio

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.


On Centos the default user that Apache is running with is called httpd that is why when you run the shell script through Apache it tries to create the /usr/share/httpd/.ssh folder.

A quick fix would be to generate a new ssh key and add it in the /usr/share/httpd/.ssh directory, then the Apache user would have access to the key that it needs to authenticate with against the destination server.

Though on another note, I would recommend figuring out a different way to do this as running shell commands with your Apache user is not exactly secure. You could for example create a cronjob and run this command at a specific time.

Regards, Bobby