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.
Related
Main issue is image file is not moving from temp location to new location. But it is not giving any error. And all mysql queries are working. Al the html part also working.
$newFileName = $_POST['filename'];
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['temp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode(".",$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg","jpeg","png");
if(in_array($fileActualExt,$allowed)){
if($fileError === 0){
if($fileSize < 20000000){
$imageFullName = $newFileName . "." . uniqid("",true) . "." . $fileActualExt;
$fileDestination = "../gallery/" . $imageFullName;
include_once 'dbh.inc.php';
if(!empty($imageTitle) || !empty($imageDesc)){
$sqlSelect = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$sqlSelect)){
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount+1;
$sqlInsert = "INSERT INTO gallery(title,description,imgfullname,ordergallery) VALUES(?,?,?,?);";
if(mysqli_stmt_prepare($stmt,$sqlInsert)){
mysqli_stmt_bind_param($stmt,"ssss", $imageTitle,$imageDesc,$imageFullName,$setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
}
}
}
}
}
}
Your $imageTitle and $imageDesc variables are empty in this code since they are never given a value. Therefore it will not enter the if statement and move the files.
You've probably been downvoted here because your description of what the code actually does is somewhat vague. You also do not appear to have tested or published a MCVE. Why, for instance, do you SELECT * FROM gallery; when all you use the data for is to display a count (which is irrelevant to the problem you describe).
You're handling of the filename is sensibly done, although ideally the path should be outwith the document root (and subsequent read access mediated by a script).
That "all mysql queries are working" suggests that the execution thread is reaching move_uploaded_file(), we shouldn't be guessing how the code works / what diagnostics you may have run. Each of those "if" statements should have an "else". Each of the mysqli_*() calls should check the return value. You should be checking the return value of move_uploaded_file(). You should also be checking your log file for errors and warnings (after verifying that the logging mechanism is working as expected).
From a cursory glance through the code (I imagine that the relevant POST vars are populated) the next place I would be looking (after the return values and logs) is at the permissions on the target directory.
Hello have successfully built a web application that allows users upload videos, but i am trying to compress videos before uploading them so as to save bandwidth. Please how do I go about these? e.g, In pictures compression it is GD library but in video searched post on Youtube and stack overflow, none answers my question these is my code. NOTE:these code works perfectly but I am trying to compress the video before upload in php. Thanks in advance..
I looked at this post Server-side video conversion and compression not really what i am looking for because i have never really worked with ffmpeg
<?php include "connect.php"; ?>
<?php
if ((isset($_POST['videoname'])) && (isset($_POST['aboutvideo'])) && (isset($_POST['timestart'])) && (isset($_POST['timestop'])) && (isset($_POST['streamersid']))){
$videoname=$_POST['videoname'];
$aboutvideo=$_POST['aboutvideo'];
$timestart=$_POST['timestart'];
$timestop=$_POST['timestop'];
$streamersid=$_POST['streamersid'];
$streamerstype=$_POST['streamerstype'];
$streamersname=$_POST['streamersname'];
$date=$_POST['date'];
$fileName = $_FILES["file1"]["name"]; //file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; //file in the php tmp folder
$fileType = $_FILES["file1"]["type"]; //the type of file it is
$fileSize = $_FILES["file1"]["size"]; //File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; //0 for false and 1 for true
$tex = pathinfo($fileName, PATHINFO_EXTENSION); //get video extension
if($tex=='mp4' || $tex=='avi' ||
$tex=='webm' || $tex=='flv' ||
$tex=='MP4' || $tex=='3gp')
{
$rand = substr(md5(microtime()),rand(0, 26) , 26);
#$filez = $rand.$_FILES['file1']['name'];
$videoname= mysqli_real_escape_string($con, $videoname);
$aboutvideo= mysqli_real_escape_string($con, $aboutvideo);
$timestart = mysqli_real_escape_string($con, $timestart);
$timestop = mysqli_real_escape_string($con, $timestop);
//compression script from here video would be compressed before path being being saved to database and moved to folder
if(move_uploaded_file($fileTmpLoc, "plays/$filez")){
$insert="INSERT INTO `plays`(`streamers_id`, `file1`, `video_name`, `about_video`, `streamers_type`, `time_start`, `time_stop`, `date`, `streamers_name`) VALUES ('$streamersid','$filez','$videoname','$aboutvideo','$streamerstype','$timestart','$timestop','$date','$streamersname')";
$run=mysqli_query($con, $insert);
echo "Upload complete ";
} else {
echo "Upload Failed";
}
} else {
echo "Invalid video";
}
}
?>
You are looking to compress BEFORE upload, then it must be done using code running on the client. Your PHP runs on the server. Therefore, you must write some sort of app that the user can download that can compress and upload.
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.
I'm hoping this is an easy one, I'm using mySQL and php to upload an image as a BLOB type using this code:
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);
}
This is all working fine, inserting to the database and everything. I then want to use SimpleImage: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ to perform some resize and compression work on the image before uploading it. I can't see how to combine say:
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($_FILES['userfile']['tmp_name']);
$image->resizeToWidth(150);
$image->output();
With my existing code, I think what I want to do is get $content to become $image, but I've tried for a while and can't find a way of doing it. Any help much appreciated.
Happy Christmases to those who like Christmas and TIA to all.
You are outputting the resized image to the browser (::output()) but you're not saving it. If you want to store it inside the database, you need to change the temporary file first, e.g. by using the ::save() function of SimpleImage.
Next to that, you write you want to resize the picture in the browser before uploading. That can not be done with PHP, but only with javascript and browsers who support that. Additionally the upload handling on the PHP side might differ then. But I'm not really sure if you really meant it that the image is resized before uploading.
Another Idea I had is using an output buffer:
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'];
$image = new SimpleImage();
$image->load($_FILES['userfile']['tmp_name']);
$image->resizeToWidth(150);
ob_start();
$image->output();
$content = ob_get_clean();
$content = addslashes($content);
...
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?