PHP file upload - php

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?

Related

PHP File Upload to Database

<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')")

PHP image compression and uploading to mysql

I have a php script, which uploads pictures to a mysql database. The images are taken within the browser. I would like to compress them before uploading, but I'm not quite sure how exactly to compress the uploaded data. What I've got for the moment is this:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0)
{
//$positiony = $_POST['posy'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$content = imagejpeg($content,null,50);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (team_name, id, display, content) ".
"VALUES ('$team_name', 'null', '1', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
echo "<br>File $fileName uploaded<br>";
}
The image uploading works fine, but the uploaded images are broken. Introducing imagejpeg as a form of compressing has caused the issues. Should I be using it on something else?
Most images are already compressed so there is no need to "compress them further".
Storing them in a database is not a recommended thing to do. Just upload them to a location on the server and save the path to that location.

Restricting all but one file format to be uploaded

I'm studying on MySQL & PHP, and for my first production I've started to work on a review panel. You can simply upload your product reviews to the database and browse them later on, directly from the panel, which in this case is a local website.
The problem is, I can't figure out how to rule over every file format on upload, except .pdf! To be more clear: I only want my upload form to accept .pdf files to be uploaded. At the moment it doesn't restrict anything, here is my code:
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$revName = $_POST['revname'];
$revRating = $_POST['rating'];
$revRecommend = $_POST['recommend'];
$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);
}
rename($tmpName,"C:\\xampp\\htdocs\\ReviewArchieve\\files\\reviews\\".$fileName);
include 'include/config.php';
include 'include/opendb.php';
$query = "INSERT INTO files (revname, rating, recommend, name, size, type, content)".
"VALUES ('$revName', '$revRating', '$revRecommend', '$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
include 'include/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
?>
Got it working!
Thanks to the MIME refer, I managed to learn something new, and accomplished my task with a little bit of investigation! It was not the part of code offered in the correct answer, that did not work at all in my case, no matter what I did, but instead, I used this method:
I noticed I have already included the file type.
$fileType = $_FILES['userfile']['type'];
So now I just had to make an if from it, like this:
if($fileType == 'application/pdf') {
*** Code to be driven here, same as above on the original code ***
}
else {
echo "Invalid file, upload interrupted!";
}
Answer:
....
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
if (mime_content_type($tmpname) != 'application/pdf') {
die("uploaded file not valid");
}
....
You have a number of problems here the biggest are:
SQL Injection. You must sanitize your user inputs or little bobby tables will visit you. Think about using parametrized queries
You should check the file's mimetype.
http://www.php.net//manual/en/function.mime-content-type.php works out the box although is deprecated. You should use fileinfo.

Saving Uploaded File Path in MySQL with PHP

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);
?>

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories