Prevent form re-submit after refresh [duplicate] - php

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!"; } } ?>

Related

Renaming a form-selected file before submitting upload

I am attempting to create a form which allows the renaming of a selected file within the form, before submitting the upload.
I created the form with a 'text' field named "new_fileName" in addition to the file-picker.
On the upload.php side, I changed the variable to $newname, and tried a few ways to use that to change the name of the uploaded file. Including using it to replace the ['name'] part of the $filename variable. But so far, no success with anything.
FORM
<!DOCTYPE html>
<html>
<head>
<title> Rename and Upload Form </title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file" id="file" />
<br><br>
<input type="text" name="new_fileName" placeholder="Rename File"/>
<br><br>
<input type="submit" value="Rename and Upload" />
</form>
</body>
</html>
upload.php
<?php
$newname = $_POST['new_fileName'];
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
if( move_uploaded_file($_FILES['file']['tmp_name'], $location)){
echo 'File uploaded successfully';
}else{
echo 'Error uploading file';
}
?>
After a bit of tinkering with the 'upload.php' page, this is what ended up working to change the name of the file before submitting the upload form.
This code also adds the file-type extension to the new file name.
(New) upload.php
<?php
$filename = $_POST['new_fileName'];
$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name)));
if($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_FILES['file']['error'] > 0) { echo 'Error: ' . $_FILES['file']
['error']; }
if (file_exists('upload/' . $_FILES['file']['name'])) { unlink
('upload/' . $_FILES['file']['name']); }
move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_POST =
$filename . "." . $ext);
echo 'File uploaded successfully' ; }
else { echo 'Error uploading file'; }
?>

how upload file from folder in php then deleted it after uploaded

I am trying to upload a file from one folder on my Pc to another folder on the XAMPP server. Then after uploaded the file must be deleted from the source.
I have written this code which uploads the file to the folder on the XAMPP server but does not remove it from the source and it shows the error "Unlink resource temporarily unavailable".
my code is :
<?php
if (isset($_POST['save'])) {
// destination of the file on the server
$destination = 'uploads/' . $filename;
$file = $_FILES['myfile']['tmp_name'];
$size = $_FILES['myfile']['size'];
$filepath = 'uploads/'.$filename ;
//-------------------------------
elseif (file_exists($filepath)) {
echo '<script type="text/javascript">';
echo ' alert(" Failed, Sanad already exist")';
echo '</script>';
} else {
if (move_uploaded_file($file, $destination)) {
$filename = $_FILES['myfile']['name'];
//$filename = $_POST['myfile'];
//$file_Path = 'uploads.$filename;
$file_Path = 'D:/pic/'.$filename;
echo $file_Path ;
// check if the file exist
if(file_exists($file_Path))
{ unset($filename);
unlink($file_Path);
echo 'File Deleted';
}else{
echo 'File Not Exist';
}
}
}
}
?>
<html>
<head>
</head>
<body >
<form action="tt.php" method="post" enctype="multipart/form-data" class= "form" >
<h3>Upload File</h3>
<input type="file" name="myfile" > <br>
<button type="submit" class ="add "name="save" value="save" class = "button"> save</button>
</form>
</body>
</html>

PHP File Upload Error - Undefined Index , Encytype used, File Permissions are right

