move_uploaded_file in PHP not working? - php

I'm actively learning php and am working on a CMS Project. I'm stuck on image upload.
PHP
if ( $_POST['img'])
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
HTML
<img src="images/$image" />
MySQL
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
The name of the file is uploaded to database but the file itself is not being uploaded to the destination folder.

Type your html code in between form and in the form wrtie as following
<form action="" method="post" enctype="multipart/form-data">
<img src="images/$image" name="img" />
...
</form>

Use $_FILES to check file is posted or not instead of $_POST. Also make proper quote for variables. Then for echo php variable use php tags.
Try
PHP:
if ( $_FILES['img'])
$uploads_dir = 'images'; // will be on same location where php file exist.
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, $uploads_dir.'/'.$name);
HTML:
<img src="images/<?php echo $image;?>" />
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);

// Upload multiple files to the folder
$upload_dir = '/images';
if ( $_FILES['img']){
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["img"]["tmp_name"][$key];
$name = $_FILES["img"]["name"][$key];
move_uploaded_file($tmp_name, "$upload_dir/$name");
}
}
}
//MySQL
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
HTML used in form submission
<input type="file" name="img" multiple>
Showing the images in HTML
$dir = "/images/";
$images = glob($dir."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}

You are assigning a directory that is equivalent to the file name. Try this
<?php
if (!file_exist("your main directory/the file to story")) {
mkdir("your main directory/the file to story", 0777, true);
}
// then you start uploading your once the folder is created
?>
The process here is if the folder directory doesn't exist, the mkdir() function will create that folder. Then that's the time you start on moving the file to the created folder.

Put all of your code in if statement:
if ( $_POST['img']) {
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}

<form action="phpfilename.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit">
$file=$_FILES['file']['name'];
$dest="uploads/$file";
$src=$_FILES['file']['tmp_name'];
move_uploaded_file($src,$dest);
$result=mysql_query("insert into tablename(dbfieldname) values('$dest')");

Related

PHP move_uploaded_file() only moves the last picture to the folder

I have a form though which i want to upload multiple images and store them in my folder, but my program only stores the last selected image.
My form:
<form method="POST" action="server.php" enctype="multipart/form-data">
<input type="file" name="pictures[]" multiple>
<button class="btn btn-success btn-block" name="add">ADD</button>
</form>
My PHP code:
$images = $_FILES['pictures'];
$image_names = $images['name'];
$image_tmpnames = $images['tmp_name'];
foreach($image_names as $image_name){
$foto = 'images/' . $image_name;
foreach($image_tmpnames as $image_tmpname){
move_uploaded_file($image_tmpname,$foto);
}
}
How can I fix this so all of the pictures will be moved to my "images" folder?
maybe try other loop, and set the distination path.
I craft this code you can implement in your solution:
$arquivo = isset($_FILES['img']) ? $_FILES['img'] : FALSE;
for ($controle = 0; $controle < count($arquivo['name']); $controle++){
$destino = $diretorio."/".$arquivo['name'][$controle];
if(move_uploaded_file($arquivo['tmp_name'][$controle], $destino)){
echo "Upload sucess<br>";
}else{
echo "Erro upload";
}
}
Don't use nested loops. You want to process the two arrays in parallel, not as a cross-product.
foreach ($image_names as $i => $image_name) {
$image_tmpname = $image_tmpnames[$i];
$foto = 'images/' . $image_name;
move_uploaded_file($image_tmpname,$foto);
}

PHP file upload wrong file name encoding

Im doing a webpage and have a problem with file upload, that changes the file name umlauts into a weird name.
For example when i upload a file called "töö.docx" and look at the name in the uploaded folder, it shows me this "tƶƶ.docx".
When i call out the name of the file in index.php it shows me the correct name "töö.docx".
But after i go into the upload folder and change the name "tƶƶ.docx" manually into "töö.docx" and than call out the name of the file in index.php, it shows me "t��.docx" which is wrong.
Here is the code for upload in index.php:
<form method="post" enctype="multipart/form-data">
<strong>File upload:</strong>
<small>(max 8 Mb)</small>
<input type="file" name="fileToUpload" required>
<input type="submit" value="Upload" name="submit">
</form>
And here is the upload controller code:
$doc_list = array();
foreach (new DirectoryIterator('uploads/') as $file)
{
if ($file->isDot() || !$file->isFile()) continue;
$doc_list[] = $file->getFilename();
}
$target_dir = "uploads/";
$target_file = $target_dir . basename( isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "");
$file = isset($_FILES["fileToUpload"]) ? $_FILES["fileToUpload"] : "";
$up_this = isset($_FILES["fileToUpload"]["tmp_name"]) ? $_FILES["fileToUpload"]["tmp_name"] : "";
$file_name = isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "";
if (!empty($file)) {
if(isset($_POST["submit"])) {
if (file_exists($file_name)) {
echo "File already exists.";
exit;
} else {
$upload = move_uploaded_file($up_this, $target_file);
if ($upload) {
echo "File ". '"' . basename($file_name). '"' . " has been uploaded";
} else if (!$upload) {
echo "Could not upload file";
exit;
}
}
}
}
I use the variable $doc_list to call out the names of the documents in folder in index.php:
<div>
<?php if (!empty($doc_list)) foreach ($doc_list as $doc_name) { ?>
<tr>
<td><?= $doc_name ?></td>
</tr>
<?php } ?>
</div>
I've set the website charset into utf-8. and i still don't know why it's not displaying the correct file name with umlauts.
Try to add accept-charset="UTF-8" like this:
<form method="post" enctype="multipart/form-data" accept-charset="UTF-8">

PHP get names of multiple uploaded files

Hi im trying to create a script to upload multiple files.
everythings works so far and all files are being uploaded.
My problem now is that i need to grap each file name of the uploaded files, so i can insert them in to a datebase.
Here is my html:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image[]" multiple />
<input type="submit" value="upload" />
And here is the php:
if (!empty($_FILES['image'])) {
$files = $_FILES['image'];
for($x = 0; $x < count($files['name']); $x++) {
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
$size = $files['size'][$x];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
}
Really hope someone can help me with this.
/JL
You have your indexes backwards. $_FILES is an array, with an element for each uploaded file. Each of these elements is an associative array with the info for that file. So count($files['name']) should be count($files), and $files['name'][$x] should be $files[$x]['name'] (and similarly for the other attributes. You can also use a foreach loop:
foreach ($_FILES as $file) {
$name = basename($file['name']);
$tmp_name = $file['tmp_name'];
$size = $file['size'];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
I think the glob() function can help:
<?php
foreach(glob("*.jpg") as $picture)
{
echo $picture.'<br />';
}
?>
demo result:
pic1.jpg
pic2.jpg
pic3.jpg
pic4.jpg
...
be sure to change the file path and extension(s) where necessary.
Thanks for the help, i got it to work by simply creating variables:
$image_1 = (print_r($files['name'][0], true));
$image_2 = (print_r($files['name'][1], true));
$image_3 = (print_r($files['name'][2], true));

Uploading files with 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}.";
}
}
}
?>

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories