PHP File Upload

Upload a file using PHP

Below is one way to upload files, there are many other ways.

As @nordenheim said, $HTTP_POST_FILES has been deprecated since PHP 4.1.0, thus not advisable to use so.

PHP Code (upload.php)

<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowedTypes = ['jpg', 'png'];

if (isset($_POST["submit"])) {
// check type
if (!in_array($imageFileType, $allowedTypes)) {
$msg = "Type is not allowed";
} // Check if file already exists
elseif (file_exists($target_file)) {
$msg = "Sorry, file already exists.";
} // Check file size
elseif ($_FILES["fileToUpload"]["size"] > 5000000) {
$msg = "Sorry, your file is too large.";
} elseif (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
}
}

?>

HTML Code to start function

<form action="upload.php" method="post" id="myForm" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
</form>

Hope this helps.

HTML PHP File Upload :: Uploaded File Doesn't Appear On Server

This should be the HTML for your index page. You do not need to use JS to handle file uploads:

<!DOCTYPE html>
<html>
<body>
<h2>DIY HTML5 File Uploader</h2>
<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="uploadFile">
<hr>
<input type="submit">
</form>
</body>
</html>

And this should be the PHP code for uploader.php:

<?php
$target_dir = "uploads/";
$filename = basename($_FILES["uploadFile"]["name"]);
$target_file = $target_dir . $filename;
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir . $filename)) {
echo "The file ". $filename . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>

This code saves your uploaded file in the uploads folder.
If you have any answers or need me to explain the code, please ask.

Files not uploading despite not reaching the file size limit

The error you're getting is related to POST data in general (which uploads go through), and is not specific to file uploads.

The PHP setting you're looking for is post-max-size. You should be able to fix your issue by increasing its value.

Relevant part from the docs:

Sets max size of post data allowed. This setting also affects file
upload. To upload large files, this value must be larger than
upload_max_filesize.

Using PHP for file-upload in Wordpress

pathinfo() expects a path not a URL.

$target_dir should be a path, eg: /home3/dy/public_html/wp-content/uploads. Check $_SERVER['DOCUMENT_ROOT'] if you are not sure.

$target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"]);

Then, you've got a path where you want the files to be uploaded to.
Now you need to run:

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

File not uploading PHP

Make sure that in your form.. you put the enctype.

eg: <form method="post" enctype="multipart/form-data" action="index.php"></form>;

To check if files are successfully updated upon submitting the form. use print_r to see results.
print_r($_FILES);

PHP file upload fails when changing HTML input name

This line has the problem move_user_file($_FILES['user_file']['tmp_name'], $path).

php's bool move_uploaded_file ( string $filename , string $destination ) moves the uploaded files to a desired location. It is a built in function in php's API.

Your code should be changed to

move_uploaded_file($_FILES['user_file']['tmp_name'], $path)

in order to get it to work.

Your misunderstanding I think has come from your naming. Previously your field name is uploaded_file and the function name is move_uploaded_file(). So you must have thought that, when your field name is user_file, you should call move_user_file() in php. That's kinda creative thinking.. :D

Is the "uploaded_file" a fix or hard-coded kind of value? Well, you need to read the link given.

File Upload form using php

Some problems with your code...

onsubmit="event.preventDefault(); ...

...prevents the form from submitting the file provided by <input type="file" ... to the form action target: upload.php conventionally, such as clicking the submit button.

~

echo "..." . basename( $_FILES['uploadedFile']['name']) . "...";
echo "<script>document.write(readfile(\"".$target_path."\"));</script>";
$stringPath = $target_path; //PASSING NAME PARAM
printf($stringPath);

...your upload.php file simply writes a string that, if properly called for, gets sent from the server to the browser by way of HTTP.

NO Javascript is executed at this point.

If the browser calls upload.php by loading the page, you leave the current page and only load that string in the browser. If the browser calls upload.php by way of XHR, or Fetch, the page remains but you need to use Javascript to capture the STRING and do something with it.

~

echo "<script>document.write(readfile(\"".$target_path."\"));</script>";

In the PHP file, on the server, you are writing a string of Javascript code, which is sent as text to the browser to be executed there later. The browsers gets something like:

<script>document.write(readfile("uploads/filename.png"));</script>

It's okay to use PHP to send a Javascript string to the browser—however the problem is you're providing a file path on the server. Once the Javascript string gets to the browser and evaluated it does not have access to the server file and directory structure, such as: uploads/filename.png

Since you're attempting to execute a Javascript function named readfile(...) it appears you're trying to use Javascript FileReader to access the file uploaded to the server, but FileReader only handles files on the client, and provided through a Javascript File or Blob object, or an input type="file" element, or a drag and drop process.


Keep in mind that PHP executes on the server, and only text gets sent to the browser. The browser then receives the text from the server and processes and renders it.

The PHP context on the server cannot execute Javascript, and the browser context (Javascript/DOM events) on the client cannot execute PHP.

You only have a text channel between the two. And the text channel is only invoked by a page load, or without a page load by using XHR, or Fetch. If you use XHR or Fetch you then need to use Javascript to handle the text received back from the server.


To take a photo, upload it to the server, and display the photo on the page, without reloading the page:

camera.html

<input type="file" id="campic" accept="image/*" capture="camera">

<script>

var campic = document.querySelector("#campic");

campic.onchange = function () {
var file = campic.files[0];
upload(file);
displayAsImage(file);
};

function upload (file) {
var form = new FormData(),
xhr = new XMLHttpRequest();

form.append('image', file);
xhr.open('post', 'upload.php', true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
xhr.send(form);
}

function displayAsImage (file) {
var imgURL = URL.createObjectURL(file),
img = document.createElement('img');

img.onload = function () {
URL.revokeObjectURL(imgURL);
};

img.src = imgURL;
document.body.appendChild(img);
}
</script>

upload.php

<?php 

$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedFile']['name']);

if ( move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $target_path) ) {
echo "File uploaded.";
}
else {
echo "Error uploading the file.";
}

?>

Get more information on this approach here: How to use HTML5 to capture a camera image .

PHP file upload - rename file

Change the first lines in the the code like this:

<?php
$target_dir = "uploads/";
$imageFileType = strtolower(pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . trim($_POST['your_name']) . '_invoice.' . $imageFileType;
$uploadOk = 1;

But you should also have to have <input type="text" name="your_name"> in your form because according your code and the article, there's no text-typed input.



Related Topics



Leave a reply



Submit