Upload longblob works in local but not in web server - php

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.

Related

$_POST returning null on server, but works fine on mamp localhost

Hello everyone,
I'm a Newbie web app developer. Recently, I finished my project on Mamp
and trying to move everything into server. Then odd things happened. The $_POST
function all of sudden does not work.
I googled this question for two days and tried many things. Like
changing apache config, reinstall some php package. I tried to use .htaccess, but did not figure out how it works. I just wondering is there
any other way to make this thing works as i tested on mamp.
By the way,i use LAMP in server.
Here is php code. var_dump($_POST) will return null and
var_dump($_REQUEST) will return array{}.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ID=$_POST['Client_ID'];
$name=$_POST['username'];
var_dump($_POST);
$sex=$_POST['sex'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
$time=$_POST['time'];
$company_name=$_POST['Company_name'];
$wechat_id=$_POST['Wechat_id'];
if ($sex==0){
$sex="female";
} else {
$sex="male";
}
$delOrnot=0;
$sql="INSERT INTO Client(client_id,owner_name,gender,cell_phone,email,time,company_name,delOrnot,department) VALUES ('{$ID}','{$name}','{$sex}','{$mobile}','{$email}','{$time}','{$company_name}','{$delOrnot}','{$wechat_id}')";
if($conn->multi_query($sql)===TRUE){
echo"New records created successfully";
}else {
echo "Error " . $sql . "<br>" . $conn->error;
}
$conn->close();
Here is html code.
<form action="member-add.php" method="post" class="form form-horizontal" id="form-member-add">
<div class="row cl">
<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>userID:</label>
<div class="formControls col-xs-8 col-sm-9">
<input type="text" class="input-text" value="" placeholder="" id="Client_ID" name="Client_ID">
</div>
</div>
<div class="row cl">
<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>username:</label>
<div class="formControls col-xs-8 col-sm-9">
<input type="text" class="input-text" value="" placeholder="" id="username" name="username">
</div>
</div>
</form>
And it works perfectly on mamp. I don't know what is wrong on my server configurations. Thank you for your kindly help!
In your form opening tag
<form action="member-add.php" method="post" class="form form-horizontal" id="form-member-add">
Try adding an enctype, this attribute specifies how the form-data should be encoded when submitting it to the server.
<form action="member-add.php" method="post" enctype="multipart/form-data" class="form form-horizontal" id="form-member-add">
This is how it should look.
You can read more about the different enctypes HERE.
How to debug this
I think however that its more important to see, a possible way to debug this. When you make a request to the server, that request is sent and you can view, what you have sent to the server as well as the servers response. In order to do that (Chrome is used for this example), open your google developer tools (just press F12), then go to Networking and click on the request that its made when you click the send button.
Is your php and HTML code is on same file?
I will suggest you to put your code at top of the file then check var_dump.

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

<input type="file" accept="image/*;capture=camera"> save image to database using php

I have a mobile web app form where I access the mobile device camera and capture a photo along with some other details captured within other fields in the form. Using php I save the information captured in the form to a mysql database sucessfully, but the image is not stored. I have searched for a resolution but cannot find anything on using php with
<input type="file" accept="image/*;capture=camera">
to store the image in a database. The database field is currently blob but this can change if needed.
The form works perfectly for all other data, so the issue is with my lack of understanding of how to handle images or files with php. can anyone help or point me in the right direction please. The basis of my code is pasted below.
The form save is working fine as the bus_name input saves to the database, but the bus_img record is blank.
HTML
<div data-role="page" id="view_record">
<div data-role="header">
Back
<div data-role="main" class="ui-content">
<form method="post" enctype="multipart/form-data" action="saveRecord.php">
<label for="bus_name">Business Name:</label>
<input type="text" name="bus_name" id="bus_name" placeholder="Enter Business Name">
<label for="bus_type">Business Type:</label>
<input type="text" name="bus_type" id="bus_type" placeholder="Enter Business Type">
<label for="bus_tel">Business Tel:</label>
<input type="text" name="bus_tel" id="bus_tel" placeholder="Enter Business Tel No">
<label for="bus_img">Business Photo:</label>
<input type="file" name="bus_img" id="bus_img" accept="image/*;capture=camera">
<label for="comments">Comments:</label>
<textarea name="comments" id="comments" placeholder="Enter Comments"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
PHP
<?php
$bus_img = $bus_name = "";
$servername = "";
$username = "";
$password = "";
$dbname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());}
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
$bus_name = $_POST["bus_name"];
$sql = "INSERT INTO tblLead(leadImage, occupantName)
VALUES ('$bus_img','$bus_name')";
if (mysqli_query($conn, $sql))
{
} else
{
echo "Error: " . $sql . mysqli_error($conn);
}
mysqli_close($conn);
exit();
}
?>
ANy help much appreciated. Thanks
Firstly, file handling requires $_FILES and not $_POST.
Your form tag does not contain a proper enctype to handle files.
As per the manual's example on files handling:
<form enctype="multipart/form-data" action="__URL__" method="POST">
Reference:
http://php.net/manual/en/features.file-upload.post-method.php
Then you need to escape that (file) data and there are a few ways to do this.
One of which being mysqli_real_escape_string($conn, $file)
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
Something you should also be using against all your data as it is presently open to an SQL injection.
I.e. and by replacing:
$bus_img = $_POST["bus_img"];
with:
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
And make sure that the file does not exceed the maximum uploaded size allowed/set on your server.
Use proper error checking also.
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php

