/    Sign up×
Community /Pin to ProfileBookmark

Only allow certain files to be uploaded

Hey guys, I am trying to allow only .doc, .docs and .pdf files to be uploaded to my database. Currently the PHP script allows upload of any file type. I would like to restrict it to only allow uploading of genuine PDF DOC and DOCX files. I have found a possible solution but I am not sure where to put it because I am very new to this. If you could help fix this I would be grateful! (I have 2 files here) Also, when I try to run the files the browser only reads the title?

index.php

[code]

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″/>
<title>Upload PDF & Word files to Database</title>
</head>
<body>
<?php
$dbh = new PDO(“mysql:host=localhost;dbname=mydata”,”root”,””);
if(isset($_POST[‘btn’])){
$name = $_FILES[‘myfile’][‘name’];
$mime = $_FILES[‘myfile’][‘type’];
$data = file_get_contents($_FILES[‘myfile’][‘tmp_name’]);
$stmt = $dbh->prepare(“insert into myblob values(”,?,?,?)”);
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$mime);
$stmt->bindParam(3,$data, PDO::PARAM_LOB);
$stmt->execute();
}
?>
<form method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”myfile”/>
<button name=”btn”>Upload</button>
</form>
<p></p>
<ol>
<?php
$stat = $dbh->prepare(“select * from myblob”);
$stat->execute();
while($row = $stat->fetch()){
echo “<li><a href=’view.php?id=”.$row[‘id’].”‘ target=’_blank’>”.$row[‘name’].”</a></li>”;
}
?>
</ol>
</body>
</html>

[/code]

view.php

[code]

<?php
$dbh = new PDO(“mysql:host=localhost;dbname=mydata”,”root”,””);
$id = isset($_GET[‘id’])? $_GET[‘id’] : “”;
$stat = $dbh->prepare(“select * from myblob where id=?”);
$stat->bindParam(1,$id);
$stat->execute();
$row = $stat->fetch();
header(“Content-Type:”.$row[‘mime’]);
echo $row[‘data’];
echo ‘<img src=”data:image/jpeg;base64,’.base64_encode($row[‘data’]).'”/>’;

[/code]

possible solution

[code]

$sys = mime_content_type($_FILES[“fileToUpload”][“tmp_name”]);
if($sys == ‘application/x-zip’ || $sys == ‘application/msword’){
echo ‘ allowed’;
}else{
echo ‘not allowed’;
}

[/code]

to post a comment

15 Comments(s)

Copy linkTweet thisAlerts:
@rootNov 11.2018 — a web form DOES NOT USE &lt;button name="btn"&gt;Upload&lt;/button&gt; as a submit button its &lt;input name="submit" type="submit" value="whatever you want it to be like Submit"&gt; or in your case &lt;input name="btn" type="submit" value="Upload"&gt;

Checking the file name extension as well as the document type being interrogated, your only real concern is to not to allow uploads of executable files. There are many valid types of documents, not everyone had access to a microsoft system OR to Microsoft Office even if they do have a window box.

So you should really be limiting executable scripts and files and allow more text file formats.
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 11.2018 — Thanks for pointing out the submit button issue Root. I am not quite smart enough to figure out any other way I am going to have to use what I have. Any fixes would be appreciated
Copy linkTweet thisAlerts:
@ConstManNov 11.2018 — @PeaceTime2323 thanks for asking, there was a similar problem

Your code and solution @root helped me)))

@root too thanks)
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 11.2018 — @ConstMan#1597696

I am glad that it helped. Do you think you could help me fix my code above?
Copy linkTweet thisAlerts:
@rootNov 12.2018 — @PeaceTime2323#1597695 Well I D K where you were taught that but its the wrong way as its always been an <input tag for a submit button.

If you want something to work properly, its not a case of doing it your way that you only know (as I keep pointing out to my son, there is a tool for every job, use it properly and you will always get the expected outcome), note the use of "properly" because many people assume using it will yield the desired results off the bat, not always, hence the inclusion of properly because there is invariably something wrong if the form is't working right.

The &lt;form tag is also missing action and a name and if the form is not clear in where to send the data, it sends its data to itself (own page) and I see no reference to a processing script server-side either, so have you a script handler?
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 12.2018 — I know that you are right root. I have no idea how to code. I just bring the best I can and hope someone is able to touch it up. If nothing else could you show me how to insert my possible solution into the code?
Copy linkTweet thisAlerts:
@rootNov 13.2018 — Well, it does actually help if you understand structure which all languages have, with some exceptions to that rule but in essence, all programming languages follow rules for them to work, using the code(s) is also a requirement to understand how to use them as much as understanding the structure.

You will find plenty of poor examples of web forms out on the internet and ANYONE, it doesn't matter if it is a seasoned programmer under contract using the &lt;button for a submit option should hang their heads in shame.

Everyone piles in from the code perspective of scripting and not getting their markup correct before adding features.

A good learning route is...

HTML5 -> CSS -> JavaScript -> PHP -> SQL

There will be plenty of people who went the

