Not able to insert images into database using wpdb - php

I am trying to run this code to take image input from front end. I know I can't simply upload images using just this $_POST['img']. I read that I have to use file_get_contents() for this purpose. But I am new to this , I don't know How exactly to use file_get_contents()
However I tried this code, but I am unsuccessful in inserting.
<form action="" method="post">
<label id="img">image: <input type="file" name="img" id='media'/></label>
<input type="submit" name="Submit" value="upload"/>
<?php
global $wpdb;
if($_POST['Submit'])
{
$image=$_POST['img'];
if($wpdb->insert(
'image',
array(
'image' => $image
)
) == false) echo 'Database Insertion failed';
else echo 'Database insertion successful<p />';
}
?>
This did not work. After this I tried this. But still unsuccessful.
<form action="" method="post">
<label id="img">image: <input type="file" name="img" id='media'/></label>
<input type="submit" name="Submit" value="upload"/>
<?php
global $wpdb;
if($_POST['Submit'])
{
$image=$_POST['img'];
$item = file_get_contents($_FILES['img']['tmp_name']);
if($wpdb->insert(
'image',
array(
'image' => $item
)
) == false) echo 'Database Insertion failed';
else echo 'Database insertion successful<p />';
}
?>
for this I am getting a warning
Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\kite\wp-content\plugins\php-code-widget\execphp.php(27) : eval()'d code on line 11
Somebody please help me out.
And in my database, in the table "image" the column "image" has the data type BLOB, not sure if the problem is with this.
Thanks in advance

For file uploads you should add, enctype="multipart/form-data"
<form enctype="multipart/form-data" action="" method="post">
^ ^
First upload to some folder and then use file_get_contents()
if (move_uploaded_file($_FILES['file']['tmp_name'], "your path". $_FILES["file"]['name'])) {
// image will get uploaded here
}
Then use
file_get_contents("new path")

Related

Uploading multiple images to server and database using PHP and a single HTML input [duplicate]

This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 1 year ago.
Could someone please assist as I would like to upload multiple images to the server as well the image names to the database.
The below code works for uploading the images to the server:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post" enctype='multipart/form-data'>
<input type="file" name="file[]" multiple>
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// 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], dirname(__DIR__)."/img/".$filename);
}
} else {
// Load view with errors
$this->view('posts/add');
}
}
I am also able to upload the 3 image names when using the below code with 3 separate inputs:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post">
<input type="file" name="image1">
<input type="file" name="image2">
<input type="file" name="image3">
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'user_id' => $_SESSION['user_id'],
'image1' => trim($_POST['image1']),
'image2' => trim($_POST['image2']),
'image3' => trim($_POST['image3']),
];
// Validated
if($this->postModel->addPost($data)){
flash('post_message', 'Post Added');
redirect('posts');
} else {
die('Something went wrong');
}
} else {
$data = [
'image1' => '',
'image2' => '',
'image3' => ''
];
$this->view('posts/add', $data);
}
}
Could someone please advise on how I could combine the code, in order to use a single file input for uploading the images to server, as well as the image names to the database?
Complete Code
<form method='post' action='' enctype='multipart/form-data'>
<input type="file" name="file[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
PHP
<?php
if(isset($_POST['submit'])){
$imageName =$_FILES['file']['name'];
// 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],'upload/'.$filename);
//insert code
$query = "insert into images(images) values('".$imageName."')";
mysqli_query($con,$query);
}
}
?>
Use this input code -
<input type="file" name="image[]" id="file" multiple>
And count file in php file then use loop for iterating file like-
$counts = count($_FILES['image']['name']);
for($i=0;$i<$counts;$i++){
//uploading code here
}

Issue with uploading multiple files on a single html page using php

