What's the Best Way to Create a Single-File Upload Form Using PHP

What's the best way to create a single-file upload form using PHP?

File Upload Tutorial

HTML

<form enctype="multipart/form-data" action="action.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="userfile" type="file" />
<input type="submit" value="Go" />
</form>
  • action.php is the name of a PHP file that will process the upload (shown below)
  • MAX_FILE_SIZE must appear immediately before the input with type file. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.
  • You can change the name of the input with type file, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).

PHP

<?php
$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>

The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.

Printing the value of $_FILES can give a hint as to what's going on. For example:


Array
(
[userfile] => Array
(
[name] => Filename.ext
[type] =>
[tmp_name] =>
[error] => 2
[size] => 0
)
)

This structure gives some information as to the file's name, MIME type, size and error code.

Error Codes

0 Indicates that there was no errors and file has been uploaded successfully

1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need

2 Indicates that the maximum file size defined manually, within an on page script has been exceeded

3 Indicates that file has only been uploaded partially

4 Indicates that the file hasn't been specified (empty file field)

5 Not defined yet

6 Indicates that there´s no temporary folder

7 Indicates that the file cannot be written to the disk

php.ini Configuration

When running this setup with larger files you may receive errors. Check your php.ini file for these keys:

max_execution_time = 30
upload_max_filesize = 2M

Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.

The maximum memory permitted value (set via memory_limit) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via upload_tmp_dir.

Checking file mimetypes

You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that a user could potentially upload PHP code to the server and then run it.

You can use the very useful fileinfo extension (that supersedes the older mime_content_type function) to validate mime-types.

// FILEINFO_MIME set to return MIME types, will return string of info otherwise
$fileinfo = new finfo(FILEINFO_MIME);
$file = $fileinfo->file($_FILE['filename']);

$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue

More Information

You can read more on handling file uploads at the PHP.net manual.

For PHP 5.3+

//For those who are using PHP 5.3, the code varies.
$fileinfo = new finfo(FILEINFO_MIME_TYPE);
$file = $fileinfo->file($_FILE['filename']['tmp_name']);
$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue

More Information

You can read more on FILEINFO_MIME_TYPE at the PHP.net documentation.

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 .

how to make a File upload form with one input in PHP?

ok let me add an example asumming you are expecting the same here is something that you might be looking:

HTML:

<form method="post" action="abc.php" name="imageform" id="imageform">
Choose File :<input type="file" name="file" id='fileupload'>
</form>

js:

$(document).ready(function(){
$('#fileupload').on('change',function(){
$('#imageform').submit();
});
});

How to upload any type of file to the server using PHP 5?

=> Try this code for upload any type of file ..

//HTML PAGE

<li class="text">File Upload </li>
<li><input type="file" name="file" value="" class="input" ></li>

try this to all file upload..
//PHP PAGE

if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"upload/".$name);// set your folder name to store all file.

Multiple Image Upload PHP form with one input

$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);

if(in_array($ext,$extension)) {
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else {
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else {
array_push($error,"$file_name, ");
}
}

and you must check your HTML code

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>

Nice link on:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

How do I create a single file from my HTML form and PHP script so that it is accessed from a pop-up Modal?

If I understood your question this shall do the thing, if not then please specify what I got wrong so I can edit my answer

// Get the modalvar modal = document.getElementById("myModal");
// Get the button that opens the modalvar btn = document.getElementById("myBtn");
// Get the <span> element that closes the modalvar span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal btn.onclick = function() { modal.style.display = "block";}
// When the user clicks on <span> (x), close the modalspan.onclick = function() { modal.style.display = "none";}
// When the user clicks anywhere outside of the modal, close itwindow.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; }}
/* The Modal (background) */
.modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; /* Sit on top */ padding-top: 100px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scroll if needed */ background-color: rgb(0, 0, 0); /* Fallback color */ background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */}

/* Modal Content */
.modal-content { background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 80%;}

/* The Close Button */
.close { color: #aaaaaa; float: right; font-size: 28px; font-weight: bold;}
.close:hover,.close:focus { color: #000; text-decoration: none; cursor: pointer;}
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal --><button id="myBtn">Open Modal</button>
<!-- The Modal --><div id="myModal" class="modal">
<!-- Modal content --> <div class="modal-content"> <span class="close">×</span> <form action="comb-insert.php" method="post" enctype="multipart/form-data"> <p> <label for="file">Choose file:</label> <input type="file" name="file" id="file"> </p>
<p> <label for="category">category:</label> <input type="text" name="category" id="category"> </p>
<p> <label for="title">title:</label> <input type="text" name="title" id="title"> </p>
<p> <label for="embedcode">embedcode:</label> <input type="text" name="embedcode" id="embedcode"> </p>
<p> <label for="video_platform">video_platform:</label> <input type="text" name="video_platform" id="video_platform"> </p>

<input type="submit" value="Submit"> </form> </div>
</div>

simple file upload script

You lack enctype="multipart/form-data" in your <form> element.



Related Topics



Leave a reply



Submit