0

i have a problem in uploading multiple file can anyone help me to solve this problem?

here is my index.php

<!DOCTYPE html>
<head>
    <title>MySQL file upload example</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
    <form action="add_file2.php" method="post" enctype="multipart/form-data">
       <input type="file" name="uploaded_file[0]"><br>
        <input type="file" name="uploaded_file[1]"><br>
        <input type="file" name="uploaded_file[2]"><br>
         <input type="submit" value="Upload file">
    </form>
    <p>
        <a href="list.php">See all files</a>
    </p>
</body>
</html>

add_file2.php

<?php
  $dbLink = new mysqli('localhost', 'root', '', 'sampleupload');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
for($c=0;$c<8;$c++){
if(isset($_FILES['uploaded_file['.$c.']'])) {
 
    if($_FILES['uploaded_file['.$c.']']['error'] == 0) {

        $name = $dbLink->real_escape_string($_FILES['uploaded_file['.$c.']']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file['.$c.']']['type']);
        $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file['.$c.']']['tmp_name']));
        $size = intval($_FILES['uploaded_file['.$c.']']['size']);
 
        
        $query = "
            INSERT INTO `file` (
                `name`, `mime`, `size`, `data`, `created`
            )
            VALUES (
                '{$name}', '{$mime}', {$size}, '{$data}', NOW()
            )";
 }
	

        $result = $dbLink->query($query);
 
     
        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']);
    }
 
   
  
}


echo '<p>Click <a href="index.php">here</a> to go back</p>';

?>
3
Contributors
24
Replies
27
Views
7 Years
Discussion Span
Last Post by ryan311
0

Hi,

check your code here. 6,7,8,9

for($c=0;$c<8;$c++){

if(isset($_FILES'])) {

You have indicated for loop with 8 iterations.
On your upload form its less than that. Not a good sign.

why cant you do it simple like

for($i=0;$i<count($_FILES);$i++)// U can use $_FILES super global array to catch all files. Thus my view. also count() and sizeof() works the same.
{
 if($_FILES['uploaded_file['.$i.']){
                 //CHECK UP YOUR LOGIC FROM HERE
THAT IS THE SECOND IF STATEMENT.

}

My advice is make it simple and build on it. Divide and conquer.

I can only point you to a simple and right direction. Get back to me if you can.

0

hi mate thank you for your reply. that code i get from tutorial i am new in php and still studying it ^^,. how can i make it simple? can u help me? btw i can manage 1 upload file but in this case multi upload i can't i don't know why. i try your code i always got this error

echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES);

An error accured while the file was being uploaded. Error code: 1

0

I think you need new code.
The code you had from whatever source if's looks too buggy to me.

You are looking to insert the file into a DB right.? what is the mime type?

If its not .txt, doc . Then i do not recommend saving into a DB. you can save it on the server side and keep the path in the DB.

Just give more info and i will write you a working script.

Edited by richieking: n/a

0

<!DOCTYPE html>

<head>

<title>MySQL file upload example</title>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

</head>

<body>

<form action="#" method="post" enctype="multipart/form-data">

<input type="file" name="uploaded_file0"><br>

<input type="file" name="uploaded_file1"><br>

<input type="file" name="uploaded_file2"><br>

<input type="submit" value="Upload file">

</form>

<p>

<a href="list.php">See all files</a>

</p>

</body>

</html>

//very basic script. build on it 

//You need to get the value of the file.

for($i=0;$i<count($_FILES);$i++){
	// 
	$upload="uploaded_file".$i;
	if(empty($_FILES[$upload]['name'])){
	// Do nothing. 
	}
	
	else{  
	 // you do this just incase all the form field was not porpulated.
	$goodFile=$_FILES[$upload]['name'];  /** 
	                                       * You can do all your checks by using $upload.
                                            *  ie. $_FILES[$upload]['mime_type'], $_FILES[$upload]['size'] etc
                                            */     
// Where the file is going to be placed Ofcourse you provide your own path
$target_path = "uploads/";

/* Add the original filename to our target path.  
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $goodFile); 


// If You intend to save files at the server side.
if(move_uploaded_file($_FILES[$upload]['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "<br/>There was an error uploading the file, please try again!<br/>";
}

// if you want to put inside mysql db

$content= file_get_contents('uploads/'.$goodFile);// uploads is the path you uploaded the file

// go ahead and insert into db. $content
 $content;
$query= "Insert Bla Bla values ($content)"; // Are you following me???????????

//EXECUTE mysql_query to insert. 

if (mysql_query($query)){
	// You DELETE the file You Uploade.
	unlink("uploads/$goodFile");
}

	}
	
}

There are few things you must add. a random file name and some security. please do not use this on a working server. Modify
and add few checks.

0

Thats not a hard nut. The logic is simple.

Modify this script and check for mime type such as txt,doc and write if statement to upload and insert and delete.

2. for the rest of the file, just save them on the server and save the path into the DB.

You must also generate random file name to help the uniqueness of the files. very simple.

$foo= rand (time(),1234567890);
   // The real file extention.to get the ext you do this.
    
$filename = strtolower($goodfile) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];

// NEW FILE NAME IS 
$newName=$foo.".".$sxts;

The rest of the job thus the mime check,upload,insert are all basic if clauses.

Please explore :)

Edited by richieking: n/a

0

hi richie still not :( can you provide me a sample because im new in php :( i don't know what should i put in my database.

0

hi richie i'm still updating my code here it is my new code i'm still getting a problem in creating a path

<?php
if(!is_dir("upload")){//do we need to make the uploads directory for the files?
    mkdir("upload");//make the rest of the script safe, though this will only be done once
    
}
// 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 = new mysqli('localhost', 'root', '', 'sampleupload');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }
 		$putItAt = "upload/".basename($_FILES['uploaded_file']['name']);
		$putItAt = str_replace("php","txt", $putItAt);
        // Gather all required data
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
        $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 `try` (
                `name`, `mime`, `size`, `data`, `created`
            )
            VALUES (
                '{$name}', '{$mime}', {$size}, '{$data}', NOW()
            )";
 
        // Execute the query
        $result = $dbLink->query($query);
 
        // Check if it was successfull
        if($result) {
			if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$putItAt))
			{
            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']);
    }
 
    
}
else {
    echo 'Error! A file was not sent!';
}
 
// Echo a link back to the main page
echo '<p>Click <a href="index.html">here</a> to go back</p>';
?>

hope you can help me thanks a lot.

0

What error do you receive, ??? and what exactly do you need.??

The multi upload script i wrote you can upload any number of files you need.

Why dont you build on it?

0

My problem is the file is save on the database not on the path. i want it to transfer into upload file folder. :)

because if the file save in my dbase it get bigger and slowly to retrieve. i have only 1 question richie, is it possible to change the dbase all i want to save is the name, description of the file and the date user upload the file? i want to add name textbox and description textbox. :)

Edited by ryan311: forgot

0

hi ritchie i have something to ask, in this line

if (mysql_query($query)){
    // You DELETE the file You Uploade.
    unlink("uploads/$goodFile");
}

it means delete the file in the path?

i have 1 more to ask

how can i limit each user to 50mb storage space to their upload?

i mean the total storage of all files upload.

thanks

Edited by mike_2000_17: Fixed formatting

0

ryan311,

My problem is the file is save on the database not on the path. i want it to transfer into upload file folder.

because if the file save in my dbase it get bigger and slowly to retrieve. i have only 1 question richie, is it possible to change the dbase all i want to save is the name, description of the file and the date user upload the file? i want to add name textbox and description textbox.

You can add any data you want about the file into the DB. No limit. Yes its a good practise to save the path into your database and put the file in its folder on your server. This means you must have the folder created during the whole show. This means your script create one folder per user.

i have 1 more to ask

how can i limit each user to 50mb storage space to their upload?

i mean the total storage of all files upload.

thanks ^^,.

Yes you can do that. a piece of cake. you create the folder as i indicated for each user, have the folder name, folder size field in your DB.
During the upload, you check with ...

1. if the folder exist, if not, you create the folder and save the path to the folder into a variable for future use.
2. If the User already got a folder, you run a query to check if the size of the folder is less than the size you need. There are 2 or more ways to check that.

a. You calculate the size of all the uploaded files against the max upload size.
this mean you already got a field to take file size (The uploaded file details... ie. fileName,fileSize,mimeType,directoryPath,uploadDate,).

b. Or you can check the directory size against your max upload size.

**** Once you got the size, you can write your upload around that with those details***

ryan311. try and do this as a programmer.

1. Always have yourself a notebook to write what you want.
2. Plan on how to do that step by step.
2a. Plan well..
2b.Try you ideas..
2c.Keep planning and trying.

You see, the more you have good idea about what you want, its very easy to programme.

do things gradually and one after the other. ok? ;)

0

ryan311

hi ritchie i have something to ask, in this line

if (mysql_query($query)){
// You DELETE the file You Uploade.
unlink("uploads/$goodFile");
}

it means delete the file in the path?

that is if you want to delete the file just uploaded because you wish to store that in your DB. It is just an option.

0

thank you richie ^^. i have a problem in moving a file to my root folder. i try to upload same file. only 1 file put in my root folder.

Edited by ryan311: n/a

0

i have a problem in moving a file to my root folder. i try to upload same file. only 1 file put in my root folder.

Ryam311,
root folder as /home/ryan311 ???

What OS?. linux?

If you need system root....
You will need root permission. Php can not give you root perm.

Edited by richieking: n/a

0

i mean in upload folder. :) my OS is windows 7 i was searching last night about it and still i can't find my answer. i really have a problem in uploading a file with the same name. it save on database but i can see only 1 in my upload folder.

0

Because when you upload 10000000000 files with the same name.
You will see and have Only 1 file.

They will over write each other. They must be distinct file names to keep all.

;)

Edited by richieking: n/a

0

thanks maybe i need to validate the file name of the file :) ^^. this is my last question ritchie, how can i delete the file in my upload folder? is there a way to delete that file in my upload folder?

0

Hi mate Thanks for your reply. I can get the code i am new to php tutorial and still studying. How I can keep it simple? can u help? i certainly can handle a file to download, but in this case I can not upload multiple do not know why. i try i still have this error code.

0

Hi mate Thanks for your reply. I can get the code i am new to php tutorial and still studying. How I can keep it simple? can u help? i certainly can handle a file to download, but in this case I can not upload multiple do not know why. i try i still have this error code.

The multi upload code should work without problem. Just change the upload dir to what ever path and make sure you have a read write permission.

;)

0

richie can u help me, i have a file sharing my problem is how can i get the file?

here is my code in file sharing

<?php
session_start();
include ('dbconnect.php');
 
$userid = $_SESSION['id'];
$id = $_POST['fileid'];
$getfile = mysql_query("Select * from try where id ='$id'");
$row = mysql_fetch_array($getfile);
$name = $row['name'];
$mime = $row['mime'];
$size = $row['size'];
$data = $row['data'];
$date = $today = date("F j, Y");
$send = $_POST['share'];
$sendmany = explode(',', $send);
 
for ($counter=0; $counter<count($sendmany); $counter++)
	{
		$sendmany[$counter] = trim($sendmany[$counter]);
		$sql = mysql_query("Select * from user where email='$sendmany' or username='$sendmany'");
		if (mysql_num_rows($sql) > 0)
		{
		$send = mysql_query("Insert into try (name, mime, size, data, userid, date) Values ('$name', '$mime', '$size', '$data', '$userid', '$date'");	
		}
	}
	if ($send)
	{
	echo 'wow';	
	}
?>

is it possible to get the file in my upload folder?

for example

i have project.docx this project.docx in my upload folder is USERID_project.docx

i put userid to be able to have a unique file to each user.

i want it to share with your for example your userid is 7 i want it to save another file with 7_project.docx same file. how can i do that? hope you can help me for the last time :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.