Cannot upload img to a folder - php

Im using laravel. And the img wont upload to my public/imgs folder. It keeps saying Sorry, there was an error uploading your file.
// PHP CODE
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if (move_uploaded_file($_FILES["img"]["name"], $target_file)) {
echo "success";
}
else {
echo "Sorry, there was an error uploading your file.";
}
// HTML CODE
<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>

First make sure the upload dir is existing and writable; then file_uploads is on in php.ini

Maybe you should change your original move_uploaded_file function to
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)
See the diff between name and tmp_name

<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>
HTML
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if ($_FILES['img']['error'] == 0) {
if (move_uploaded_file($_FILES['img']['tmp_name'], $target_file)) {
echo 'success';
} else {
echo 'upload failed<br>';
echo '<pre>';
echo 'tmp name: ';
print_r($_FILES['img']['tmp_name']);
echo "\n target: ".$target_file;
echo "\n\n";
print_r($_FILES['img']);
echo '</pre>';
}
} else {
echo 'upload failed: ' . $_FILES['img']['error'];
}
PHP
This code should work and show all data for debugging.

Related

Simple File upload code in PHP

This issue might have been discussed multiple times but I wanted a simple PHP script to upload a file, without any separate action file and without any checks. Below is my written code:-
<html>
<head>
<title>PHP Test</title>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="upload file" name="submit">
</form>
</head>
<body>
<?php echo '<p>FILE UPLOAD</p><br>';
$tgt_dir = "uploads/";
$tgt_file = $tgt_dir.basename($_FILES['fileToUpload']['name']);
echo "<br>TARGET FILE= ".$tgt_file;
//$filename = $_FILES['fileToUpload']['name'];
echo "<br>FILE NAME FROM VARIABLE:- ".$_FILES["fileToUpload"]["name"];
if(isset($_POST['submit']))
{
if(file_exists("uploads/".$_FILES["fileToUpload"]["name"]))
{ echo "<br>file exists, try with another name"; }
else {
echo "<br>STARTING UPLOAD PROCESS<br>";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $tgt_file))
{ echo "<br>File UPLOADED:- ".$tgt_file; }
else { echo "<br>ERROR WHILE UPLOADING FILE<br>"; }
}
}
?>
</body>
</html>
I saved it in /var/www/html/phps/ location. But everytime I try to upload the file, I get ERROR WHILE UPLOADING FILE error. What am I doing wrong here. P.S. I have no previous experience of PHP, I just started with bits & pieces from internet.
Thanks
kriss
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ".basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} 
else {
echo "Sorry, there was an error uploading your file.";
}
?>
I hope that this thing will work and this is what you are in need of.
<?php
$name = $_POST['name'];
$image = $_FILES['fileToUpload']['name'];
$tempname = $_FILES['fileToUpload']['tmp_name'];
move_uploaded_file($tempname, "foldername/$image");?>

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">

Multiple files not uploading, not moving file in php

