Jump to content

Need PHP uploading help


rodriguezt0871

Recommended Posts

Hi my name is Tomas

 

Ive been building a website for my church, and at first I just used html. But now im starting to discover php which has helped me to be able to update the website more efficiently.

 

I love the tutorials that Stefan has, they have helped me tremendously. But now im stuck.

 

I'm making a admin page for myself so that when we get new content I can throw them on the website quickly.

 

I'm at the point to where im trying to build a mp3 uploading script where the form would include the following:

 

Sermon Title______________

Speaker_________________

Date____________________

__________Browse

Submit

 

I have my form built but now its just the uploading script. I would like all this information to be placed in a mysql database where I have 5 feilds:

 

id

title

Speaker

date

file_path

 

on top of that I would like the script to permanently save this file to my server.

 

Can anyone help me, or can walk me through making this script?

Link to comment
Share on other sites

I think the best way to approach this is to break it down into simpler steps. Do each of these steps one at a time, working from the simplest to the most difficult, and make sure they work before moving to the next step.

 

-- Build your form and a basic processing script that gets the data from the form and displays the data

http://www.tizag.com/phpT/postget.php

 

-- Make sure you build in basic error checking into the form. For example, are there certain fields that are required? If so, check for them and display an error if they aren't filled in.

 

-- Revise the form to save the data to your database instead of displaying it. Don't worry about actually uploading any files in this step, just save the file name in the database (you may need to look at the links at the end of this post on file uploads to figure out the file name).

http://www.tizag.com/mysqlTutorial/mysqlinsert.php

http://teamtutorials.com/web-development-tutorials/php-tutorials/inserting-data-into-a-mysql-database-using-php

 

-- take a look at security, perhaps using htmlspecialchars() and mysql_real_escape_string() to make sure no invalid data is being passed into the form.

http://www.php.net/manual/en/function.htmlspecialchars.php

http://php.net/manual/en/function.mysql-real-escape-string.php

 

-- Revise the form to include upload functionality

http://www.tizag.com/phpT/fileupload.php

http://www.php.net/manual/en/features.file-upload.post-method.php

 

Hopefully that will help get you started.

Link to comment
Share on other sites

alright giving the info you have provided, this upload will only be used by authorized personell in a closed area. I'll give you a quick walk through how you could write your php code to work with mp3 uploads.

 

 

Let's begin with creating the form one can use to locate and choose what file to upload:

 

>


Upload Test



Simpel upload form
</pre>
<form enctype="multipart/form-data" action="upload.php" method="POST">

 Upload this file: 

</form>
<br><br><br

 

Right from the start you can see that this form might differ from what you've come in contact with before depending on what you've coded so far.

 

Let's cover some key part of the form that you should know about.

 

The form uses POST, it won't work with GET. Although the PUT method is supported by Netscape composer and Amaya it will not work with the code ahead.

 

In the form tag you have to put the attribute enctype="multipart/form-data". Simply because we have to tell the server that a file is coming along with the regular form information.

 

We also must have a field that sets the maximum allowed upload file size in bytes present. It's of type hidden thus won't show up other than in the sourcecode. However just because it's hidden doesn't mean it's safe so we will be checking it's state further ahead in the coding.

In the example above I have around 10,000,000 bytes which very roughly translated somewhere around 10 MB. Remember that the max file size allowed is set in the php.ini file so if it only states 2 MB then our 10MB limit in the code won't matter as the 2MB set in the php.ini is in effect.

 

Lastly we need a input of type file, which is quite obvious, for how else are we supposed to locate the file needed to be uploaded.

 

Also keep in mind to use "normal" names for the inputs, as we will be using them in the php code.

 

so right now we got the html form, we have selected a file and hit upload. Now it's time to process it. So the data we need to handle in our php script will be stored in the superglobal array $_FILES. as our form element is called userfile, the array will have the following contents:

 

$_FILES['userfile']['tmp_name'] is the place where the file has been temporarily stored on the web server, and the copy in this location will be removed from the server once the script reaches the end.

 

$_FILES['userfile']['name'] is just the file's name on the user's system.

 

$_FILES['userfile']['size'] is the size of the file in bytes

 

$_FILES['userfile']['type'] is the MIME type of the file. for example a txt file has text/plain, and a gif image has image/gif

 

$_FILES['userfile']['error'] here any possible error message from an error during the file upload will be located.

 

Good so let's get coding:

 


Uploading file....


if ($_FILES['userfile']['error'] > 0){
echo 'Problem: ';

switch($_FILES['userfile']['error']){
   case 1: echo 'File exceeded upload_max_filesize'; break;
   case 2: echo 'File exceeded max_file_size'; break;
   case 3: echo 'File only partially uploaded'; break;
   case 4: echo 'No file uploaded'; break;
}
exit;
}

// Let's check if the file is of the right type (checking MIME type)
// mp3 files are of MIME types audio/mpeg3, audio/x-mpeg-3, video/mpeg, video/x-mpeg
// I'll be just checking one of them as after all it's way too easy to cheat.

if($_FILES['userfile']['type'] != 'audio/mpeg'){
echo ' Problem: file is not mp3!';
exit;
}

// let's check whether the hidden input field has been altered by some idiot trying to upload
// something bigger than allowed

if($_FILES['userfile']['size'] > 10485760 ){
  echo 'Problem: the file size is too big, do not mess with my html punk!';
  exit;
}

