简体   繁体   中英

Upload file to Amazon EC2 server from website by PHP

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";
    }
}

?>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM