Upload images to MySQL PHP - php

I'm trying to upload images to mysql, when i try with this code, it seems like it only insert databse, but no image filename uploaded to my server, can i know what went wrong
<form method="post" action="">
<?php
include ("setting/connect.php");
$g = mysql_query("select max(id) from abc");
while($id=mysql_fetch_array($g))
{
?>
<input type="text" name="id" value="<?php echo $id[0]+1; ?>" hidden/>
<?php }
?>
<div class="form-group">
<label>Image</label>
<input name="image" type="file">
</div>
<div class="form-group input-group">
<span class="input-group-addon">Title</span>
<input name="title" type="text" class="form-control" placeholder="">
</div>
<center><input class="btn btn-primary" type="submit" name="cmdadd" value="ADD" />
<button type="button" class="btn btn-danger">BACK</button></center>
</div>
<!-- /.panel-body -->
</form>
My php:
<?php
$id = $_POST['id'];
$title= trim($_POST['title']);
$path = "uploads/";
$tmp_name = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
if(isset($_POST['cmdadd'])){
if(empty($id)||empty($title))
{
echo "<center>Error!</center>";
}
if($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else{
move_uploaded_file($tmp_name,$path.$name);
$file="uploads/".$name;
include "setting/connect.php";
mysql_query("SET NAMES 'UTF8'");
$i = mysql_query("insert into abc values ('".$id."','".$file."','".$title."')");
if($i==true){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=danhsachtindang.php">';
}
//if($i==true){
//header('Location:index.php');
//exit;
//mysql_close();
//}
}
}
?>
Result from this: when i try to upload eg, picture.jpg, in the mysql table, it only came out "avatars/" on the column and HAVEN'T ANYTHING UPLOADED TO SERVER.

Your form lacks enctype="multipart/form-data" it's required when uploading files.
Modify it to read as:
<form method="post" action="" enctype="multipart/form-data">
Consult the manual: http://php.net/manual/en/function.move-uploaded-file.php
Also make sure that the folder has proper permissions set to write to.
Consult chmod on PHP.net for more information on setting folder/files permissions.
Sidenote #1:
Since you're using $path = "uploads/"; am assuming that you are running your code from the root of your server.
If this isn't the case, you will need to adjust it accordingly.
I.e.: $path = "../uploads/"; depending on the location of your file's execution.
Just an insight.
Sidenote #2:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
it only came out "avatars/" on the column and HAVEN'T ANYTHING UPLOADED TO SERVER
Are you trying to upload to avatars/ or uploads/?
Check that.

Related

MySQL insert stmt wont loop in file upload foreach loop

The code uploads the files and is supposed to submit the file path to the database so I can use the file paths elsewhere.
All the files upload fine in the loop, but for some reason, after it successfully submits the first MySQL stmt insert, it somehow bypasses the inserts that come after when it goes through the loop again, to upload the next file in the $_FILES[] superglobal
Here is the markup for the form
<?php
session_start();
include 'includes/functions.php';
drawHeader();
echo'
<div class="main_content_container">
';
if ( isset($_SESSION['userId'])) {
$amz_numb = $_GET['amz_numb'];
echo'
<form action="http://Localhost/Tierrashop.ca/includes/upload.php"
method="post" enctype="multipart/form-data">
Send these files
<input name="amz_numb" type="hidden"
value="'. $amz_numb .'"/><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<button type="file">Upload Files</button>
</form>
<a href="http://localhost/Tierrashop.ca/content_upload.php">
<button>Go back to product details... </button></a>
';
} else {
echo '';
}
//close of main content div
echo '</div>';
drawFooter();
?>
PHP file that launches upon form submission
<?php
include 'config.php';
if (isset($_POST['amz_numb'])) {
$uploadlocation = "../product_images/";
$amz_numb = $_POST['amz_numb'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $countfiles; $i++) {
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadlocation . $filename);
$directory_location = $uploadlocation . basename($filename);
chmod($directory_location, 0644);
//insert amz numb and path into db
$stmt = mysqli_prepare($conn, "INSERT INTO images ( amz_product_code, filepath )
VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $amz_numb, $directory_location);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}
Take a look at this please:
https://www.php.net/manual/en/mysqli-stmt.close.php
The user contributed note might be helpful for your case:
"if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with stmt->reset it worked for me."
This might be the better option: https://www.php.net/manual/de/mysqli-stmt.reset.php
Or - much better - use PDO!
UPDATE: More on PDO
If you don't know how to use the more modern standard "PDO" (if I recall it correctly it stands for "PHP Data Objects") this should be really helpful. I used this myself to make my own database handler.
https://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
The only caveat: The link above is a bit US centric. If you use it like that you will be in trouble if you support other languages in addition to English(US).
In //Define Configuration you should add:
define("DB_CHARSET", "utf8mb4");
Then in the database class itself you should add:
private $charset = DB_CHARSET;
"Set DSN" should consequently be modified like this:
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset;
Apart from these minor changes the example is still very useful.
Yaaaaa, none of that resetting stuff helped.
Figured out you don't have to keep preparing the statement, however not sure if that's what was stopping it.
I had it uploading the file, than was preparing the stmt to then execute.
In the php.ini file I had:
max_file_uploads = 3, which explained why only three files were getting inserted and locking up the script in the loop.
Also I changed post_max_size = 150mb thinking that this allows all those files to be stored in the tmp_name key in the $_FILES superglobal

Not able to upload more than 5 images in PHP

I'm trying to upload some images in my PHP application but I'm unable to do so. After some images, the post doesn't send data. It depends on the file size how many I can send like sometimes it works for 5 images sometimes for 3 images itself it throws this error.
<form action="store.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Top Image:</label><br>
<input type="file" name="topimg" class="form-control-file" style="padding-bottom:15px;">
</div>
<div class="form-group">
<label>Sub Images:</label><br>
<input type="file" name="img[]" class="form-control-file" id="exampleFormControlFile2" multiple required>
</div>
<center>
<button type="submit" class="btn btn-success" name="button">Save</button>
</center>
</form>
This is the form I'm using and it sends data to store.php
$uploaddir = '../../../img/gallery/';
$dirname = "/img/gallery/";
$newname = time() . basename($_FILES['topimg']['name']);
$fileup = $dirname . $newname;
$uploadfile = $uploaddir . $newname;
$img = '';
foreach ($_FILES['img']['name'] as $nam) {
$img = $img.",".$dirname.time().$nam;
}
$img = substr($img,1);
The above part is for setting the name and then the code to insert into my DataBase follows this (I think it's unnecessary so I left it out)
move_uploaded_file($_FILES['topimg']['tmp_name'], $uploadfile);
$count=0;
foreach ($_FILES['img']['name'] as $filename)
{
$tmp=$_FILES['img']['tmp_name'][$count];
$count=$count + 1;
move_uploaded_file($tmp,$uploaddir.time().$filename);
$tmp='';
}
Then this code to upload the files.
So when I try to upload the files it says "Undefined index: topimg" and "Undefined index: img" with errors that relate to these being invalid. I'm I doing the PHP part wrong or is it some setting in the server. I'm using MAMP pro if this info is needed
I think you need to change the upload_max_filesize and post_max_size directives in php.ini. See the php website https://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for more information on these directives.
To change the php.ini file for mamp pro, check this question.

Upload longblob works in local but not in web server

I have a php file that loads an image and receives a text, then sends them to another .php that runs a query to save the data in the database ... everything works fine in my local version, but in the version Web only the text is saved, the longblob does not.
I tried to debug using $_FILES['error'], mysqli_sql_exception, error_reporting, etc... but no warning or error appears.
I know there are similar posts and I checked them but none of them helped me
The version of php in local and server is 7.3 and the mysql property max_allowed_packet is 20M in both.
This send the data:
<form enctype="multipart/form-data" method="post" action="php/saveImage.php" enctype="multipart/form-data">
<div class="form-group">
<label for="classification" class="control-label">classification</label>
<input type="text" class="form-control" id="classification" placeholder="..." maxlength="50" name="classification" required>
</div>
<div class="form-group">
<label for="image" class="control-label">Image</label>
<input type="file" id="imagen" name="imagen" accept=image/*>
</div>
<input type="submit" class="btn btn-primary" value="Save">
</form>
and this get and save the data:
<?php
session_start();
include 'Connection.php';
$connection = new Connection();
$conn = $connection-> getConnection();
$classification = $_POST['classification'];
$blob = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$sql = "INSERT INTO gallery (image, title) VALUES ('$blob', '$classification')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "Success";
} else {
echo "Error";
}
?>
Update: I know the code has security vulnerabilities and bad practices, but is not the point now, is for a personal use only.
The problem was the type of data in the database was blob and not longblob.

How to upload ANY file type BLOB using PHP

Good Day.
So i am struggling with inserting a blob into a mySQL DB that is being sent from a form. in any case it fails on insert and i receive this screen when i use the var_dump to view the $sql variable.
My final point of this is to insert a file of any type into the db, regardless of size. Please note that i am trying to do be able to do this with any file type (zip, docx or otherwise).
here is my form
<form name="frmImage" enctype="multipart/form-data" action="upload.php"method="post" >
<label>Upload File:</label><br />
<input autocomplete="off" type="text" id="notes" style="width:50%" name="notes" placeholder="Write Something about this upload">
<input id="myfile" name="myfile" type="file"/>
<button style="width:20%" id="sendFile" name="sendFile" type="sendFile" value="sendFile">Submit</button>
</form>
and here is the PHP script that handles the input from the form.
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
session_start();
require_once('connect.php');
if (isset($_POST['sendFile'])) {
$imgData = ($_FILES['myfile']['tmp_name']);
$imageProperties = getimageSize($_FILES['myfile']['tmp_name']);
$notes = mysqli_real_escape_string($connection,$_POST['notes']);
$email = mysqli_real_escape_string($connection, $_SESSION['email']);
$comentity = mysqli_real_escape_string($connection,$_SESSION['entityname']);
$file_size = $_FILES['myfile']['size'];
$sql = "INSERT INTO `supportcontent` (`sentity`,`scontentdata`, `scontentnotes`, `suseremail`, `stype`,`ssize`)
VALUES('$comentity', '".file_get_contents($imgData)."','$notes','$email','{$imageProperties['mime']}','$file_size')";
var_dump($sql);
$current_id = mysqli_query($connection, $sql)
or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error($connection));
if (isset($current_id)) {
header("Location: landingpage.php?upload=success");
}
exit();
}
else{
echo 'pedestrian';
}
?>
So i am not sure whats wront, i am aware the issue is happening in my insert, but i am not exactly sure what could be causing it.
You might want to try the base64_encode function according to this answer: Error in SQL syntax when trying to upload image to BLOB field
I had the same issue once but this code worked fine on me:
Remember to change the column that stores the file to longblob

Can not rename a folder inside $_POST

I browsed many references in this site and found that this works successfully:
<?php
//tes to rename a sub folder
$oldDir="test";
$newDir = "testing";
if (!is_dir(dirname($newDir))) {
mkdir(dirname($newDir), 0777, true);
}
rename($oldDir,$newDir);
echo 'successfully renamed into';
?>
Now,I need to rename a category label (directory). But, It gave me error:
"warning"."No such file or directory in ...." when I have a category name inside $_POST, as in illustrated below:
First, submit.php
<?php
$displCat = $mydb->prepare("SELECT * FROM labelz ORDER BY label_name");
$displCat->execute();
$dataCat = $displCat->fetchAll();
foreach ($dataCat as $tampil_cat) {
$idcat=$tampil_cat['id'];
$cat=$tampil_cat['label_name'];
?>
<form action="u.php?id=<?php echo $idcat; ?>" method="post" name="frmupdatekat">
<div class="modal-body" style="overflow:auto;">
<h4>Edit Kategori: <?php echo $idcat.". ".$cat; ?></h4>
<input type="text" class="form-control" id="txtOldKat" name="txtOldKat" value="<?php echo $cat; ?>" style="border:0px;"/>
<input type="text" class="form-control" id="txtUpdateKategori" name="txtUpdateKategori"/>
<br />
<input type="submit" name="cmdUpdateKategori" id="cmdUpdateKategori" class="btn btn-success" style="vertical-align:middle; height:27px; padding:4px; font:12px Arial;" value="Update Kategori"/>
<br />
<br />
</div>
</form>
//.......
?>
Second, u.php
<?php
session_start();
include('conn.php');
if (isset($_GET['id'])){
$id=isset($_GET['id']) ? $_GET['id'] : '';
$txtOldKat=trim($_POST['txtOldKat']);
$txtUpdateKategori=trim($_POST['txtUpdateKategori']);
rename($txtOldKat,$txtUpdateKategori);
echo "<script>alert('Haadeeeehhh, ini koq error muluuuuuuuuuuuu!');</script>";
exit(); // stop to see if errors here.
if (isset($_POST['cmdUpdateKategori'])){
if (empty($_POST['txtUpdateKategori'])){
echo "<script>alert('Admin, Anda belum mengganti nama Kategori!');</script>";
echo "<meta http-equiv='refresh' content='0; url=adminz/kategori.php?target=kategori'>";
exit();
}
else{
$sql="SELECT * FROM labelz WHERE id=:id";
$sth = $mydb->prepare($sql);
$sth->execute(array(':id' => $id ));
//....... others code
?>
I then used previous scripts but not work even to use:
__DIR__
__dirname(__FILE__)
realpath()
etc.
I also check if the $old_cat exists and it really exists.
Here's the screenshot from filezilla (and also check in cpanel).
Then try using trim() in post value.
I also read here: http://php.net/manual/en/function.rename.php to see if I was wrong.
It seems, it doesn't work inside $_POST.
So, What should I do since I need it to do inside that $_POST.
Otherwise, you may have other solution to.
If you find this is duplicate question, pls let me know the link.
Thanks a lot for your advice/suggestion/solution.
Do some error checks in your code, make sure $old_cat exists prior to renaming, make sure $new_cat is in fact a valid file/folder name and doesn't already exist, make sure $old_cat and $new_cat are actually set.

Categories