HTML5 -&gt; PHP -&gt; SQL -&gt; CSS -&gt; JavaScript

or

HTML5 -&gt; JavaScript -&gt; CSS

routes

My advice is to learn CSS befor Javascript. a few lines of CSS could easily replace 100 lines of script.

THE DOM is easily referenced and people still jump to adding ID's to things that only require a name tag setting.

You get people using DIV's for tables and table when DIV's should be used, generally there is a poor level of understanding of technology layers and the components in those layers and how to properly use them.

If you follow advice and learn from it and understand the processes then you can quickly pick up programming understanding, putting it in to practice is a bit of a leap for beginners, I know, I was a beginner once.

Keep learning from your mistakes, unless you try to answer the problems first, being handed the answer on a plate is not helping you at all, its just slowing the learning process.
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 14.2018 — Thanks for your time and for the advice
Copy linkTweet thisAlerts:
@NogDogNov 14.2018 — As far as this bit of code...
``<i>
</i>$sys = mime_content_type($_FILES["fileToUpload"]["tmp_name"]);
if($sys == 'application/x-zip' || $sys == 'application/msword'){
echo ' allowed';
}else{
echo 'not allowed';
}<i>
</i>
`</CODE>
You would need to change <C>
['filetoUpload']</C> to the name of your file upload form field. Then you would need to check what the applicable MIME values would be for the types of files you want to allow (you can google that as easily as I can) and use them in the <C>if()</C> statement. Then it's up to you what you want to have happen when it passes the if condition or if not what you want to have happen in the else condition. That being said, I do not know how reliable/spoof-able that function is, so <I>[i]caveat emptor[/i]</I>.

BTW: AFAIK there's nothing wrong now with using a <C>
button</C> element for a submit -- as long as it includes <C>type="submit"`. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-type
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 15.2018 — Thanks, looks like I was able to fit that button type="submit" between the button tag. Hopefully have something to show you guys by tomorrow night if you are still here.
Copy linkTweet thisAlerts:
@rootNov 15.2018 — It depends on the server. Many servers expect a submit button.

You may want to add drag and drop, there are plenty of examples up in the either that are non-jquery, so noce and light weight.

For some people, clicking a link and navigating to a file is like... too much effort... so drag and drop can also be added and then AJAX (not to be confused with JQuery) if you want to make uploading more fun for that find navigation difficult.
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 15.2018 — Thanks for the feedback so far but I am still unable to get the file to run, all it shows is the title and its not throwing any errors. The button element now has type="submit" and I changed ["filetoUpload"] to ["myfile"]. (cant figure out how to fit my solution in there). I am using MAMP on my Mac book pro if anyone else is able to get this to run please let me know. I feel like its 90% there but I cant get the other 10% if someone can step in and drive at this point I would appreciate it.

I replaced my form with one I found online, and still all it shows is the title

<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="utf-8"/&gt;
&lt;title&gt;Upload PDF &amp; Word files to Database&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$dbh = new PDO("mysql:host=localhost;dbname=mydata","root","");
if(isset($_POST['btn'])){
$name = $_FILES['myfile']['name'];
$mime = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh-&gt;prepare("insert into myblob values('',?,?,?)");
$stmt-&gt;bindParam(1,$name);
$stmt-&gt;bindParam(2,$mime);
$stmt-&gt;bindParam(3,$data, PDO::PARAM_LOB);
$stmt-&gt;execute();
}
?&gt;
&lt;form method="post" enctype="multipart/form-data"&gt;
&lt;input type="file" name="myfile"/&gt;
&lt;button type="submit" name="btn"&gt;Upload&lt;/button&gt;
&lt;/form&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;?php
$stat = $dbh-&gt;prepare("select * from myblob");
$stat-&gt;execute();
while($row = $stat-&gt;fetch()){
echo "&lt;li&gt;&lt;a href='view.php?id=".$row['id']."' target='_blank'&gt;".$row['name']."&lt;/a&gt;&lt;/li&gt;";
}

<i> </i>$sys = mime_content_type($_FILES["myfile"]["tmp_name"]);
if($sys == 'application/x-zip' || $sys == 'application/msword'){
echo ' allowed';
}else{
echo 'not allowed';
}

<i> </i>?&gt;
<i> </i>&lt;/ol&gt;
&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@rootNov 16.2018 — it helps to know what the errors are that are being reported.
Copy linkTweet thisAlerts:
@PeaceTime2323authorNov 17.2018 — Good point root. By default MAMP has display errors turned off, I had to dig deep into the php.ini file to turn it on. Looks like there is a problem with my connection string to the db. I am going to work through it. How hard would it be to also insert a text field into the database. just need to add &lt;input type="text" name="firstname" into the form? And another ' ' in the ("insert into myblob values('',?,?,?)");
Copy linkTweet thisAlerts:
@rootNov 17.2018 — You just add it in where you want it to appear in the form.

On the server, you use the corresponding $_POST element to access any data in the field.
×

Success!

Help @PeaceTime2323 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...