user1257518
user1257518

Reputation: 147

adding multiple files PHP

I have the working script below but instead of image 1, image 2, image 3, image 4 being next to the boxes I want different names for each. Is there an easy way to do this? Thanks in advance!! Also where would I put header("Location: thankyou.php");
exit(); Because at the moment after putting this in, it just directs straight to the thankyou.php not the page below (document.php)

<?php
$max_no_img = 4; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for ($i = 1;$i <= $max_no_img;$i++) {
    echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while (list($key, $value) = each($_FILES['images']['name'])) {
    //echo $key;
    //echo "<br>";
    //echo $value;
    //echo "<br>";
    if (!empty($value)) { // this will check if any blank field is entered
        $filename = rand(1, 100000) . $value; // filename stores the value
        $filename = str_replace(" ", "_", $filename);
        $add = "upload/$filename"; // upload directory path is set
        copy($_FILES['images']['tmp_name'][$key], $add);
        echo $add;
        //  upload the file to the server
        chmod("$add", 0777); // set permission to the file.

    }
}
?>
</body>
</html>

Upvotes: 0

Views: 278

Answers (1)

Ofir Baruch
Ofir Baruch

Reputation: 10356

After this line:

$max_no_img = 4; 

Define an array with the names you're willing to give to each image:

$imgs_names = array('name for first image' , 'name for second image' , 'name for third image'); //and so on...

and instead of:

echo "<tr><td>Images $i</td><td>

write:

echo "<tr><td>Images ".$imgs_names[$i-1]."</td><td>

About using header , there's a problem since you already used echo. Add ob_start() at the beginning of the file and ob_flush() at the end of the file, now you can add the header() even after sending output.

EDIT2: Regarding your comment , there's an alternative way for redirection.

Add:

 $submit = true;

After:

chmod("$add", 0777); // set permission to the file.

And after:

    }
}

Add:

if(isset($submit) && $submit)
{
echo '<meta http-equiv="refresh" content="0; url=http://www.yoursite.com/thankyou.php">';
}

Upvotes: 1

Related Questions