Reputation: 107
I have installed Apache server on one EC2 instance to serve files in Amazon EFS file system. Then I mount EFS under apache root /var/www/html
. I have created subfolders under this path. Now I would like to upload files to that folder from my web application using php.
I have tried with phpseclib/SFTP. Am I doing is right?
include_once($dir.'vendor/autoload.php');
$key = PublicKeyLoader::load(file_get_contents($ppkpath));
$ssh = new SFTP('ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('ec2-user', $key)) {
exit('Login Failed');
}else{
echo "Logged in";
}
$file_name = $_FILES['file_path']['name'];
$file_tmp =$_FILES['file_path']['tmp_name'];
$uploadPath = "/var/www/html/efsmount/Foldername";
//if (ssh2_scp_send($ssh, $_FILES["file_path"]["tmp_name"], $uploadPath, 0644)) {
if ($ssh->put($uploadPath, $_FILES["file_path"]["tmp_name"], SFTP::SOURCE_LOCAL_FILE)) {
$sftp->chmod(0644, $uploadPath);
echo "Uploaded";
}
else
{
echo "Upload Failed";
}
Output is: Upload Failed
. No other error messages.
Upvotes: 0
Views: 977
Reputation: 107
I have found the solution.
In order to upload files from local machine to the EC2 instance, you’ll need to allow the ec2-user account to manipulate files in the apache document root.
I did this steps to change directory permissions. After that I run my code. It upload the files successfully.
My modified code:
include_once($dir.'vendor/autoload.php');
$key = PublicKeyLoader::load(file_get_contents($ppkpath));
$ssh = new SFTP('xx.xxx.xxx.xxx');
if (!$ssh->login('ec2-user', $key)) {
exit('Login Failed');
}else{
echo "Logged in";
}
if (!empty($_FILES) && isset($_FILES)) {
$file_name = $_FILES['file_path']['name'];
$file_tmp =$_FILES['file_path']['tmp_name'];
$uploadPath = "/var/www/html/efsmount/Foldername/";
$path = $uploadPath.$file_name;
if ($ssh->put($path, $_FILES["file_path"]["tmp_name"], SFTP::SOURCE_LOCAL_FILE)) {
echo "Uploaded";
}
else
{
echo "Upload Failed";
}
}
Upvotes: 2