Restricting uploads to PDFs and MS Word files - php

I'm making a file uploader using PHP and want to restrict it to PDFs and Microsoft Word files. However, it's currently allowing uploads from all file types to the database. How can I restrict it to only allowing PDFs and Microsoft Word files?
Here is my code:
<?php
# Check if a file has been uploaded
if (isset($_FILES['uploaded_file']))
# Make sure the file was sent without errors
if ($_FILES['uploaded_file']['error'] == 0) {
# Connect to the database
$dbLink = mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("webproject", $dbLink) or die(mysql_error());
/* if(mysql_connect()) {
die("MySQL connection failed: ". mysql_error());
} */
# Gather all required data
$filename = mysql_real_escape_string($_FILES['uploaded_file']['name']);
$filemime = mysql_real_escape_string($_FILES['uploaded_file']['type'] == "application/pdf" || $_FILES["uploaded_file"]["type"] == "application/msword");
$size = $_FILES['uploaded_file']['size'];
$data = mysql_real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$subjects = $_POST['subjects'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
# Create the SQL query
$query = "
INSERT INTO file(
Filename, Filemime, Filesize, Filedata, subjects, name, email, phone, Created
)
VALUES (
'{$filename}', '{$filemime}', {$size}, '{$data}', '{$subjects}','{$name}','{$email}','{$phone}', NOW()
)";
# Execute the query
$result = mysql_query($query, $dbLink);
# Check if it was successfull
if ($result) {
echo "Success! Your file was successfully added!";
} else {
echo "Error! Failed to insert the file";
echo "<pre>" . mysql_error($dbLink) . "</pre>";
}
} else {
echo "Error!
An error accured while the file was being uploaded.
Error code: " . $_FILES['uploaded_file']['error'];
}
# Close the mysql connection
mysql_close($dbLink);
# Echo a link back to the mail page
echo "<p><a href='index.html'>Click here to go back home page!.</a></p>";
?>

I am not sure how your code actually works, but if you replace your second if at the top by this, the program will run only if the type is pdf or word, other files will cause this error: "Error! An error accured while the file was being uploaded. Error code: ". $_FILES['uploaded_file']['error'];" to occur
if($_FILES['uploaded_file']['error'] == 0 && ($_FILES['uploaded_file']['type']=='application/pdf' || $_FILES['uploaded_file']['type']=='application/msword' || $_FILES["uploaded_file"]["type"] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))
Your first if: if (isset($_FILES['uploaded_file'])) has no braces... that's not a very good practice.

Here is a extract from a function I sometimes use:
function CheckFile ($file){
$mimeTypes = array(
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/excel",
"application/vnd.ms-excel",
"application/x-excel",
"application/x-msexcel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$fileExtensions = array("pdf", "doc", "docx", "xls", "xlsx");
if (in_array($file['type'], $mimeTypes) &&
in_array(end(explode(".", $file["name"])), $fileExtensions)) {
return true;
}
}
Call it with CheckFile($_FILES['uploaded_file']) It will return true if the doc is a pdf word or excel file
Edit:
One way to use it would be like so:
if (!CheckFile($_FILES['uploaded_file'])){
?>
<p>Sorry, your file was not of the correct type</p>
<?php
exit();
}

Related

Can't insert file's path into database.(I'm New to HTML and PHP)

I'm trying to upload the file's path into my database. But nothing is being inserted. My file gets uploaded to target directory successfully. I want to insert the path too, but can't do it. I believe I'm doing some mistake in the Insert Into statement. Please let me know what's wrong?
My upload.php code is below:
<?php
// variables
$conn = mysqli_connect('localhost','root','abcdef','trademark');
if(!$conn) {
echo "Not Connected To Server";
}
else {
define('UPLOAD_DIR', 'uploads/');
$fileName = $_FILES['file'];
// check for which action should be taken if file already exist
//Rename file name
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo"FILE SUCCESSFULLY UPLOADED!! " . "<br/><br/><br/>"; //after renaming
}
// If no such file already exists, then upload it as it is
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo " FILE SUCCESSFULLY UPLOADED!! ". "<br/><br/>";
}
// function to rename file
function update_file_name($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = trim($arr[(count($arr) - 1)],$ext);
$exist = FALSE;
$i = 2;
while(!$exist)
{
$file = $dr.$fName.'_'.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
} // function to rename ends
$sql = "INSERT INTO file (Path) VALUES (' " . mysqli_real_escape_string( UPLOAD_DIR.$fileName['name']) . " ')";
$r = mysqli_query($conn,$sql);
echo 'file info inserted';
}
?>
Check syntax for function mysqli_real_escape_string
getting warning message as,
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in

How to call functions from another php file?

In short: I am uploading to /var/tmp multiple excel files, then convert them into .csv(2 different converters for .xls and .xlsx). The resulting file, result.csv should be inserted into database. It all worked until we decided to allow to upload multiple files simultaneously(adding multiple attribute to html input tag). Problem: data not inserted into table
<?php
// database connection goes here;
include 'convertt2a.php';
if (isset($_POST["submit"])) {
$updir = "/var/tmp/result.xlsx";
$n= count($_FILES['rawexcel']['name']);
for ($i=0; $i<$n; $i++) {
$upfile = $updir.basename($_FILES['rawexcel']['name'][$i]);
$ext = pathinfo ($_FILES['rawexcel']['name'][$i], PATHINFO_EXTENSION);
if(is_uploaded_file ($_FILES ["rawexcel"]["tmp_name"][$i]))
{
move_uploaded_file ($_FILES["rawexcel"]["tmp_name"][$i], $updir);
if ($ext == 'xlsx' ) { exec("/usr/local/bin/cnvt /var/tmp/result.xlsx /var/tmp/result.csv "); } else
if ($ext == 'xls' ) { exec("/usr/local/bin/xls2csv -x /var/tmp/result.xls* -b WINDOWS-1251 -c /var/tmp/result.csv -a UTF-8"); }
echo "File successfully uploaded and converted to .csv ";
}
else {
echo "error uploading file ".$upfile;}
if (isset($_POST['provider'])) {
//select action to perform on case of different providers
if ($_POST['provider']=='tele2altel'){echo t2a("tele2");}
}
echo "cycle ".$i."ended here; </br>";
}}
else {echo "not isset post method";}
?>
t2a function:
function t2a ($string){
//opening .csv file, inserting into table in SAMPLEBANK TELE2ALTEL
$row =0;
if (($handle = fopen("/var/tmp/result.csv", "r"))!==FALSE){
while (($data = fgetcsv($handle, 1000, ","))!==FALSE) {
$row ++;
//we got data in $data[$i] array
if ($row==4) {$idb=$data[2];}
if ($row >6) {
$da=$data[0]; $imei = $data[1]; $ab=$data[2];$ty = NULL;
$du=$data[6]; $op = $data[3];$dir =$data[5];
$num= strlen($dir);
if ($num>=28) {$ty= $dir; $dir=NULL;}
if ($ab!==''){
$sql= "INSERT INTO tele2altel(Abonent,Opponent, Type, Data, Duration, idBase, IMEI,direction)
values ('$ab','$op','$ty','$da','$du', '$idb','$imei','$dir')";
$res = mysqli_query($conn, $sql);}
}}
fclose($handle);
} else {echo "unable to read file";}
$s = "Successfully inserted into DB";
return $s;
}
My output:
File successfully uploaded and converted to .csv
cycle i ended here;
Successfully inserted into DB, i times(number of files to be uploaded)
I have checked seapartely .csv files, they are being converted correctly. Thus, the error is in t2a function. I will appreciate any help.
Include the another file in it.
<?php include('yourfilename'); ?>
I think the line below is opening the wrong file...
fopen("/var/tmp/result.xlsx", "r")
Should be
fopen("/var/tmp/result.csv", "r")
The thing that was needed for this code to work was clarification of type of return for function:
function t2a ($string):string {}
solved the problem.

Audio files to be stored into database

Prior to this link:What is the best way to store media files on a database?
The answer stated:
(
Every system I know of that stores large numbers of big files stores them externally to the database. You store all of the queryable data for the file (title, artist, length, etc) in the database, along with a partial path to the file. When it's time to retrieve the file, you extract the file's path, prepend some file root (or URL) to it, and return that.
)
My questions are:
a)How do you store the partial path of the file?
b)How do you extract the file's path?
c)How do you prepend some file root and return it?
(Sorry I am very new and this bit I don't quite get. Any input or examples would be lovely.)
Btw, these are my codes for uploading the file, I just don't know the retrieve bit.
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'spellingbee');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$location = $dbLink->real_escape_string($_FILES['uploaded_file']['location']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `location`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$location}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
As far as I understand your problem you want to upload a audio file and save its name to database and then You want to retrieve it.
To do so just after your all validations (I am writing this code as if want to create a directory)
if(is_dir("audio")
{}
else
{mkdir("audio");}
$path = "http://www.domain.com/audio/".$_FILES['file']['name']; //prepend any path
// insert in database
move_uploaded_file($_FILES['file']['tmp_name'],$path);
And to retrive it:
just fetch the value of path from database.
Fetch From DB:
$q = mysql_query("select * from tablename");
while($r = mysql_fetch_array($q))
{
$path = $r['columnNameofPathinDatabase'];
echo $path;
}

Page taking too long to load [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I find it very difficult to comprehend why one of my pages is taking long before displaying its content. The code on the page is as follows.
Please, advise what could be wrong and if the code is secure. If not how to fix it.
<?php
//open database
include("includes/db_connect.php");
//require("includes/mysql_conn.php");
// Check to see if the type of file uploaded is a valid image type .........................
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
// These are the same for all file upload boxes
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
// This is an array that holds all valid image extensions
// These are the same for all file upload boxes
$valid_exts = array('jpg', 'jpeg', 'bmp', 'gif');
// This check is optional
if(!in_array($file['type'], $valid_types))
return 0;
// Get the extension from the uploaded filename
$upload_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
// This check is essential for security
if(!in_array($upload_ext, $valid_exts))
return 0;
return 1;
}
//...................................................................................................
// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";
// Get our POSTed variables
$ctitle = $_POST['ctitle'];
$csubject = $_POST['csubject'];
$creference = $_POST['creference'];
$cyear = $_POST['cyear'];
$cobjecttype = $_POST['cobjecttype'];
$cmaterial = $_POST['cmaterial'];
$ctechnic = $_POST['ctechnic'];
$cwidth = $_POST['cwidth'];
$cheight = $_POST['cheight'];
$cperiod = $_POST['cperiod'];
$cmarkings = $_POST['cmarkings'];
$cdescription = $_POST['cdescription'];
$csource = $_POST['csource'];
$cartist = $_POST['cartist'];
$image = $_FILES['image'];
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$target_path_1 = $TARGET_PATH . $image['name'];
// Sanitize our inputs
$ctitle = mysql_real_escape_string($ctitle);
$csubject= mysql_real_escape_string($csubject);
$creference = mysql_real_escape_string($creference);
$cyear = mysql_real_escape_string($cyear);
$cobjecttype = mysql_real_escape_string($cobjecttype);
$cmaterial = mysql_real_escape_string($cmaterial);
$ctechnic = mysql_real_escape_string($ctechnic);
$cwidth = mysql_real_escape_string($cwidth);
$cheight = mysql_real_escape_string($cheight);
$cperiod = mysql_real_escape_string($cperiod);
$cmarkings = mysql_real_escape_string($cmarkings);
$cdescription = mysql_real_escape_string($cdescription);
$csource = mysql_real_escape_string($csource);
$cartist = mysql_real_escape_string($cartist);
$image['name'] = mysql_real_escape_string($image['name']);
// Make sure all the fields from the form have inputs
if ( $ctitle == "" || $csubject == "" || $creference == "" || $cyear == "" || $cobjecttype == "" || $cmaterial == "" || $ctechnic == "" || $cwidth == "" || $cheight == "" || $cperiod == "" || $cmarkings == "" || $cdescription == "" || $csource == "" || $cartist == "" || $image['name'] == "")
{
echo "All fields are required";
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
echo "You must upload a jpeg, gif, or bmp";
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($target_path_1))
{
echo "A file with that name already exists";
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (
move_uploaded_file($image['tmp_name'], $target_path_1)
)
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into collections (ctitle, csubject, creference, cyear, cobjecttype, cmaterial, ctechnic, cwidth, cheight, cperiod, cmarkings, cdescription, csource, cartist, cfilename) values ('$ctitle', '$csubject', '$creference', '$cyear', '$cobjecttype', '$cmaterial', '$ctechnic', '$cwidth', '$cheight', '$cperiod', '$cmarkings', '$cdescription', '$csource', '$cartist', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DataBase: " . mysql_error());
exit;
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
echo "Could not upload file. Check read/write persmissions on the directory";
exit;
}
?>
And my database connection code:
<?php
//set connection variables
$host = "localhost";
$username = "joseph";
$password = "";
$db_name = "collectionsdb"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
?>
Thanx.
Joseph
Seems fine to me.
There are three stages.
Time to upload the data(depends on filesize and connection speed)
connect to the database(depends on the load on your database server)
and the moving of the file on the server(depends on the load of your server) ...
If you are on a local test system there could be the virus scan interfering as well. First filtering the post data then scanning the file and scanning the file again when moved(yes, they can be pretty paranoid...).
Advice: Put some "print_r(microtime());" in there and take a look.
The code is not necessarily secure. Sql injection is on thing that I is easily spotted. Do not pass the variables into the query string like that. Although you are using mysql_real_escape_string() there are scenarios where this is not adequate.
Please use parametrized queries. Also you should worry about html markup inserted into your db that could be used for XSS.
Another point to keep in mind is the permissions for you upload folder. Make sure you don't have everyone read and write.
Hope it helps.
See my comment for additional info about the root cause of your slow loads.

Filesize Error Message

I wonder whether someone could please help me.
I'm trying to incorporate an 'filesize' error message into a script, shown below, which is used to upload BLOB files to a mySQL server.
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = 'No title provided';// use (empty title) string
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["fileupload"]["size"]/1024000 >= 10)
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed Size.<br />";
}
if (isset($_FILES['photo']))
{
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title: ',
data='$data'");
$msg = 'Success: Image Uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['del'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'Image deleted';
}
if (isset($_POST['view'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'Image deleted';
}
}
}
?>
Through some guidance I received on this site I've been able to come up with the way to check the filesize, which starts at this line:
if($_FILES["fileupload"]["size"]/1024000 >= 10)
but I cannot get the error message to work.
The specific message needs to be activated if the file size is over 1MB. When I try to upload a file greater than this, the file is correctly rejected, but I receive the incorrect error message, 'Error: unknown file format'.
I've tried all number of ways to try to get this to work, but I just get the same incorrect error message.
I would be so grateful if someone could take a look at this and let me know where I'm going wrong.
Many thanks
SOLUTION
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
if ($imtype == 3)
$ext="png"; //
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["photo"]["size"]/102400 >= 1) {
$msg = "he file you wish to upload is:<strong>[ ". $_FILES["photo"]["size"]/1024000 . " MB]</strong> is more than allowed Size.";
}
I'm new to php but i searched for that and found this in manual
http://php.net/manual/en/function.set-error-handler.php
I posted as an answer because i cant comment. i hope it helps.
Looks like all of your other error messages go into a variable called $msg. I updated your calculation to be a bit easier:
if($_FILES["fileupload"]["size"]/102400 >= 1)
{
$msg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed Size.<br />";
}

Categories