user6750159 user6750159 - 3 months ago 11
PHP Question

Php issues with file_get_contents

I am having trouble uploading an image into my database. Now the form send and processes successfully however it does not properly send when I put the variable
containing the file_get_contents information. So here is my code so far.

<?php
if (isset($_POST['submit-ads']))
{
$filename = $_FILES["file_uploaded"]["name"];
$filecontent = $_FILES["file_uploaded"]["tmp_name"];
$filesize = $_FILES["file_uploaded"]["size"];
$filetype = $_FILES["file_uploaded"]["type"];
if ($filetype == "image/png" || "image/jpeg" || "image/bmp")
{
if ($filesize > 0 && $filesize < 1000000000)
{
if ($newContent = file_get_contents($filecontent))
{
if ($conn = mysqli_connect("localhost", "root", "", "smartlea_browser_extensions"))
{
$newQuery = "INSERT INTO `food`(`image`, `imagename`, `access_token`) VALUES('".$newContent."', '".$filename."', '123')";
if ($query = mysqli_query($conn, $newQuery))
{
echo 'Works erase this line';
}
else
{
die("Could not insert file".mysqli_error($conn));
}
}
else
{
die('Could not connect to mysql');
}
}
else
{
die('ERROR getting file content. Invalid filepath');
}
}
else
{
die('Invalid filesize');
}
}
else
{
die('Image type not supported');
}
}
?>


Now this does not work. Again the issue lies on the line performing the query. When I put $newContent into the field. It throws this error

Could not insert fileYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'P�$�>�̒��(j�d�nf��� 5I�O7������$٧�Y�sqEM���' at line 1


Can someone shed some light on why this is not working? What I am trying to do is just upload an image into my database. Please do not recommend saving it into
a folder because there is a strict reason I am doing it this way. Now no ajax is involved. Just that PHP code (Which is a snippet but everything involved in
that function) The error is above if you need any other information let me know.

Answer

You need to use the function mysqli_real_escape_string to make sure your file contents doesn't break your sql query. Like so:

$newContent = mysqli_real_escape_string($conn, $newContent); // Now run the query

Even better, use prepared statements, read more on this here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Comments