user3680780 user3680780 - 6 months ago 48
PHP Question

upload image with filename cannot be empty

I am doing a page with upload images and everything are fine. But the problem appeared when i accidentally uploaded image without choosing any images. A warning came out "Warning: file_get_contents(): Filename cannot be empty". I try to solve but the warning is still appeared. Did i need to add anything? What should i do in order to remove that warning? This is my php code

<form name="form1" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>select files</td>
<td><input type="file" name="f1"></td>
</tr>
<td><input type="submit" name="submit1" value="upload"></td>
<td><input type="submit" name="submit2" value="display"></td>
</table>
</form>

<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"image")or die(mysqli_error($con));;
if(isset($_POST["submit1"]))
{
$image = addslashes(file_get_contents($_FILES['f1']['tmp_name']));
$sql ="INSERT INTO images (username, image) VALUES('$_SESSION[username]','$image')";
$result=mysqli_query($con, $sql);

}if(isset($_POST["submit2"]))
{
$sql = "SELECT username, image FROM images where username = '$_SESSION[username]' ";
$result = mysqli_query($con,$sql);
echo"<table>";
echo "<tr>";
while ($row=mysqli_fetch_assoc($result))
{
echo "<td>";
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" height="100" width="100"/>';
echo "</td>";


}
echo "</tr>";
}

?>
?>

Answer

use this code

 if(isset($_POST["submit1"]))
    {
    if(empty($image))
    {

       $msg="Filename cannot be empty";
    echo "<script type='text/javascript'>alert('$msg');</script>";
    }
    else

    {

     $image = addslashes(file_get_contents($_FILES['f1']['tmp_name']));
        $sql ="INSERT INTO images (username, image) VALUES     ('$_SESSION[username]','$image')";
        $result=mysqli_query($con, $sql);
    }
    }
Comments