Log in

View Full Version : PHP Upload Form



Rockonmetal
09-01-2007, 08:34 PM
Please read all before answering... if you do not understand make sure you ask... thanks!
ok heres what I've got... I got a peice of code I got from PHPFreaks.com... its a multiple file uploader form... which works perfectly! The thing is I'm having trouble understanding to add on different fields like textarea and text box to so that I don't have a bigilion forms on my page...
Here is the code for the upload form...

<?php
//upload directory.
//change to fit your need eg. files, upload .... etc.
$upload_dir = "submitions/";
//number of files to upload.
$num_files = 1;
//the file size in bytes.
$size_bytes =2048000; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".gif",".jpg",".jpeg",".png",".txt",".nfo",".doc",".rtf",".htm",".dmg",".zip",".rar",".gz",".exe");


//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> is NOT writable, Please CHMOD (777)");
}


//if the form has been submitted, then do the upload process
//infact, if you clicked on (Upload Now!) button.
if (isset($_POST['upload_form'])){

echo "<h3>Upload results:</h3>";

//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {

//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$file_name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$file_name = str_replace(' ', '_', $file_name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];

#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#

if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File $i: Not selected.<br>";
}else{
#-----------------------------------------------------------#
# this code will check file extension #
#-----------------------------------------------------------#

$ext = strrchr($file_name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($file_name) Wrong file extension. <br>";
}else{
#-----------------------------------------------------------#
# this code will check file size is correct #
#-----------------------------------------------------------#

if ($file_size > $size_bytes){
echo "File $i: ($file_name) Faild to upload. File must be <b>". $size_bytes / 1024 ."</b> KB. <br>";
}else{
#-----------------------------------------------------------#
# this code check if file is Already EXISTS. #
#-----------------------------------------------------------#

if(file_exists($upload_dir.$file_name)){
echo "File $i: ($file_name) already exists.<br>";
}else{
#-----------------------------------------------------------#
# this function will upload the files. :) ;) cool #
#-----------------------------------------------------------#
if (move_uploaded_file($file_tmp,$upload_dir.$file_name)) {
echo "File $i: ($file_name) Uploaded.<br>";
}else{
echo "File $i: Faild to upload.<br>";
}#end of (move_uploaded_file).

}#end of (file_exists).

}#end of (file_size).

}#end of (limitedext).

}#end of (!is_uploaded_file).

}#end of (for loop).
# print back button.
echo "&#187;<a href=\"$_SERVER[PHP_SELF]\">back</a>";
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo " <h3>Select files to upload!.</h3>
Max file size = ". $size_bytes / 1024 ." KB";
echo " <form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "File $i: <input type=\"file\" name=\"file". $i ."\"><br>";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload Now!\">
</form>";
}
?>
It works...
All I am concentrating is how to get this to work...
I wanna add 5 inputs on to it... not file inputs but different inputs:
i wanna add:
3 Textboxes (Named: Name, Email, and File Title)
1 Textarea (Named: Description)
and 1 checkbox (Named: TermsofService)
I also want the form to validate the extra things i'm adding on when the submit button is pressed... Don't write something to check the file uploader part because it already validates to make sure that the file being uploaded is the right one... I don't have any idea how to do this... so please be very detailed as where peices go or just give the whole thing with everything I asked for... *giving everything together would really help me out!*... I know that you can write data on to a file using filewrite, I just don't know the code that will do it when you submit the form... Thanks!

JShor
09-02-2007, 05:25 AM
Ok, well you need a database to store all of you're info. I wrote it with this intent of you using mysql, if you're using another database, post a reply if you have some other type like postgres, dbsc, ms ODBC, etc.,




<?php

//connect to mysql. You MUST edit these! (except localhost)
mysql_connect("localhost", "MYSQLUSER", "MYSQL_PASS") or die(mysql_error());
mysql_select_db("MYSQL_DB") or die(mysql_error());
//upload directory.
//change to fit your need eg. files, upload .... etc.
$upload_dir = "submitions/";
//number of files to upload.
$num_files = 1;
//the file size in bytes.
$size_bytes =2048000; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".gif",".jpg",".jpeg",".png",".txt",".nfo",".doc",".rtf",".htm",".dmg",".zip",".rar",".gz",".exe");


//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> is NOT writable, Please CHMOD (777)");
}


