2012-05-19 36 views
5

Estoy aprendiendo Amazon S3 usando S3 PHP Class. He subido todos mis archivos a mi bucket S3, ahora quiero crear enlaces para cada archivo disponible en mi bucket.¿Cómo crear un enlace de descarga para un objeto de cubo de Amazon S3?

¿Funcionará la siguiente función para mí?

public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) 
{ 

} 

    $s3 = new S3('access-key', 'secret-key'); 
    $s3->getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false); 

u otra función como get_object_url, pero no get_object_url() en mi clase S3.

Estoy usando Undesigned's Amazon S3 PHP class.

+0

posible duplicado de [¿Cómo se descarga un archivo con php y Amazon S3 SDK?] (http: // stacko verflow.com/questions/7389394/how-do-i-download-a-file-with-php-and-the-amazon-s3-sdk) –

Respuesta

10

Las siguientes pautas son válidos para la construcción de las direcciones URL S3:

http(s)://<bucket>.s3.amazonaws.com/<object> 
http(s)://s3.amazonaws.com/<bucket>/<object> 
+2

No se puede utilizar para descargar. http://stackoverflow.com/questions/7389394/how-do-i-download-a-file-with-php-and-the-amazon-s3-sdk –

+2

¡NOTA! Esto no funcionará para ti si tienes seguridad en tu cubo –

4

Si desea que el público acceder a la cubeta, es tan simple como

http: // [YourBucketName] .s3.amazonaws.com/[YourFileName]

Mientras configura permisos correctamente

Si le preocupa el abuso de descargas, querrá una URL autenticada (que supongo que quiere de la muestra de código). En cuyo caso, le sugiero que use el SDK de Amazon: http://aws.amazon.com/sdkforphp/, ya que contiene ejemplos de lo que necesita.

$s3->getObjectUrl($bucket, $filename, '5 minutes'); 

Docs: http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_getObjectUrl

+1

función 'get_object_url()' no funciona con mi biblioteca, qué hacer ahora. – Frank

+0

Función que no funciona con lib –

+1

Actualizada al método público actual "getObjectUrl" http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_getObjectUrl – Robbie

0

veo que la gente ya ha respondido a esto, pero yo quería añadir algún contexto más para aquellos quién puede tener un cubo seguro (requiere acceso). Tenga en cuenta que no tiene que generar las URL si habla directamente con el depósito S3, entonces puede usar 'file_get_contents', etc., pero es mucho más lento ya que no puede usar solicitudes de curl múltiple (para la velocidad). Sin embargo, podría usar pthreads si tiene una versión más reciente de php.

INSTALACIÓN: Instale el archivo de la clase S3 para Amazon, hay formas fáciles de agregarlo usando el compositor o simplemente descargando el archivo S3.php manualmente.

que no esté garantizada: (ver otros mensajes sobre este asunto, básicamente utilizar la URL)

http(s)://<bucket>.s3.amazonaws.com/<object> 
http(s)://s3.amazonaws.com/<bucket>/<object> 

HTTPS protegida (cuando se ha protegido su cubo):

https://amazon.com/file/you/wanted.xxx?ID:XXXXX?SIG:YYYYY 

(1) Cree una URL https: // y use la herramienta multi curl para obtener todas al mismo tiempo (recomendado).

Un simple ejemplo:

$url = /path/to_the/file_name/file.ext 

//note check amazon to confirm the path which will contain only "_" and no spaces. 

$s3 = new S3($awsAccessKeyID, $awsSecretKey); 
$curls[] = $s3->get_object_url($bucketName, $uri, '1 hour'); 
var_dump($results = multiCurlRequest($curls));  

más información:

http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.S3.S3Client.html#_getObjectUrl http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation

FYI:

function multiCurlRequest($curlList = array(),$user = '', $pass = '',$timeout = self::MULTI_REQ_TIMEOUT_SECS, $retTxfr = 1) { 

    if (empty($curlList) || count($curlList) == 0) return false; 

    $master = curl_multi_init(); 
    $node_count = count($curlList); 

    for ($i = 0; $i < $node_count; $i++) { 
     $ch[$i] = curl_init($curlList[$i]); 
     curl_setopt($ch[$i], CURLOPT_TIMEOUT, $timeout); // -- timeout after X seconds 
     curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, $retTxfr); 
     curl_setopt($ch[$i], CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
     curl_setopt($ch[$i], CURLOPT_USERPWD, "{$user}:{$pass}"); 
     curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true); 
     curl_multi_add_handle($master, $ch[$i]); 
    } 

    // -- get all requests at once, finish when done or timeout met -- 
    do { curl_multi_exec($master, $running); } 
    while ($running > 0); 

    $results = array(); 

    // -- get results from requests -- 
    for ($i = 0; $i < $node_count; $i++) { 
     $results[$i] = curl_multi_getcontent($ch[$i]); 
     if ((int) curl_getinfo($ch[$i], CURLINFO_HTTP_CODE) > 399 || empty($results[$i])) { 
      $this->set_request( [ ['label' => '404', 'href' => $results[$i], '404' => '1' ] ]); 
      unset($results[$i]); 
     } 
     curl_multi_remove_handle($master, $ch[$i]); 
     curl_close($ch[$i]); 
    } 

    curl_multi_close($master); 
    if (empty($results)) return false; 
    //$results = array_values($results); // -- removed as we want the original positions 
    return $results; 
} 
Cuestiones relacionadas