I have this problem i've created a code for uploading text and image into a database and a folder. Few days back I was wondering how to create a unique id and to be inserted. I've figured it out a way but then the code doesn't upload the image into the database only into the folder.
<?php
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$query = "
INSERT INTO image_area2
('id',`name`,`path`,`unique_id`)
VALUES
('','$file_name','uploads/$file_name','$_POST[un_id]');
";
The code seems to be fine for the image to be insert into the database but it doesn't work and I can't figure it out. Thank you for the help in advance.
My answears so far so you could see it better:
Well the problem is i don't have any error which is the strangest thing. It works perfectly it inserts the text into the db and the image into the folder but it doesn't insert the path and name into the db. And the code for the insertion is ok i think and i can't figure it why it doesn't do it. I've used print_r($query) function to see if the code is receiving the information from the form and it is receiving it.
Well i've added the mysql_query($query); row and nothing again it has added the text into the db and the image into the folder but nothig about the image into the db. $_FILES['files']['tmp_name'] i use it to define and get the name,tmp name size and type and i've put them into the array $file_name,$file_size,$file_type and $file_tmp
Well i've cleared the id it posted one time but the strange thing is that i've added 1 image and in the db there where 2 lines for the same image and then if i want to add new text and new image again it doesn't work 1 or more images are added into the folder only.
RESOLVED:
The problem was resolved with 2 steps the one that i was written 'id' like that and it wasn't needed anyway and the second the WAMP server was having problems and it was removed and changed. Thank you for all your help :)
If your code is copy/pasted from the actual file, your SQL is using the incorect quote marks in the field list. It should be:
$query = "
INSERT INTO image_area2
(`id`,`name`,`path`,`unique_id`)
VALUES
('','$file_name','uploads/$file_name','$_POST[un_id]');
";
(Notice the back-ticks around id rather than the normal single quote-marks
If id is an auto-incremented primary key then change the SQL to:
$query = "
INSERT INTO image_area2
(`name`,`path`,`unique_id`)
VALUES
('$file_name','uploads/$file_name','$_POST[un_id]');
";
Also, a few pointers:
Sanitize your variables. $_POST['un_id'] is wide open to SQL
injection
Move away from the mysql_ functions - they're
deprecated. Move to mysqli_ or PDO equivalents. This will also
make prepared functions available and remove the need to sanitize
your data (if used properly)
Related
While I'm sending file ( type="file") to database (PHPmyAdmin), instead of saving with file name it saves as BLOB as shown in the following figure.
I found the the similar question Saving Files as blob in database ajax php pdo
here but didn't help me. My php code is as follows for sending file to the database.
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $get.".".$ext; //$newname='newfilename.'.$ext
$target ="folder/".$newname;
$doc= move_uploaded_file( $_FILES['file']['tmp_name'], $target);
$sql="INSERT INTO apply(mobile,doc,position)
VALUES (' $mobile','$newname',' $position')";
$query=mysqli_query($conn, $sql);
The file is sending to target folder (named folder) with the correct required name but Why I'm not getting the same name in the database. What's going wrong in my code?
Thanks in advance.
First of all, you should not tore files into the database directly because of critical performance issues.
Suggested way is to store files in file system, and store their path in database as TEXT or Varchar.
Now coming to your question:
While I'm sending file ( type="file") to database (PHPmyAdmin), instead of saving with file name it saves as BLOB as shown in the following figure.
Every file is composed of binaries but in different order and format. Storing it in database is not actually tricky. Database converts them into array of bytes/ stream of bytes and then stores these byte format data into the table.
When a fetch query is fired, it returns the exact byte stream in response. And at application level, these bytes are treated as files by their respective encoding techniques.
It's worth reading this post and subsequent link in the accepted answer.
I wonder how I do to save the name of an image in mysql with plupload?
In file upload.php have many variables and I do not know which one stores the filename, already tried everything and could not
I would like to save the image name that plupload creates, not the original name
can someone help me?
thank you
Get the file name like this.
$filename = $_FILES["file"]["name"];
and pass $filename into insert statement.
Try this plugin for plupload to upload file from github
You can directly used a $fileName variable
here give you a example, like
$sSQL = "INSERT INTO eletz_multiimage (image_name) VALUES ('$fileName')";
$result = mysql_query($sSQL);
I'm making a web-based system using html and php, one of the functions is to allow students to upload files to the database, 3 files actually.
I made an input field of type file and I'm sure my PHP is correct but sometimes a warning I don't understand appears and the query doesn't work. but this does not always happen.. usually not..
Here's one of the fields in the HTML:
<tr><td> <p><span>C.V: </span> </td><td> <input class="contact" type="file" id ="CV" name="CV" value="" required /></p> </td></tr>
and here's the PHP
//check for CV
if ($_FILES["CV"]["size"] > 0)
{
$fileName = $_FILES['CV']['name'];
$tmpName = $_FILES['CV']['tmp_name'];
$fileSize = $_FILES['CV']['size'];
$fileType = $_FILES['CV']['type'];
//check if larger than 1M
if($fileSize > 1048576) {echo "<p style='color: red;'> Cannot upload <b>CV</b> due to large size. File must be less than 1MB </br> </p>"; $complete= false;}
//check if .PDF ( I need it to be PDF always)
else if($fileType != "application/pdf")
{
echo "<p style='color: red;'> Cannot upload <b>CV</b> file type must be a .PDF only </br> </p>"; $complete= false;}
//everything is fine:
else{
$fp = fopen($tmpName, 'r');
$CV = fread($fp, filesize($tmpName));
$CV = addslashes($CV);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
echo "<br>CV: File $fileName uploaded with type $fileType and size $fileSize <br>";
}
}
SQL Query:
$qry=" UPDATE student SET CV = '$CV', Transcript='$tran',IELTScertificate='$EC', Status ='$stat' WHERE KSUID ='$KSUID'";
Warnings:
Warning:mysql_query(): MySQL server has gone away...line 330
Warning:mysql_query(): Error reading result set's header...line 330
330. $result=mysql_query($qry);
In the database I didn't use a table for uploaded files, I only need content but I don't care about the type because it'll always be a pdf, and I don't care about the name as long as it's stored in the right column.
I'm not sure if this is the problem? but I don't think so cause some files were successfully uploaded where other files with different size didn't.
Another issue I'm facing with retrieving the files..
when I download the file I get it correctly as a .pdf file but when I open it it says the file got damaged.. I'm not sure why? maybe because I'm using local server? though I don't think so but I'm tired trying to figure out :( if anybody faced such a problem before or if you know how to fix this problem please help me
HTML :
<a href='updatestudentlist.php?id=".$ksuid."&file=00'>CV</a> <br/>
PHP:
if(isset($_GET['file'])){
$file=intval($_GET['file']);
if($file==00) //I use this cause other files got different numbers
{
$query = "SELECT CV FROM student WHERE KSUID='".$_GET['id']."'";
$result = mysql_query($query) or die('Error, query failed');
list($content) = mysql_fetch_array($result);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=".$_GET['id']."_CV");
echo $content;
exit;
}
}
There are multiple issues at play here, mostly centered around how you're working with the database.
1) You shouldn't be using mysql_query() to interface with your database, because that module has been depreciated in favor of better, more current libraries (such as MySQLi). In particular, one major feature the MySQL extension lacks that MySQLi has is prepared statements, which is indirectly why you're getting the warning about the server going away.
Aside from opening yourself to injection attacks with your current code, it also produces an extremely large SQL query (because you're including the PDF itself inside the query string to update the student profile). If an individual query is taking too long to execute, the connection to the server will be dropped (which issues that particular warning). Thus, you should be getting the error from uploading larger PDFs, whereas smaller PDFs upload just fine.
If instead you use prepared statements, as available in the MySQLi extension, the server will be able to handle the extremely short query and then wait on the parameters to be passed as well, of which the extremely large PDF file-string will be one.
2) Your file is considered "damaged" because you're using addslashes() on it before inserting it into the database, but not using stripslashes() when you pull it out. Thus, the PDF you're serving up has most of the data right, but it has a bunch of extra slashes in it, which throws off the PDF reader.
The first part of question is mostly related to connectivity issues with the MySQL Server. There are a host of reasons that could happen. Check this link Server has gone away for the different reasons
I have a postgres database with stored images 'bytea' type and I try to display them into a browser with PHP. I found the way to display one of them but I can't make it for more than one. The code I use is the following:
File Name - display_image.php
$conn = pg_connect("dbname=test user=postgres password=postgres");
$temp = '/home/postgres/tmp.jpg';
$query = "select lo_export(image, '$temp') from map ";
$result = pg_query($query);
if($result)
{
while ($line = pg_fetch_array($result))
{
$ctobj = $line["image"];
echo "<IMG SRC=show.php> </br>";
}
}
else { echo "File does not exists."; }
pg_close($conn);
File Name - show.php
header("Content-type: image/jpeg");
$jpeg = fopen("/home/postgres/tmp.jpg","r");
$image = fread($jpeg,filesize("/home/postgres/tmp.jpg"));
echo $image;
The problem seems to be the "tmp.jpg" virtual file which displays only one image. If the result of the query is 7 images then it displays 7 times the same image within a while loop. How can I solve this?
Thanks for the interest!
I did this some time ago for bytea.
You need to run your bytea data through pg_unescape_bytea. See http://php.net/manual/en/function.pg-unescape-bytea.php
Basically your SQL query returns the bytea field in an escaped format.
However this is not what you are doing. And so the above is just for the next poor sap who comes here looking for bytea help. Please amend to note you are using LOB's not BYTEA's.
Also note that your code there is not concurrency safe. If two users request different images, my guess is that you will get both users getting different images. For this reason you should add the oid to the retrieval url, and name your file /tmp/$oid.jpg where $oid is the oid of the large object. You will need to retrieve that info (I believe it looks like it is stored in the image field of map?). On the other hand that assumes that all files are essentially public. if that's not the case, you want to move everything into the show_image.php and clean up when you are done.
I am attempting to store files in a MySql database based upon this article. Before you suggest I store files on the file system and not in the database the files uploaded will be stored and relate to records in the database. I could keep a path to the files and just the file names but I want users to be able to modify and delete the files directly through the web interface. So, let's just pretend that storing in the database is a good option and not discuss others.
My issue is when I go to download the file the data returned from the BLOB in the MySql database is not exactly what I uploaded in test. If I use the function of addslashes then binary wise it is completely off. If I remove that function from the routine then I get much closer.
Using a Binary Diff application I can see that, while not using addslashes the file data returned has one additional byte of data at the beginning of the file and in turn one less byte at the end. The remainder of the file's data is offset by one due to this little feature of the download.
I am using a FORM to submit the data and enctype is set to multipart/form-data as it should be. Here's some code I'm using to get it all to work. DAL in the code references a class I created for my Data Access Layer. It handles all saving and retrieving routines and doesn't seem to be injecting any new data. I've checked by looking at the file's content before it goes to my DAL class for saving and the extra byte is already there.
upload
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fp = fopen($_FILES['userfile']['tmp_name'], 'r');
$_FILES['userfile']['content'] = fread($fp, $_FILES['userfile']['size']);
$_FILES['userfile']['content'] = addslashes($_FILES['userfile']['content']);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$_FILES['userfile']['name'] = addslashes($_FILES['userfile']['name']);
}
$fileDAL = new DAL("files");
$newID = $fileDAL->SaveItem($_FILES['userfile'], false);
echo "<br>File ".$_FILES['userfile']['name']." uploaded as ID $newID<br>";
}
download
if(isset($_GET['id']))
{
$id = $_GET['id'];
$objFiles = new DAL('files');
$objFile = $objFiles->GetItem($id);
header("Content-length: $objFile->size");
header("Content-type: $objFile->type");
header("Content-Disposition: attachment; filename=$objFile->name");
echo $objFile->content;
exit;
}
use mysql_real_escape_string().
excerpt from its man page:
Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.
so I would change the escaping part of your code to:
if( get_magic_quotes_gpc() )
{
$_FILES['userfile']['name'] = stripslashes( $_FILES['userfile']['name'] );
}
$_FILES['userfile']['name'] = mysql_real_escape_string( $_FILES['userfile']['name'] );
Turns out that I add an extra line feed or carriage return at the end of a PHP file that was in my headers prior to this code being executed. It caused the header upon writing to include the line feed (OA) in the binary data for file saving.