I am trying to build a web page where users can edit images portrayed on their public pages. There are 3 images that display on their public page and I've set up 3 HTML forms in order to handle the 3 separate files.
I only have 1 listed below because once I figure out the fix to 1 I'll be able to duplicate the fix to the other 2,
I have other upload pages on my website and they work fine, but for some reason this page is giving me trouble. I can select a file but when I want to upload it my php code doesn't read that there is anything being posted.
*I've commented out the function call (I know it works) I just need to know why my php code won't read that there is a file there.
If I had to guess it'd be something with how it's named or how it's being tossed to the php code.
The code looks like this:
<div class="academic" style="width:250px;">
<br>
<?php
if(isset($_FILES['aca']) === true)
{
echo 'please print'; //It doesn't
if(empty($_FILES['aca']['name']) === true)
{
echo 'Please choose a file! <br>';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['aca']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['aca']['tmp_name'];
echo '<br>';
echo '<br>';
print_r($_FILES['aca']['tmp_name']);
echo '<br>';
echo '<br>';
if(in_array($file_extn, $allowed) === true) {
//upload_image($file_temp,$file_extn);
echo 'You have uploaded a picture!';
echo '<b><h3>Press submit again to finish the upload</h3></b>';
//echo "<script>window.top.location='../hidden/viewPNM.php?id=$permi'</script>";
}
else
{
echo 'Incorrect File Type!! <br> Allowed: ';
echo implode(', ', $allowed);
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="aca" id="aca">
<input type="submit" value="Upload">
</form>
</div>
</span>
Okay...here is what you can try to do:
Move the whole PHP code UNDER the form code. I remember that sometimes wierd bugs with that were happening, and the code didnt run
If that doesnt work, do following:
Change <input type="file" name="aca" id="aca"> to <input multiple="true" type="file" name="aca[]" />
Add this code above the submit button: <input type="hidden" name="sendfiles" value="Send Files" />
Replace if(isset($_FILES['aca']) === true) with if(isset($_POST['sendfiles']))
If this doesn't work, I can offer you a way to allow multiple files being uploaded from one button. (Took the code from my website I made before)

$_FILES['file'] does not work for a simple procedure

Unable to upload an image
The problem is that the image does not get set as `$_FILES['file'].
The code is very simple but still cannot get the obvious outcome.
Have marked the unexpected trouble with 3* i.e. '*'
I don't know what I am doing wrong.
Thanks in advance, your suggestions and comments are much appreciated.
Happy Coding!
<--- NOTE: HTML form below PHP --->
<?php
//CHECK: Submit
if(isset($_POST['submit']))
{
echo 'form submitted <br />';
//CHECK: File by POST
if(isset($_POST['file']))
{
echo $_POST['file'] . '<br />';
unset($_POST['file']);
}
//CHECK: File if 'isset' $_FILES
if(isset($_FILES['file']))
{
print_r($_FILES['file']);
}
else
{
echo '$_FILES not set!';
}
}
?>
<!-- HTML FORM -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5M">
Image: <input type="file" name="file" size="50" id="file" />
<br /><br />
<input style="margin-left:15%;" type="submit" name="submit" value="Upload"/>
</form>
Please correct your form action you missed `echo :-
<?php echo $_SERVER['PHP_SELF']; ?>
^
As your comment, your are getting error 2 that means:-
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was
specified in the HTML form.
Please refer this solution as well File upload ['ERROR']= 2
Following correction are needed.
1 - Add an echo in action="<?php $_SERVER['PHP_SELF']; ?>" as action="<?php echo $_SERVER['PHP_SELF']; ?>"
2 - Why your are finding file in $_POST, need a check to it
if(isset($_POST['file'])){
echo $_POST['file'] . '<br />';
unset($_POST['file']);
}
3 - You have commented your out put is from line print_r($_FILES['file']);
Array (
[name] => imagename.jpg
[type] => [tmp_name] =>
[error] => 2
[size] => 0
)
tmp_name not getting blank that means your file is not creating its temporary file to upload.
So, check temp upload file path in php.ini make sure it is working
different value in name attribute
Image: <input type="file" name="fileupload" size="50" id="file" />
<?php
if(isset($_POST["submit"]))
{
$name=$_FILES['fileupload']['name'];
$name=$_FILES['fileupload']['tmp-name'];
$name=$_FILES['fileupload']['size'];
}
?>

<input type=file> not getting image

I am trying to get image file name by tag, But when I check it through isset($_FILES['imgFile']), it returns always false.
Here is my HTML tag for getting image file:
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
Here is my php code to retrieve it:
if(isset($_FILES['imgFile']))
{
$img = $_FILES['imgFile']['name'];
echo $img";
}
else
{
echo "Image not set";
}
It always generate "Image not set" as an output though I have selected an image.
Are you using the correct enctype on the form?
<form enctype="multipart/form-data">
This is required when using a file upload element.
just use:
enctype="multipart/form-data"
Say this is your form:
<form action="same_page.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
<input type="submit" name="upload" value="Upload" />
</form>
and your php code to retrive name of the image is in the same page where the form is, then your code should be like this:
<?php
if (isset($_POST["upload"])) {
if (isset($_FILES['imgFile'])) {
$img = $_FILES['imgFile']['name'];
echo $img;
} else {
echo "Image not set";
}
}
?>
But if your php code is in another page, then you only need to use enctype="multipart/form-data" in the form as mentioned in the other answers.

How can I debug problems with move_uploaded_file?

I have a form like
<form action="send.php" method="post" enctype="multipart/form-data">
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" />
</div>
<div>
<label for="image">Image</label>
<input type="file" name="image" />
</div>
<input type="submit" value="Send" />
</form>
PHP like
echo '<pre>'; print_r($_FILES); echo '</pre>';
if (move_uploaded_file($_FILES['image']['tmp_name'], 'images/' . $_FILES['image']['name'])) {
echo 'ok';
} else {
echo 'error!';
};
I keep getting error the print_r looks like
Array
(
[image] => Array
(
[name] => Untitled-1.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpprWdjN
[error] => 0
[size] => 61768
)
)
Activate error reporting, then you should see the error thrown by move_uploaded_file telling you what's wrong.
Your $_FILES looks file, error=0 means the upload completed successfully. Most likely it's a permissions error. You can try doing something like:
if (!is_writeable('images/' . $_FILES['image']['name'])) {
die("Cannot write to destination file");
}
However, be aware that you're using a user-provided filename, so if someone uploads "pwn_my_server.php", your script will write it out to the images directory, and then they can simply visit yoursite.com/images/pwn_my_server.php and take control of your site.
In general it is NEVER a good idea to trust anything in the $_FILES array, or use it directly, since the entirety of its contents are under remote user control. The only thing created by the server is the error code and tmp_name. The rest is potentially malicious.
maybe the problem is 'image/' folder, you can set the absolute path here and make sure that path is writable, then have a try.
Use the code below:
1. create the directory named 'uploads'
2. save the file with .php extension
now run the code.
<?php
if (!empty($_FILES))
{
// PATH TO THE DIRECTORY WHERE FILES UPLOADS
$file_src = 'uploads/'.$_FILES['image']['name'];
// FUNCTION TO UPLOAD THE FILE
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_src)):
// SHOW THE SUCCESS MESSAGE AFTER THE MOVE - NO VISIBLE CHANGE
echo 'Your file have been uploaded sucessfuly';
else:
// SHOW ERROR MESSAGE
echo 'Error';
endif;
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" />
</div>
<div>
<label for="image">Image</label>
<input type="file" name="image" />
</div>
<input type="submit" value="Send" name='submit' />
</form>
:)

Categories