Im trying to upload multiple files but my code is bypassing the "move_uploaded_file" code. What is missing?
foreach ($_FILES['file']['name'] as $file) {
$target_dir = "uploads/";
$target_file = $target_dir . $file;
if (move_uploaded_file($file, $target_file)) {
echo "The file ".$_FILES["file"]["name"]. " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
move_uploaded_file needs to get the temporary file name: $_FILES['file']['tmp_name']
foreach ($_FILES as $file) {
$target_dir = "./";
$target_file = $target_dir . $file['name'];
if (move_uploaded_file($file['tmp_name'], $target_file)) {
echo "The file " . $file["name"] . " has been uploaded.<br />";
} else {
echo "Error uploading the file " . $file["name"] . ".<br />";
}
}
Small HTML snippet for the upload form:
<form action="./testpage.php" method="post" enctype="multipart/form-data">
<input name="file1" type="file" /><br />
<input name="file2" type="file" /><br />
<input type="submit" value="Upload!" />
</form>
Try this:
for($i=0; $i < count($_FILES['file']['tmp_name']);$i++)
{
if(!is_uploaded_($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No uploaded';
}
else
{
if(#copy($_FILES['file']['tmp_name'][$i],$target.'/'.$_FILES['file']['name'][$i]))
{
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
html:
<form enctype="multipart/form-data" action="#" method="post">
<input id="uploadFile" name="file[]" type="file" />
<input id="uploadFile" name="file[]" type="file" />
<input type="submit" value="Upload" name="uploadt" />
</form>

PHP image upload function, save in a dir and then return save image url

I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.
HTML:
<input name="photo" type="file" />
PHP
save_string_to_database( upload_img($_POST['photo']));
I have not much idea of PHP, I got a code from SO, but it did not do anything. Kindly help me to fix this code, or give a simple code to perform an upload:
function upload_img($img){
if ((($_FILES[$img]["type"] == "image/gif")
|| ($_FILES[$img]["type"] == "image/jpeg")
|| ($_FILES[$img]["type"] == "image/pjpeg")
|| ($_FILES[$img]["type"] == "image/jpg")
|| ($_FILES[$img]["type"] == "image/png"))
&& ($_FILES[$img]["size"] < 20000)
&& (strlen($_FILES[$img]["name"]) < 51)){
if ($_FILES[$img]["error"] > 0){
echo "Return Code: " . $_FILES[$img]["error"];
}
else{
// echo "Upload: " . $_FILES["image"]["name"] . "<br />";
// echo "Type: " . $_FILES["image"]["type"] . "<br />";
// echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
// echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
echo $_FILES[$img]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/" . $_FILES[$img]["name"]);
return THEME_DIR."/images/" . $_FILES[$img]["name"];
}
}
}
}
Here's a simple one.
HTML form to upload image
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Your PHP file that does the Upload
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Source
First you need a multipart/form-data form for uploading. This is a must :)
<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>
The PHP part is fairly simple:
This would result your file stored in "upload/{filename}"
The main part you want to consider is how to get the filename and back to your write_string_to_database procedure, you could do a simple script after the upload page like
save_string_to_database("upload/" . $_FILES["file"]["name"]);
would do the trick.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
for file upload try this
<?php if(isset($_POST['submit']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = 'images/';
$location = $path . $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $location);
} ?>
<form name="form1" id="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" name="submit">
</form>
This my function, variable $ten_anh is name of file image in html.
function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
if(isset($_FILES[$ten_anh])){
$errors= array();
$file_name = $_FILES[$ten_anh]['name'];
$file_size =$_FILES[$ten_anh]['size'];
$file_tmp =$_FILES[$ten_anh]['tmp_name'];
$file_type=$_FILES[$ten_anh]['type'];
$file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
}
if($file_size > 2097152){
$errors[]='Kích cỡ file nên là 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../images/".$file_name);
echo "Thành công!!!";
}
else{
print_r($errors);
}
}
}
Example:
- html code:
<input type="file" id="avatar" name="avatar"accept="image/png, image/jpeg" required/>
call function php: upload_anh('avatar');
<form method='post' action='' enctype='multipart/form-data'>
Name : <input type="text" name="name" required=""/><br><br>
Code : <input type="text" name="code" required=""/><br><br>
Price : <input type="text" name="price" required=""/><br><br>
Image : <input type="file" name="image" required=""/><br><br>
<button type='submit' class='buy' name="submit">Add Now</button>
</form>
<!--insert data -->
<?php
session_start();
include('db.php');
if(isset($_POST["submit"]));
{
/*echo "<pre>";
print_r($_POST);
print_r($_FILES);*/
$name = $_POST["name"];
$code = $_POST["code"];
$price = $_POST["price"];
$image = $_FILES["image"]["name"];
/* folder image save */
// $target_dir = "/var/www/html/shivam/new/upload/";
// $target_file = $target_dir.basename($_FILES["image"]["name"]);
// /*echo "1121".$target_file;*/
// $name = basename($_FILES["image"]["name"]);
// mysqli_query($con,$qry);
// /* move file */
// move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$name);
/* move_uploaded_file($tmp_name, "$target_dir/$name");*/
/* end */
$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
echo '44'.$uploadfile;
echo "<p>";
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';enter code here
print_r($_FILES);
print "</pre>";
}
?>

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories