Uploading files with PHP - php

I am using a form for users to upload files to my website. I want to allow them to upload multiple photos at once, so I am using the HTML5 "multiple" attribute.
My HTML:
<form method="post" action="save.php">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
But, for some reason when I run the script, I get an error saying undefined index: uploads. And an error saying that I have an invalid argument supplied for foreach(). What could I be dong wrong?
Thanks
UPDATE
Okay, setting the enctype="mulitpart/form-data" worked. Now, I am having trouble with moving the file. I am getting the error move_uploaded_file() expects parameter 1 to be string, array given. What am I doing wrong here?
Thanks again

You need the proper enctype to be able to upload files.
<form method="post" enctype="multipart/form-data" action="save.php">

try this html code: <form method="post" action="save.php" enctype="multipart/form-data">
Then in PHP:
if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
} else {
echo 'some error message!';
}

In order to upload files in the first place, you need enctype="multipart/form-data" on your <form> tag.
But, when you upload multiple files, every key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name']).
You need to get the array key when looping, so you can process each file. See the docs for move_uploaded_file for more deatils.
<?php
foreach ($_FILES['uploads']['name'] as $key=>$file) {
echo $file."<br/>";
$file = time().$file;
$target = UPLOADPATH.$file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with query 2');
}

index.html
<form method="post" action="save.php" enctype="multipart/form-data">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="Upload Image"/>
</form>
save.php
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {
$file_name = time() . $_FILES['uploads']['name'][$x];
$file_tmp = $_FILES['uploads']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>

Related

Send file to server derictory over form with user's name

I have a form.html
<form action="user.php" method="post" enctype="multipart/form-data" >
<input type="text" size="40" name="UserCallFile" >
<input type="file" name="filename"><br>
<input type="submit" value="Send"><br>
</form>
And user.php
<?php
if(is_uploaded_file($_FILES["filename"]["tmp_name"]))
{
move_uploaded_file($_FILES["filename"]["tmp_name"], "img/" . $_FILES["filename"]["name"]);
} else {
echo("Error");
}
?>
I need that user could download file to server which name of this file he written on text input. Ho to do that?
I tried this way
move_uploaded_file($_FILES["filename"]["tmp_name"], "img/" . $_POST["fileName"] . "." . "png");
But of course here "png" have to be logic with any file extension.
I hope you are understand the idea of problem.
Simply try to play with this..
$image = $_FILES["filename"]["tmp_name"];
$dir = "gallery/"; //adjust this correctly, watch for slashes depending on your website config
$newname = $image['name'];
if(!#copy($image, $dir . $newname))
{
echo 'error';
}

How to upload an array of files?

I'm trying to build an array of files by submitting a form several times, then move those files to a directory, but it's not working. Every uploads just overrides the previous and then it doesn't even move that one (the upload_to_file() function doesn't do anything)
HTML:
<form id="form" action="home.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="8000000">
<input class="upload_btn" type="file" name="images[]" id="image_file">
<input type="submit" id="img_submit" class="form_button" name="submit_image" value="upload"/>
</form>
It is important that there is only one upload button which can be used to upload many files.
I need them to be stored in an array so I can display their ['name'] anywhere with a loop.for ($i = 0; $i < count($_FILES['images']['name']); $i++){}
Then once another form is submitted it calls a function to move each file in the array to a directory.
Function inside an included php file:
function upload_to_file(){
$image_paths = array();
$target_dir = "uploads/images/";
$path = $target_dir . basename($_FILES['images']['name'][0]);
if(isset($_FILES['images']['name'][0]) && $_FILES['images']['size'][0] > 0)
{
if (move_uploaded_file($_FILES['images']['tmp_name'][0], $path)) {
$image_paths[0] = "uploads/images/";
}
}
return $image_paths;
}
I'm only testing it with the first element in the array, but will need to make a loop later.
Here is the program, which help you to upload multiple files. in the code "sub" is the submit button name. "upload" is the name of file controller, the uploaded files are stored in the directory called "img" that you have to create on your root folder.
<?php
if (isset($_POST['sub'])) {
if (count($_FILES['upload']['name']) > 0) {
for ($i=0; $i<count($_FILES['upload']['name']); $i++) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "") {
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
}
}
}
}
echo "<h1>Uploaded:</h1>";
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
HTML Code is given
<form action="" enctype="multipart/form-data" method="post">
<input id='upload' name="upload[]" type="file" multiple="multiple" />
<input type="submit" name="sub" value="Upload Now">
</form>

Multiple Upload using CTRL Key PHP

would you help for my code , i need to do the multiple upload but i cant so will you help me please. i need so bad.
here's my code
i made multiple upload the form but it is not working. the output is "error array"
//HTML
<html>
<head>
<form name="Image" enctype="multipart/form-data" action="upload.php" method="POST">
<h1><font face="tahoma"> UPLOAD FILES</h1>
<label for="file">Filename:</label>
<input type="file" name="Photo[]" accept="image/*" multiple="multiple"/><br/><br/>
<input type="hidden" id="pageName" name="pageName">
<script type="text/javascript">
//get page name from parent
var value = window.opener.pageName
document.getElementById("pageName").value = value;
</script>
<INPUT type="submit" class="button" name="Submit" value=" Upload ">
<INPUT type="reset" class="button" value="Cancel"><br/><br/>
</form>
</head>
</html>
//PHP this is were upload is do.
<?php
include('global.php');
?>
<?
$uploadDir = 'directory/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'][0];
$fileName1 = $_FILES['Photo']['name'][1];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName . $fileName1;
//upload error
if ($_FILES["Photo"]["error"] > 0)
{
echo "Error: " . $_FILES["Photo"]["error"] . "<br />";
}
//photo already exixts
else
//insert image into DB
{
move_uploaded_file($tmpName, $filePath);
$filePath = addslashes($filePath);
$filePath = stripslashes($filePath);
$filePath = mysql_real_escape_string($filePath);
$query = "INSERT INTO images (image , category ) VALUES ('$filePath', '$pageName')";
mysql_query($query) or die('Error, query failed');
echo" Upload Successful. <br/> <br/>";
echo "Stored in: " . "directory/" . $_FILES["Photo"]["name"];
?>
<br/><br/>
<img width="300" height="400" src="directory /<?=$_FILES["Photo"]["name"]?>"><br/>
<?
}
}
?>
Error: Array is telling you that the error being returned is actually an Array object, not a string. If you want to see the actual error message, you need to view the full contents of the array. Something like print_r($_FILES["Photo"]["error"]); or looping through the array like so
foreach($_FILES["Photo"]["error"] as $err) {
echo "error: " . $err . "<br>";
}
Or you can just print the first error returned just as you have returned the first file in your name array echo $_FILES["Photo"]["error"][0];

How to move an uploaded file

I have an HTML web form where users can upload multiple files. I am having trouble with moving the files though.
HTML:
My HTML:
<form enctype="multipart/form-data" method="post" action="save.php">
<input type="hidden" name="MAX_FILE_SIZE" value="500000"/>
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
Save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
$target= UPLOADPATH . $file;
move_uploaded_file($file, $target)
or die('error with moving the file');
$file= time() . $_FILES['uploads']['name'];
echo $file;
}
The problem is with move_uploaded_file(). What could I be doing wrong?
Try as below, you need to pass first parameter as file source
foreach ($_FILES['uploads']['name'] as $key => $file) {
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with moving the file');
$file= time() . $_FILES['uploads']['name'];
echo $file;
}

upload file with php and save path to sql

Does anyone know any good tutorial on how to upload a file with php and save the files path to a sql server?
To upload a file you need at least a HTML POST form with multipart/form-data encoding. Therein you put an input type="file" field to browse the file and a submit button to submit the form.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
In the upload.php the uploaded file is accesible by $_FILES with the field name as key.
$file = $_FILES['file'];
You can get its name as follows:
$name = $file['name'];
You need to move it to a permanent location using move_uploaded_file(), else it will get lost:
$path = "/uploads/" . basename($name);
if (move_uploaded_file($file['tmp_name'], $path)) {
// Move succeed.
} else {
// Move failed. Possible duplicate?
}
You can store the path in database the usual way:
$sql = "INSERT INTO file (path) VALUES ('" . mysqli_real_escape_string($path) . "')";
// ...
From http://www.w3schools.com/php/php_file_upload.asp
HTML
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; //<- This is it
}
}
?>
Note that to upload the file you need to specify the path to save the file. If you save the file you already know it path.

Categories