Skip to content
Advertisement

How to upload pic to Amazon s3 bucket and subfolder and display using php foreach

I am using the code here: http://net.tutsplus.com/tutorials/php/how-to-use-amazon-s3-php-to-dynamically-store-and-manage-files-with-ease/

…to create a bucket and subdirectories for users who upload pics for personal use when logged in.

After uploading the pics successfully to the s3 server, they are displayed in the html file in a list as such:

 <ul id="sortable-list">

    <?php
    $i = 0;
    $contents = $s3->getBucket("bucket_name");

    foreach($contents as $file)
    {

    $fname = $file['name'];                 
    $furl = "http://bucket_name.s3.amazonaws.com/".$fname;  

        echo "<li class="default"><img src="$furl" width="100"></li>";

        {
            $i = 0;
        }

    }
    ?>
 </ul>

For some reason, the subfolder is getting recognized as a file inside the bucket and fills the first element of the $contents as http://bucket_name.s3.amazonaws.com/subfolder/, but of course is empty without referencing a filename.

The php I’m using is a modified form of page.php on the tutsplus.com tutorial referenced above. The code that pertains to the creation of the bucket and sub-directories is here:

    if(isset($_POST['Submit'])){

        $fileName = $_FILES['theFile']['name'];
        $fileTempName = $_FILES['theFile']['tmp_name'];
        $folderName = "subfolder/$fileName";

        $s3->putBucket("unique_id", S3::ACL_PUBLIC_READ);

        if ($s3->putObjectFile($fileTempName, "unique_id", $folderName, S3::ACL_PUBLIC_READ)) {
            echo "<strong>We successfully uploaded your file.</strong>";
        }else{
            echo "<strong>Something went wrong while uploading your file... sorry.</strong>";
        }
    }

Need help figuring out how to prevent the subfolder from being recognized as a file and creating an element in in the display. Thanks much

Advertisement

Answer

Several solutions:

  1. (Easiest) If it ends in a slash, it’s a folder. i.e. check substr($fname,-1) == ‘/’ and you have a folder

  2. (Neater) You can use the get_object_list call withe a PCRE to only get files that have something after the folder name. This works well if you know the folder name.

  3. (A possible, untested) Check $file[‘size’] – if zero then it’s either a folder or an empty file. As you don’t want empty files anyway, this could be an option.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement