php - How can I give the opportunity to choose weather I want to overwrite an existing upload file or not? -
i searched everywhere find tutorial simple need have, until couldn't find answer , cannot script work.
my script should following:
- user chooses file upload , click submit
- script checks if file exists
- if file not exist upload file destination
- if file exists ask user: "overwrite?"
- if user clicks "overwrite?" overwrite file
index.php
<form action="check.php" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit" value="upload">upload</button> </form>
check.php
<?php if(isset($_files['file'])) { $file = $_files['file']; $upload = $_files["file"]["tmp_name"]; $target_file = 'files/'.basename($_files["file"]["name"]); if (file_exists($target_file)) { echo "file exist"; echo "<form action='overwrite.php' method='post'> <input type='hidden' name='upload' value='$upload'> <input type='hidden' name='target_file' value='$target_file'> <button type='submit'> overwrite?</button> </form>"; } else { move_uploaded_file($upload, $target_file); echo "file uploaded"; echo "<a href='index.php'><button>back</button></a>"; } } ?>
overwrite.php
<?php $upload = $_post["upload"]; $target_file = $_post["target_file"]; move_uploaded_file($upload, $target_file); echo "the file overwritten"; ?>
the scripts have won't work as-is, because cannot preset hidden field values in order have user upload file. additionally, if did work, require file uploaded twice.
ideally, best if check whether or not file existed , overwritten before user spent time uploading file. depends on how dictate file exists.
are going file exists if filename user provides matches (as code seems now)? loenix mentioned, relying on user provide name of file way store isn't idea. use contents.. store files using sha1()
value filename. way, files same (regardless of name) don't take disk space, , files different (even same name) can co-exist). metadata (file name, path, etc) stored in database.
however end making determination, you'll want first submit ajax request server checks existence of file, , if exists, prompt user overwrite. if user chooses overwrite, or if file doesn't exist, file uploaded server , saved.
Comments
Post a Comment