Upload file to Amazon EC2 server from website by PHP

天涯浪子 提交于 2021-01-28 02:06:14

问题


I have a website ( bedatify.com) and I want to make a page within which people could upload their images to my amazon EC2 server. I checked similar questions like Unable to upload files on Amazon EC2 - php and how to upload to files to amazon EC2 but I don't figure it out how to manage it! Is this piece f code a good start? What should I change to let user upload pictures directly to my EC2 server from my website?

<?php
if(isset($_POST['image'])){
    echo "in";
    $image = $_POST['image'];
    upload($_POST['image']);
    exit;
}
else{
    echo "image_not_in";
    exit;
}


function upload($image){
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $id = "pleeease";

    $upload_folder = "/var/www/html/upload";
    $path = "$upload_folder/$id.jpg";

    if(file_put_contents($path, base64_decode($image)) != false){
        echo "uploaded_success"
    }
    else{
        echo "uploaded_failed";
    }
}

?>

回答1:


Just a Tipp: This is a perfect use case for S3.

So upload and retreive it from S3 within you Php Backend. If you upload it to your EC2 Instance the static files can fill up your instance space. What if the instance get terminated?

There is a PHP SDK you can use: https://aws.amazon.com/de/sdk-for-php/

An example would be:

use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;

$uploader = new MultipartUploader($s3Client, '/path/to/large/file.zip', [
    'bucket' => 'your-bucket',
    'key'    => 'my-file.zip',
]);

try {
    $result = $uploader->upload();
    echo "Upload complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
    echo $e->getMessage() . "\n";
}

I hope that helps!

Dominik




回答2:


uploadfile.php

<?php
$IAM_KEY = 'xxxx';
$IAM_SECRET = 'xxxx';
$bucket = 'xxxx';


require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-east-1',
    'credentials' => [
        'key' => $IAM_KEY,
        'secret' => $IAM_SECRET
    ]
]);


$file = $_FILES["fileToUpload"]["tmp_name"];


try {
    // Upload data.
    $result = $s3->putObject([
        'Bucket' => $bucket,
        'Key'    => 'xxx',
        'SourceFile' => $file
    ]);

    // Print the URL to the object.
} catch (S3Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}    
?>

index.html

<form action="/AWS/uploadfile.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>


来源:https://stackoverflow.com/questions/53832238/upload-file-to-amazon-ec2-server-from-website-by-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!