//if the form has been submitted, then do the upload process
//infact, if you clicked on (Upload Now!) button.
if (isset($_POST['upload_form'])){

echo "<h3>Upload results:</h3>";

//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {

//define variables to hold the values.

mysql_query("INSERT INTO files (description, file_title, email, name) VALUES('$description', '$file_title', '$email', '$name') ") or die(mysql_error());
$new_file = $_FILES['file'.$i];
$description = $_POST['description'];
$file_title = $_POST['file_title'];
$email = $_POST['email'];
$name = $_POST['name'];
$file_name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$file_name = str_replace(' ', '_', $file_name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];

#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#

if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File $i: Not selected.<br>";
}else{
#-----------------------------------------------------------#
# this code will check file extension #
#-----------------------------------------------------------#

$ext = strrchr($file_name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($file_name) Wrong file extension. <br>";
}else{
#-----------------------------------------------------------#
# this code will check file size is correct #
#-----------------------------------------------------------#

if ($file_size > $size_bytes){
echo "File $i: ($file_name) Faild to upload. File must be <b>". $size_bytes / 1024 ."</b> KB. <br>";
}else{
#-----------------------------------------------------------#
# this code check if file is Already EXISTS. #
#-----------------------------------------------------------#

if(file_exists($upload_dir.$file_name)){
echo "File $i: ($file_name) already exists.<br>";
}else{
#-----------------------------------------------------------#
# this function will upload the files. :) ;) cool #
#-----------------------------------------------------------#
if (move_uploaded_file($file_tmp,$upload_dir.$file_name)) {
echo "File $i: ($file_name) Uploaded.<br>";
}else{
echo "File $i: Faild to upload.<br>";
}#end of (move_uploaded_file).

}#end of (file_exists).

}#end of (file_size).

}#end of (limitedext).

}#end of (!is_uploaded_file).

}#end of (for loop).
# print back button.
echo "»<a href=\"$_SERVER[PHP_SELF]\">back</a>";
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo " <h3>Select files to upload!.</h3>
Max file size = ". $size_bytes / 1024 ." KB";
echo " <form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "File $i: <input type=\"file\" name=\"file". $i ."\"><br>";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload Now!\">
Name: <input type=\"text\" name=\"name\"><br />
File Title: <input type=\"text\" name=\"file_title\"><br />
Email: <input type=\"text\" name=\"email\"><br />
<br /><br />
File Description: <textarea name=\"description\"></textarea><br />
<input type=\"checkbox\">I agree to the

//here, you edit the url to your TOS page
<a href=\"YOURURI\">TOS</a><br />
</form>";
}
?>


And then, run this query in your database administration system (usually phpMyAdmin)



CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`description` varchar(255) collate latin1_general_ci NOT NULL,
`file_title` varchar(255) collate latin1_general_ci NOT NULL,
`email` varchar(255) collate latin1_general_ci NOT NULL,
`name` varchar(255) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;


Good luck! :)

Rockonmetal
09-02-2007, 05:34 AM
k, unfortunitly i don't got MySQL installed with Wamp5 *i know i don't know how to install it*

alexjewell
09-02-2007, 12:05 PM
I'll write a little script to give you an idea - you want this to be added to a text file somehow? Can I have some more info about that?

Rockonmetal
09-02-2007, 03:00 PM
Ok, i know theres a code right here which adds it to a file. heres the code off of php.net

<?php
$filename = 'test.txt';
$somecontent = "$input1 all data from post into here...";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}

echo "Success, wrote data to file ($filename)";

fclose($handle);

} else {
echo "The file $filename is not writable";
}
?>


I just don't know how to do it when the user presses upload

boogyman
09-02-2007, 05:18 PM
call the function that you have that in when the user presses upload

Rockonmetal
09-02-2007, 08:35 PM
I know how to make a function, but not how to call it when the user presses upload... thats why I'm asking...

alexjewell
09-03-2007, 02:54 PM
You would just not declare $subcontent within the function, and do it this way:



function writeIt($somecontent){
$filename = 'test.txt';

if (is_writable($filename)) {

if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}

echo "Success, wrote data to file ($filename)";

fclose($handle);

} else {
echo "The file $filename is not writable";
}
}


Then, you do the following when you want to use it:



writeIt('Content to be written here...');


I would put the content together beforehand, though, like this:



$content = 'Content to be wirrten here...just to be more organized...';
writeIt($content);

Rockonmetal
09-03-2007, 05:02 PM
Ok i don't see anything that would says on submit or something like that...

boogyman
09-03-2007, 06:21 PM
Ok i don't see anything that would says on submit or something like that...

you can do it a couple ways... but I think it would be best to call it after you have done the sanitization and cleaning...



function _____ {
// WHATEVER YOU DO TO CLEAN / PRE-PROCESS DATA

if( !$errors ) {
return writeIt($somecontent);
}
else {
// WHATEVER YOU WANT TO ERROR AS
}
}


the $errors is whatever you are storing your errors as... if there arent any pre-write errors it will go ahead and write the content, if there are errors then you insert your error handling code

Rockonmetal
09-03-2007, 06:59 PM
k thnx boogyman! (who knew the boogyman could be so helpful... because usually ure afraid of the boogyman... hiding in the closet or under the bed, or inside the peice of pie :D...) lol...
I'll try it out! thanks!

Rockonmetal
09-04-2007, 01:21 AM
Ok I finally got to test out the code... I think I understand it but its not working...

<html>
<body>
<form action="report.php" method="post">
<input type="submit">
</form>
<?php
function writeIt(){
echo "Hi";
}
//Function which says write this..
if( !$errors ) {
return writeIt();
}
//If button is pressed perform function named writeIt
else {
echo "Data could not be stored...";
}
//Error message above...
}
?>
</body>
</html>
I went simple because I usually go simple then start to expand... I have no idea how to do this...
Thanks for helping...

boogyman
09-04-2007, 12:35 PM
<html>
<body>
<form action="report.php" method="post">
<input type="submit">
</form>
<?php
function writeIt(){
echo "Hi";
}
//Function which says write this..
if( !$errors ) {
return writeIt();
}
//If button is pressed perform function named writeIt
else {
echo "Data could not be stored...";
}
//Error message above...
}
?>
</body>
</html>
there is confusion inside this code.. you are trying to do the form and the write... the function writeIt() as you have it here would ened to be in the "report.php"

from there.. I made it so that the errors were put into an array, and on
if( !$errors )
checks to see if there is anything in that array. so you would need to change that line to fit your script personally. however you are handling the errors.

Rockonmetal
09-04-2007, 05:54 PM
K... I'll try this... thanks