Why are my php crud operations working in localhost, but not server?

I have a create function that works fine on localhost, but doesn't work on my server. What I mean is nothing gets stored in the database, whereas it does on localhost. I use winhost, by the way. Here's the code:
public function create ($title, $content, $date, $price){
$db = Dbclass::getDB();
$query = "INSERT INTO upcoming_albums (albums_title, albums_content, albums_date, albums_price, albums_img_path)
VALUES (:title, :content, :date, :price, :path)";
$statement = $db->prepare($query);
$statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
$statement->bindParam(':content', $content);
$statement->bindParam(':date', $date);
$statement->bindParam(':price', $price, PDO::PARAM_STR, 10);
$statement->bindValue(':path', $this->target_path, PDO::PARAM_STR);
$statement->execute();
}
Here's my form:
<form action="" enctype="multipart/form-data" method="post" id="form_c">
<label for="title">Title:</label>
<input type="text" name="title" id="title"/>
<label for="content">Content:</label>
<textarea name="content" id="content"></textarea>
<label for="date">Release Date (RRRR-MM-DD):</label>
<input type="text" name="date" id="date"/>
<label for="price">Price:</label>
<input type="text" name="price" id="price"/>
<label for="album_img">Price:</label>
<input type="file" name="file" id="album_img"/>
<span>
<?php
if (isset($_POST['btn_submit'])) {
$upcoming_album->uploadImg();
}
?>
</span>
<button type="submit" name="btn_submit">Submit</button>
</form>
and here's the code in the same file as the form that sets the create method:
<?php
require_once "../../controllers/admin/Album.php";
$upcoming_album = new Album;
if (isset($_POST['btn_submit'])) {
$upcoming_album->setFile();
$upcoming_album->create($_POST['title'],$_POST['content'],$_POST['date'],$_POST['price']);
}
$albums = $upcoming_album->read();
?>
The update method also does not work. However, the delete method works like a charm. CRUD operations work in localhost just fine.
Okies!. But in your view PHP crud works fine in local server but not server. The problem may be some issues like:-
You are using PDO's for inserting values in db (i.e) you enabled extensions on your localhost. so it works fine. but it may not enabled in server. so please try to enable in your PHP Configuration.
Or you may check this line., $db = Dbclass::getDB();
if the db is active or not by
echo ''; print_r($db); exit;

Upload images to MySQL 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.

Categories