I've been trying to solve why my file is not getting uploaded. I thought it was my school's permission causing error so I am running it over wampserver but I am still getting an undefined error and 'file was not uploaded'. I tried several echos, the file name is right, the directory is right and being create but the file will not upload to the directory. When I put it manually in the directory it uploads fine to my database so I have no idea what's wrong.
Outside of my header/body
<?php
session_start(); // Starting Session
require_once('config.php');
$link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die ('Your DB connection is misconfigured. Enter the correct values and try again.');
//$query = mysqli_query(
?>
And here's the file upload:
<?php include 'navigation.php';?>
<h1> Welcome, <?php
echo $_SESSION['login_user']; ?> !</h1>
<!-- upload file script-->
<?php
if(!file_exists ("uploads/".$_SESSION['login_user'])){ //making the user directory
mkdir("uploads/".$_SESSION['login_user'], 0777, true);
}
$img_target_dir = "uploads/".$_SESSION['login_user']; //puts stuff in uploads
$target_file2 = $img_target_dir. basename($_FILES["imgfile"]["name"]); //img file
echo $_FILES["imgfile"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file2,PATHINFO_EXTENSION);
// Allow certain file formats for images (png)
// Check if image file is a actual image or fake image
if(isset($_POST['submit'])) {
if($imageFileType == "png") {
$check = getimagesize($_FILES["imgfile"]["tmp_name"]);
echo $img_target_dir . "/" . $_FILES["imgfile"]["name"];
if($check != false) {
if (move_uploaded_file($_FILES["imgfile"]["name"], $img_target_dir . "/" . $_FILES["imgfile"]["name"])) {
//chmod("uploads/img/lab2_upload.png",0777);
//echo "Image file size: ";
//echo filesize("uploads/img/lab2_upload.png") . "<br>";
//echo '<img src= "uploads/img/lab2_upload.png" height="300" width="300">';
}
else {
echo "file was not uploaded";
}
}
else {
echo "error uploading image";
}
}
else {
echo "File not png<br>";
}
}
?>
<!-- FORM FOR PHP UPLOAD -->
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<!-- Upload image-->
<h2> Image Upload </h2>
<h4> Ensure that the file upload is a PNG file!</h4>
<form action="profile.php" method="post" enctype="multipart/form-data">
<div><h2>Upload a PNG file: </h2>
<input class="btn btn-default btn-xl wow tada" id="imgfile" type="file" name="imgfile" value="imgfile">
<br>
<input class="btn btn-default btn-xl wow tada" id="Upload" type="submit" name="submit" value="Upload">
</div>
</form>
</div>
</div>
</div>
And a screenie: http://puu.sh/o7x1c/e3ee43d124.jpg

How to upload photo and display in folder and page using php? [duplicate]

This question already has answers here:
PHP - Upload picture and display on page
(2 answers)
Closed 7 years ago.
I'm trying to make where you can upload a photo and show in folder. Then when you go to the page it will show you All photo's that were uploaded. I'm using PHP and HTML for this project.
Hopefully You understand my project by now.
This is my php code
<?php
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}
else{
print_r($errors);
}
}
?>
<html>
<link rel="stylesheet" type="text/css" href="css/main1.css"/>
<body>
<?php include("includes/navigation.php"); ?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
To show on my page:
PHP:
<?php
$dirname = "uploads/";
$images = glob($dirname."*.*");
?>
<?php
foreach($images as $image) {
echo '<img src="'.$image.'" /><br /><br />';
}
?>
Help will be appreciated Thanks,
<?php
$dir = './';
$name = $_FILES['image']['name'];
$fullpath = $dir.$name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$tmpFilename = pathinfo($name, PATHINFO_FILENAME);
$i = 1;
while(file_exists($fullpath)){
$_FILES['image']['name'] = $tmpFilename.'('.$i.')'.$extension;
$fullpath = $dir.$_FILES['image']['name'];
$i++;
}
move_uploaded_file($_FILES('image']['tmp_name'], $fullpath);
?>
In your form action attribute put:
upload_photo.php

How to Display image Using Session in PHP

i am able to display image on screen but i want to display the image using session.Please help me.
$_SESSION['user_name6'] = $_FILES["file"]["name"];
if(isset($_SESSION['user_name6']))
{
echo "<img src=<?php echo $_SESSION[user_name6]; ?> width=300 height=400
alt=Image path Invalid name=image />";
}
else
{
print "no pic here";
}
I do not know what you will actually do but this is the approach that best fits
when you put a file type in your form, you need to use the global variable Files
form.html
<form action="process.php" method="post" enctype="multipart/form-data">
<label for="picture">Picture:</label>
<input type="file" name="picture" id="picture"><br>
<input type="submit" name="submit" value="Upload">
</form>
process.php
<?php
session_start();
//make sure you have created the **upload** directory
$filename = $_FILES["picture"]["tmp_name"];
$destination = "upload/" . $_FILES["picture"]["name"];
move_uploaded_file($filename, $destination); //save uploaded picture in your directory
$_SESSION['user_name6'] = $destination;
header('Location: display_picture.php');
display_picture.php
<?php
session_start();
?>
<div>
<img src="<?php echo $_SESSION['user_name6']; ?>" alt="picture"/>
</div>

Categories