ccc
ccc

Reputation: 51

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?

Here is the input file field.

<input type="file" name="pic" id="pic" size="25" />

Upvotes: 5

Views: 21942

Answers (3)

Brant Messenger
Brant Messenger

Reputation: 1451

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tmpFile = $_FILES['pic']['tmp_name'];
    $newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
    $result = move_uploaded_file($tmpFile, $newFile);
    echo $_FILES['pic']['name'];
    if ($result) {
         echo ' was uploaded<br />';
    } else {
         echo ' failed to upload<br />';
    }
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Upvotes: 2

Cory
Cory

Reputation: 1339

This is a simple example, it should work.

Although you probably want to add checking for image types, file sizes, etc.

  <?php
    $image = $_POST['pic'];
    //Stores the filename as it was on the client computer.
    $imagename = $_FILES['pic']['name'];
    //Stores the filetype e.g image/jpeg
    $imagetype = $_FILES['pic']['type'];
    //Stores any error codes from the upload.
    $imageerror = $_FILES['pic']['error'];
    //Stores the tempname as it is given by the host when uploaded.
    $imagetemp = $_FILES['pic']['tmp_name'];

    //The path you wish to upload the image to
    $imagePath = "images/";

    if(is_uploaded_file($imagetemp)) {
        if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
            echo "Sussecfully uploaded your image.";
        }
        else {
            echo "Failed to move your image.";
        }
    }
    else {
        echo "Failed to upload your image.";
    }
?>

Upvotes: 14

erisco
erisco

Reputation: 14319

http://php.net/file_upload covers just about everything you need to know.

Upvotes: 6

Related Questions