devmonster
devmonster

Reputation: 474

uploading file error using move_uploaded_file

I have a problem with the move_uploaded_file function. The problem is when I choose the image I want to upload, it doesn't move into the file i set.

<?php
include("db_connect.php");
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp');
$path = 'images/';
if( $_FILES['image'])
{

$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
$final_image = rand(1000,1000000).$img;
// echo $img.$tmp.$final_image;
    if(in_array($ext, $valid_extensions))
    {
     $path = $path.strtolower($final_image);

        if(move_uploaded_file($tmp,$path))
        {
            echo "<img src='$path' />";
            $insert = $mysqli->query("CALL sp_uploadImage('".$path."')");
        }
        else 
        {
        echo 'invalid';
        echo '<pre>';
        print_r($_FILES);
        }   
    }

}
?>

Upvotes: 2

Views: 64

Answers (1)

Second2None
Second2None

Reputation: 1600

You should run proper conditionals for your if statements and provide an alternate route in case it doesn't go as planned.

<?php
include("db_connect.php");
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp');
$path = 'images/';
if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ''){
// check if file name is set and not empty
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
$final_image = rand(1000,1000000).$img;
    if(in_array($ext, $valid_extensions)){
        $path .= strtolower($final_image);
        if(move_uploaded_file($tmp,$path)){
            echo "<img src='$path' />";
            $insert = $mysqli->query("CALL sp_uploadImage('".$path."')");
        }else {
            echo 'Failed to move Files';
        }   
    }else{
        echo 'Not a Valid Extension';
    }
}else{
    echo 'No Files Found';
}
?>

This way it will return the appropriate message and let you know what's going wrong.

Upvotes: 1

Related Questions