Files being posted after refreshing page [duplicate] - php

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
Closed 6 years ago.
edit: marked as duplicate, but the solutions in post didn't help in my case when I tried. Don't want to do it with ajax right now, so I just used window.location to redirect. I lose the names of uploaded files, but I'd rather deal with passing those through somehow.
I have a form to upload files, I post to the same page, after submit the file is uploaded but if I refresh the files are reuploaded. I've tried to set $_POST and $_FILES to a blank array at the end of the upload script, but still keeps the post data every time .. Also tried adding a header, but it says they are already sent, when I try to use ob_start at the beginning of script, no change.
my table and form looks like this
<table name="doctor_file_table" width="100%">
<tr>
<td><b>Name</b></td>
<td><b>Type</b></td>
<td><b>Size (bytes)</b></td>
<td><b>Created</b></td>
<td><a href='path_to_file' download =''>Download</a></td>
<td><button id ='id#' onClick='deleteFile(this)' type='button'>Delete</button></td>
</tr>
<form action="" enctype="multipart/form-data" method="post">
<div>
<label for="upload">Add Attachments:</label>
<input id="upload" name="upload[]" type="file" multiple="multiple"/>
</div>
<p><input type="submit" name="submit" value="Submit"></p>
</form>'
And here is the upload script:
if(isset($_POST['submit']) && $_POST['uploaded'] == 1){
echo $_POST['uploaded'];
if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if($tmpFilePath != ""){
//save the filename
$shortname = $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = "/var/www/html/doctor_files/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
$fullname = substr($filePath,27);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
$sql = 'insert into '.TABLE_DOCTOR_FILES.'(shortname,fullname,filepath,type,size,doctor_id) VALUES("'.$shortname.'", "'.$fullname.'", "'.$filePath.'", "'.$_FILES["upload"]["type"][$i].'",'.$_FILES["upload"]["size"][$i].',"'.$doctor_id.'")';
database_void_query($sql);
//use $shortname for the filename
//use $filePath for the relative url to the file
}
}
}
}
//show success message
echo "<h1>Uploaded:</h1>";
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
}

Request Header will store your data. So if you refresh, data will sent back again.
You have 3 solutions:
split your code into 2 different page
use ajax (of course this needs to split the page like no 1)
try to redirect into another page, then redirect again to your form page.
To use the third way, you can try this:
index.php
<html>
<head><title>asdas</title></head>
<body><!--i give you header to know this is will give error header or not-->
<?php
if(isset($_POST['submit']) && $_POST['uploaded'] == 1){
echo $_POST['uploaded'];
if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if($tmpFilePath != ""){
//save the filename
$shortname = $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = "/var/www/html/doctor_files/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
$fullname = substr($filePath,27);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
$sql = 'insert into '.TABLE_DOCTOR_FILES.'(shortname,fullname,filepath,type,size,doctor_id) VALUES("'.$shortname.'", "'.$fullname.'", "'.$filePath.'", "'.$_FILES["upload"]["type"][$i].'",'.$_FILES["upload"]["size"][$i].',"'.$doctor_id.'")';
database_void_query($sql);
//use $shortname for the filename
//use $filePath for the relative url to the file
}
}
}
}
//show success message
echo "<h1>Uploaded:</h1>";
header('Location: http://localhost/stackoverflow/success.php');
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
?>
<table name="doctor_file_table" width="100%">
<tr>
<td><b>Name</b></td>
<td><b>Type</b></td>
<td><b>Size (bytes)</b></td>
<td><b>Created</b></td>
<td><a href='path_to_file' download =''>Download</a></td>
<td><button id ='id#' onClick='deleteFile(this)' type='button'>Delete</button></td>
</tr>
<form action="" enctype="multipart/form-data" method="post">
<div>
<label for="upload">Add Attachments:</label>
<input id="upload" name="upload[]" type="file" multiple="multiple"/>
</div>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
success.php
<html><head><title>redirect</title></head>
<body><!--i give you header to know this is will give error header or not-->
<?php
echo "<p>Your upload is success</p>";
echo "<p>You will redirect back</p>";
echo "<p>or press this to redirect directly</p>";
?>
<script>
setTimeout(function () {
window.location.href = "index.php";
}, 3000);
</script>
</body></html>

Related

How can I add a delete function to this script to delete file on server

