<body>
<form action="#" enctype="multipart/form-data" method="post">
<input multiple="" name="img[]" type="file" />
<input name="submit" type="submit" />
</form>
<?php
mmysql_connect("localhost","root","");
mysql_select_db("multiple");
if(isset($_POST['submit'])){
$filename = $_FILES['img']['name']);
$tmpname = $_FILES['img']['tmp_name']
$filetype = $_FILES['img']['type'];
for($i=0; $i<=count($tmpname)-1; $i++){
$name =addslashes(filename[$i]);
$tmp = addslashes(file_get_contents($tmpname[$i]));
mysql_query("INSERT into img(name,image) values('$name','$tmp')");
echo "uploaded";
}
}
?>
</body>
</html>
I am trying to upload a simple image to my database So I can work on this user hosted site. So far nothing has worked. I'm dyin here. I've looked through so many tutorials.
From hitting an issue with file uploads before, it's much easier on the DB and your coding to upload your file to the server using 'move_uploaded_file()' and then provide a reference in your DB. In the above example, you are storing your file in a temporary folder ['tmp_name'], saving that file name, but then not transferring the file somewhere that won't delete it.
So for something generic to help:
$fileName $_FILES['img']['name'];
$fileType = $_FILES['img']['type'];
$fileLocation = $_FILES['img']['tmp_name'];
$newFileName = "newFileName.jpg";
$img = "folder/".$newFileName;
move_uploaded_file($fileLocation, "../folder/".$newFileName);
The reason for this is that when you save to the 'tmp' folder (which you must for a bit), the file is also renamed to a seemingly random set of characters. So you need to get that file location, move it to the folder of your choice, and also name it something findable. Then you can save the $img path in your DB and call it from anywhere (with some modification). It will take some playing with, but this should help.
To upload an image to the database directly from an uploaded file, you need to upload the base64 encoded version of the image. And also make sure that the field type of the image in your database is actually blog or LongBlog.
Here is the code to do that
$file = $_FILES['file'];
$filename = $file['name'];
$convert_to_base64 = base64_encode(file_get_contents($file['tmp_name']));
$base64_image = "data:image/jpeg;base64,".$convert_to_base64;
$query = mysqli_query($con, "INSERT INTO 'table'(image)VALUES('$base64_image')")
Related
I have a form:
<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>
I have php code:
$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';
This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.
I had to change the system of uploading the image by doing this:
$file_content = file_get_contents($file['tmp_name']);
$file_dump = file_put_contents($location, $file_content);
This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.
In your code by using
$ext = explode(",", $file['type'])[0];
you get the extension as image/your_image_type.
Then you are appending that with the file name, which will create an invalid image.
To get the extension, you can do as follows
$ext= explode("/", $file['type'])[1];
or
$ext = strtolower(end(explode('.',$_FILES['image']['name'])));
Hello i have one problem to ask. The problem is when i'm trying to upload an image to certain folder usin php, the image is not move.The image information is insert into database but only the image is not move to destination folder. The folder is empty but no error is show. My file_upload in Php.ini is on but still the image is not move.
Below is my code:
<form action='try1.php' method='post' enctype='multipart/form-data'>
<table border='1'><tr>
<td><input type='file' name='file_img' /></td><td>
<input type='submit' name='btn_upload' value='upload'></td></tr>
</table>
</form>
<?php
require 'conf.php';
$link = mysqli_connect($h,$u,$p,$db);
if(isset($_POST['btn_upload']))
{
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "upload/".$filename;
move_uploaded_file($filetmp,$filepath);
$query = "insert into try (image,type,path) values ('$filename','$filetype','$filepath')";
$result = mysqli_query($link,$query);
}
?>
I hope some one can help me to solve this problem,thank you.
(solved)I have solved the problem. its not the code but my pc that have problem.Thank you for helping.
At first delete your upload folder. After that
Please keep below code in your code.
$filepath = "upload/";
$filePathWithFileName = "upload/".$filename;
if (!file_exists($filepath)) {
mkdir($filepath, 0777);
}
move_uploaded_file($filetmp,$filePathWithFileName);
$filepath = "./upload/".$filename;
i'm currently making a website for my final year university project, which requires a photo upload function. Currently when a user uploads a photo, the photo is stored in a folder in the remote server. I need the images to go into a database and so I was wondering if anyone had any advice as to how to do this and where to place the code to send the uploaded content to the database within the following code, also I need for it to work where when each individual user uploads an image, they are all displayed for all to see, and not as it is currently, where only one image is displayed at a time and when the page is refreshed, the image disappears. Hope that all made sense, any help would be greatly appreciated. Thank you.
<?php include_once("home_start.php"); ?>
<h1>Upload your images here:</h1>
<div id="fileselect" style="border-bottom:thin #000000 solid; border- collapse:collapse">
<form id="frmSimple" action="home.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" id="filename" name="filename" size="10" /><br />
<input type="submit" id="submit" name="submit" value=" Upload " />
</form>
</div>
<div id="feedback">
<?php
// Determine whether a file was uploaded
if ($_FILES) {
// Put file properties into variables
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
// Determine whether file is png, jpg or other
switch($_FILES['filename']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
//default: ext = ''; break;
}
//validate against file type
// if $ext is empty string (therefore null or false) image is not a jpg or png
if($ext){
// validate against file size
if($size < 1000000){
// Create a safe name for the file and store in a safe location
$n = "$name"; // Could add .$ext to enforce file type
$n = ereg_replace("[^A-Za-z0-9.]","",$n); // Remove all except alphanumeric characters and
$n = strtolower($n); // Convert to lower case (platform independence)
$n = "uploaded_images/$n"; // Add folder to force safe location
move_uploaded_file($tmp_name, $n); // Move to the safe location and give it the safe
echo "<p>Uploaded image '$name' as '$n': </p>";
echo "<img src='$n' />";
}
else echo "<p>'$name' is too big - 50KB max (50000 bytes).</p>";
}
else echo "<p>'$name' is an invalid file - only jpg and png accepted.</p>";
}
else echo "<p>No image has been uploaded.</p>";
?>
</div>
<?php include_once("home_end.php"); ?>
I would highly recommend against it. Instead, stored the photos in a folder and reference their location from the database (i.e. a string pointing to their location on the filesystem).
However, if you're so inclined to store it in the database, you need to:
Get the file contents after upload
Ensure that the contents don't have any characters that would conflict with your SQL (easy solution is to encode it somehow; base64 perhaps?)
Perform your SQL insert
Again - this is a bad idea. Don't do it - save it to the filesystem.
Also, the following line:
move_uploaded_file($tmp_name, $n);
without any checks of file type, or file integrity, makes it trivial to upload a shell to your box.
Once after the file uploaded successfully get the uploaded image path.
$file_type='jpg'; //if you are using more than one type write a switch case
$file_size = filesize($file);
$fp = fopen($file,'r');
$content = fread($fp,$file_size);
$content = addslashes($content); //content is a binary data of the image
fclose($fp);
To save the image in database. Write a insert query with whatever fields you want $file_name, $file_type, $file_size and content. I am assuming you are able to connect to database successfully.
mysql_query("INSERT INTO Images (id,file_name,file_type,file_size,content)
VALUES ('bird', 'jpg',340kb,'binarydata')");
I am trying to upload a file, and save the path to MySQL.
I want to make a custom path for each file, which will be based on a variable, however the actual file name of the file will stay the same.
I am submitting the file via POST. I believe I have to use $_FILE? The name of the form item is "file".
How would I go about doing this? Note: I DO NOT want to store the actual file on the database, just the path.
EDIT: I also want to save the actual file to a path, too.
Take a look at this page: http://www.php.net/manual/en/features.file-upload.post-method.php There is an example of moving an uploaded file to some folder.
So yes the relevant information is stored in $_FILE
First create appvars.php like something below
<?php
// Define application constants
define('GW_UPLOADPATH', 'foldername/');
define('GW_MAXFILESIZE', 32768); // 32 KB
?>
then create the code to save the file like something like this
<?php
require_once('appvars.php');
$file = mysqli_real_escape_string($dbc, trim($_FILES['file']['name']));
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
//do some checks to make sure the person upload the file type you like
if ((($file_type == filetype) // check for the size also
&& ($file_size > 0) && ($file_size <= GW_MAXFILESIZE)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = GW_UPLOADPATH . $file;
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
// Write the data to the database
mysqli_connect( database info);
$query = "INSERT INTO table (file ) VALUES ($file)";
mysqli_query($dbc, $query);
}
}
}
mysqli_close($dbc);
?>
I am trying to upload files to my server using php to save them into a binary form into my mysql database but I cant get it to work, here is the script I’m using, I believe it has something to do with "$_FILES" because when I take this out "&& $_FILES['userfile']['size'] > 0" the script starts to run but then the variables underneath that use "$_FILES" aren’t defined.
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
db_connect();
db_select();
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
db_disconnect();
echo "<br>File $fileName uploaded<br>";
}
This is a 2 fold process, first the upload itself and then the manipulation on the server. The first validation would be to make sure the file was even uploaded. For that you can use after the line
$fileName = $_FILES['userfile']['name'];
Use:
if(is_uploaded_file($fileName)) {
// Here goes all the file manipulation/storage/etc
} else {
echo 'Error: File could not be uploaded.';
}
Try to use that and maybe re-post if the file was actually uploaded. Just because $_FILES has content it does not necessarily mean that the file was uploaded to the server.
You should better use the file upload status to check whether the upload was successful.
And don’t use the addslashes function for MySQL queries. Use the mysql_real_escape_string instead.
If you upload the files with a form, does it have a 'enctype="multipart/form-data"' in the "form" tag?
I assume your field that's being posted is named "userfile"?
Also, this is not directly germane to your question, but it's generally considered a better practice to store files in the filesystem rather than in MySQL. Filesystems are designed to store large blocks of binary data, while databases are not.
I assume from your example that your input name is upload. <input type="file" /> results in PHP are not sorted in $_POST but in $_FILES. The documentation uses $_FILES['userfile'] as their example field, but if your input is declared as <input type="file" name="upload" />, you should simply use $_FILES['upload'].
try make print_r( $FILES ) and define what is the problem.
Maybe form have not needed type?