kangkong
kangkong

Reputation: 21

How do i set a default image when the user doesn`t upload any image?

How can I set a default image to upload/'default image.jpg' to use it when user doesn't upload his own image?

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]);          
$location = "upload/" . $_FILES["image"]["name"];

Upvotes: 0

Views: 495

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

You should start by checking if there even was a file uploaded before you're trying to use it.

// Here's the default value
$location = "upload/default_image.jpg";

// Check if we got an uploaded file
if (!empty($_FILES['image']['tmp_name'])) {
    // We have an uploaded file, now let's handle it
    $image      = addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name = addslashes($_FILES['image']['name']);
    $image_size = getimagesize($_FILES['image']['tmp_name']);

    if (move_uploaded_file($_FILES["image"]["tmp_name"], "upload/" . $_FILES["image"]["name"]) {
        // Yay! It worked! Let's overwrite our default value!
        $location = "upload/" . $_FILES["image"]["name"];
    }
}

// The rest of your code

Upvotes: 1

gabe3886
gabe3886

Reputation: 4265

As mentioned in the comments, start with a default file name in the $location variable, and overwrite it if needed

$location = "upload/default image.jpg"; // the default file value
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);

if (move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]) 
{          
    // only change the location if something was uploaded
    $location="upload/" . $_FILES["image"]["name"];
}

Upvotes: 0

Related Questions