i have a script which loads all files within a specific directory folder into a viewable table. I have also been able to successfully get the date uploaded element integrated and am using the $iterator function as seen in the code below
UPDATE
edited value to checkbox input but still not working
Removed unnecessary code snippets from past attempts
Updated code to most recent and added full script for better understanding including CD001's suggestions
// Begin Adding Uploader Page Content
function pdfupload_admin_page(){
?>
<style>
<?php include '../wp-content/plugins/PDF-Uploader/support-files/stylesheet.css'; ?>
</style>
<div class="wrap">
<div id="contact">
<div style="text-align:center;">
<h1>Secure PDF File Upload</h1>
<p>Adding a watermark to your PDF files is as easy as uploading the file using the form below.<br>
Upon successful submission of your PDF file you will receive the uploaded PDF files URL which you can then use when linking to the PDF within any page or post you desire.</p>
<p>The PDF file when linked to using the URL provided will automatically acquire a watermark when loaded within the browser of the specific logged in user as well as the current date and time.</p>
<form action="" method="post" enctype="multipart/form-data">
<h3>Select PDF File To Upload:</h3><br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload PDF File" name="submitUpload">
</form>
<?php
$target_dir = "../wp-content/plugins/PDF-Uploader/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submitUpload"])) {
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["fileToUpload"]["size"] > 10000000) {
// echo "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($FileType != "pdf") {
echo "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "File uploaded successfully use the following URL when linking to your PDF <br> https://website.com/wp-content/plugins/PDF-Uploader/watermarked.php?filename=" . basename( $_FILES["fileToUpload"]["name"]). "";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
// Check if file already exists
/**
* FILE DELETION HANDLER
*/
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
</div>
<?php
// if ($handle = opendir('../wp-content/plugins/PDF-Uploader/')) {
// while (false !== ($file = readdir($handle)))
// {
// if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
// {
// $thelist .= '<td><input type="checkbox" name="file[]" value="https://website.com/wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
// }
// }
// closedir($handle);
//}
?>
<form id="deletionForm" method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
// $iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/pdf-watermarker/');
foreach($iterator as $file){
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="wp-content/plugins/PDF-Uploader/<?php echo $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?php echo $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><?php echo $cTime->format('Y-m-d h:i:s'); ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</div>
<?php
}
// End Adding Secure PDF Upload Page Content
So all in a nutshell, I need to figure out why the delete functionis not working and add a sort order to the script to product the results in alphabetical order.
Any code samples would be greatly appreciated.
File handling require a valid enctype in <form>, being enctype="multipart/form-data" as per the manual:
https://secure.php.net/manual/en/features.file-upload.post-method.php
An example from the manual:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
You need to change all references of $_POST['file'] to $_FILES['file']['name'] / $_FILES['file']['tmp_name'] respectively.
Handling multiple files is also included in the manual, and here is an example pulled from it:
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Use PHP's error reporting to help you debug:
https://php.net/manual/en/function.error-reporting.php
However, when dealing with checkboxes, don't use empty(), use isset():
if(isset($_POST['file'])) { // check if the checkbox was checked.
It's a bit unclear if you want to upload files. If so, then you need to change the <input type="checkbox" to an file input type <input type="file"
Edit:
This part of your code should error out, since there needs to be an empty variable declaration using $thelist = "";
I.e.:
<?php
if ($handle = opendir('../wp-content/plugins/PDF-Uploader/.')) {
$thelist = "";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$thelist .= '<td><input type="checkbox" name="file[]" value="../wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
}
}
closedir($handle);
}
?>
Solution (explanation follows)
<?php
// global iterator
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
<form method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
foreach($iterator as $file) {
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="<?= $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?= $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><input type="text" name="date[]" value="<?= $cTime->format('Y-m-d h:i:s'); ?>"></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</body>
</html>
Explanation
Since the FilesystemIterator holds the path to the directory for your PDF repository I've defined that as a global variable at the top of the script. It's then referenced wherever required so should you ever need to change the filepath, you just change it in the $iterator.
For instance, it's used in the loop and passed to the delete_file function. The form itself is only posting the filenames rather than the full paths.
Otherwise you weren't really a long way off.
Couple of thoughts
The FilesystemIterator class has methods for detecting the extension and whether the file is . or .. so you can replace:
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
With:
if(!$file->isDot() && $file->getExtension() == 'pdf')
Which is a little neater.
There is also a security concern with having a directory that's both web server readable and writeable - if there's a vulnerability in your application an unauthorised user could upload and execute anything (open it in the browser); a malicious PHP script for instance.
You can mitigate this through your Apache configuration - one common thing to do is to disable PHP via an .htaccess file:
php_flag engine off

Upload an image and newsTitle related to image PHP

I need to upload an image and add it to my slideshow and give it related newsTitle in front of my uploaded picture. I'm a new in PHP and trying to learn how to send data from my admin.php file to my index.php file and add more image with a <form> in html.
My problem is that I can upload images but can't get my newsTitle printed to my home page which is index.php.
This is my PHP code in index.php:
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
$newsImage = $_POST['newsImage'];
echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
echo'<h2'.'>'.htmlspecialchars($newsImage["newsImage"]).'</h2>';
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
This is my html code in admin.php:
<form action="index.php" method="post" enctype="multipart/form-data">
<br><br>
<tr>
<td> NewsTitle: </td>
<td> <input type="text" name="newsTitle" placeholder="newsTitle"> </td>
</tr>
<br><br>
Select image to upload:
<input type="file" name="image">
<br><br>
<br><br>
NewsText: <textarea name="newsImage" placeholder="newsImage" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" value="Send" name="send_object">
</form>
I'm trying to do this without connection to the database, just to my apache server. I have tried with another global variable $_REQUEST but it didn't work. What I know it can use for $_POST , $_GET and $_COOKIES
Firstly, if you are trying to make each news with a text you collect it separately with the $_POST , but note once you refresh the page the parameters are gone cause the form processes everything so there is no space for output in text but if you use the get the parameters remain because you are not storing both the post method and get method in the database. Try this
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
<?php
$newsImage = $_POST['newsImage'];
//this would give a parse error echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
try
echo <?php echo $newsimage; ?>
?>

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>

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

Prevent form re-submit after refresh [duplicate]

This question already has answers here:
Does page reload ever cause post?
(3 answers)
Closed 9 years ago.
I've been reading some on other question regarding this that i should use the header( 'Locaction: xxx.php' ); but i can't figure out how to implement it to my code. I'm sorry for bad explaination on this. Any help or guiding i would be most greatful! This is the index.php below:
<body>
<div id="container">
<div id="upload">
<div id="logo"><img src="images/logo.png"></div>
<form enctype="multipart/form-data" method="post" action="uploader.php">
<p class="uploadtxt">Choose your file below:</p>
<input type="file" name="image" class="button" />
<input type="submit" value="Upload It!" class="button" />
</form>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
And this is the uploader.php code below:
<?php
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$url = "http://localhost/";
// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 10000000) { // if file is larger than we want to allow
echo "ERROR: Your file was larger than 10000000kB in file size.";
unlink($fileTmpLoc);
exit();
} else if (!preg_match("/.(gif|jpg|jpeg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png.";
unlink($fileTmpLoc);
exit();
}
//-- GENERATE A RANDOM NAME --//
$newfilename = rand(0, 999);
$newerfilename = $newfilename .'-'. $fileName;
//-- MAKE UPLOADS FOLDER IN YEAR AND MONTHLY --//
$path = "uploads/";
$year_folder = $path . date("Y");
$month_folder = $year_folder . '/' . date("m");
!file_exists($year_folder) && mkdir($year_folder , 0777);
!file_exists($month_folder) && mkdir($month_folder, 0777);
$path = $month_folder . '/';
move_uploaded_file($_FILES["image"]["tmp_name"], $path . $newerfilename);
?>
<html>
<head>
<title>Localhost - Upload Completed!</title>
<?php include_once 'header.php'; ?>
<body>
<div id="container">
<div id="upload">
<div id="logo"><img src="images/logo.png"></div>
<p class="filenametxt"><?php echo "The image is now uploaded!"; ?></p>
<p class="uploadtxt">Get the link below:</p>
<pre><?php echo $url . $path . $newerfilename; ?></pre>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
Try this:
<input type="hidden" name="key" value="<?php echo (isset($_POST['key']) ? $_POST['key'] : rand(1,150)); ?>" />
<?php if (isset($_POST['key']) { $_SESSION['key'] = $_POST['key']); } ?>
And in your submission PHP:
<?php if (isset($_SESSION['key'])) { if ($_POST['key']==$_SESSION['key']){ echo "You may not resubmit a form!"; } } ?>

Categories