// now let's proceede with moving the file where we want it to be

// $uploadFile is the path to where I'll be moving my file, just remember that I'm writing this on a *nix system.
// in the root tree I've created a directory called /uploads and it's to here I'm uploading. 
//So remember full path must be specified. Let's assume you are on a win and want to upload to C:\uploads\ then the path would be 'file://C:/uploads/'.$_FILES['userfile']['name'];
// Remember that the directory must exist as well.

$uploadFile = '/uploads/'.$_FILES['userfile']['name'];

if (is_uploaded_file($_FILES['userfile']['tmp_name']) ){
 if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile)){
   echo 'Problem: Moving file failed!';
   exit;
 }
} else {
echo 'Problem: Possible file upload attack. Filename: ';
echo $_FILES['userfile']['name'];
exit;
}

echo 'File uploaded without any problems';

// Place some code that saves $uploadfile (the path to the file along with all other info you needed in the database after this and you are done.

?>

 

 

Quite a nice little chunk of code just to upload a file, however as you most likely have spotted, the majority of the code is to check for errors and reporting them back. And I'll cover that in a bit.

 

First let's go through some common sense security aspects of file uploading, although it's a great tool to use, it also is the type of function mostly attacked and abused by idiots trying to harm you and your business. And file uploads with php has a bad history as it had some very nasty security flaws that lead to some spectacular attacks in the past. However they got fixed but nevertheless always make sure you have the latest php version and if you don't make sure you check regularly for patches related to PHP's upload functions. To prevent the case where an old security flaw is present in your system just because you never patched the bad code PHP uses.

 

Also it's wise to restrict the upload system to only administarators maybe moderators depending on the organisation, in other words only trusted people, to prevent any security breaches. Keep in mind if you are not uploading the files to a sandbox/virtual space then a well crafted exploit could reveal you password for accessing the host system, not to mention give free passage to exploring your system and whatnot.

 

So with this in mind let's go over what the hell we just did in the upload.php code.

 

So the first chunk of code is just checking the error code, if one of them occured it will be caught by the switch system, displaying our error code then terminating the script.

 

We then proceede with checking the MIME type. So we check if $_FILES['userinput']['type'] holds that type. It is very important that you realize that this is just error checking and has nothing to do with the security. As the MIME type found in that array element is based on the file ending of the file you are uploading which the browser you are using picks up and send to the server. NO WHERE is it guaranteed that the file being sent is actually a mp3 file and not some script that will cause you a lot of harm.

The one that would be interested in spoofing or pretend another file is a mp3 by altering the file extension, has only one reason and this is a malicious intention. Thus the importance of only trusted parties using this system.

 

 

Next step is a security step, where we check if the file that is said to be uploaded was really uploaded, this is vital as not doing this could result in me sending in a entry to local files on your system, the file exists but it's nothing I uploaded myself, well imagine I just sent in a entry that would result in trying to open or read the file /etc/passwd on a *nix system. That would not be good, would it?

 

if this all goes well, the file is then copied to the directory /uploads/.

 

All you got to do is add a small snippet of code that adds the data of the variable $uploadFile (which is the path to the mp3 file) to you database record and you are done.

Edited by krillz
Link to comment
Share on other sites

okay here is my form:

 

   Sermon Title:

   Speaker:       

   Date:            





 

and here is my upload php:

 

<?php
$sermon = $_POST["sermon"];
$speaker = $_POST["speaker"];
$date = $_POST["date"];
$audio = $_FILES["audio"];

echo 
   $audio;

// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("audio") or die(mysql_error());

// Insert a row of information into the table "example"
mysql_query("INSERT INTO audio 
(sermon, speaker, date, path) VALUES('$sermon', '$speaker', '$date', '$audio' ) ") 
or die(mysql_error("error"));  

echo "Data Inserted!";

?>

 

Its not working. I need it to save the file but an errors occur.

Link to comment
Share on other sites

okay here is my form:

 

></pre>
<form name="audio_upload" action="upload.php" method="POST">
   Sermon Title:

   Speaker:       

   Date:            





</

 

and here is my upload php:

 

$sermon = $_POST["sermon"];
$speaker = $_POST["speaker"];
$date = $_POST["date"];
$audio = $_FILES["audio"];

echo 
   $audio;

// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("audio") or die(mysql_error());

// Insert a row of information into the table "example"
mysql_query("INSERT INTO audio 
(sermon, speaker, date, path) VALUES('$sermon', '$speaker', '$date', '$audio' ) ") 
or die(mysql_error("error"));  

echo "Data Inserted!";

?>

 

Its not working. I need it to save the file but an errors occur.

 

 

If you read the post above, where I've shown you how you need to go about uploading a file then you would see that your form is wrong, also how you deal with the files (that is if the server ever knew you were sending something) is not correct.

 

Either check my previous post or check the numerous links provided.

Link to comment
Share on other sites

Specifically what errors are you running into?

 

based on the code I would say php generates an error based on this strange code formulation:

 

$audio = $_FILES["audio"];

 

As there is no such thing. His correct super global array element for the file would be

$_FILES['audio']['tmp_name'] but it is deleted as soon as the script hits the end as he didn't move it out of the temporary directory.

 

His form need revising as well, as that is not a correct file upload form, the server never knows a file is coming so even if he changes the code to use the correct array form it will still not find the file.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...