have an upload script where I can delete an image I have to write manually its name in an input box in a form.I read the images' names directly from a folder in my server. I'd like to copy the name of the image that I want to delete by clicking on the image or on its name for each image that I want to delete. It's not easy to explain it, I will show you the code:
EDIT2: It'working:
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'GET' ) {
if (isset($_GET['name']) && $_GET['name'] != '') {
$img_file = $_GET['name'];
if($img_file){
unlink("img/$img_file");
header('Location: index.php');
}
}
}
?>
<?php
if(isset($_POST['upload_img'])){
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$file_tmp_name = $_FILES['image']['tmp_name'];
if($file_name){
move_uploaded_file($file_tmp_name,"img/$file_name");
}
}
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label>upload image </label><br>
<input type="file" name="image"><br>
<input type="submit" value="Upload Image" name="upload_img">
</form>
<?php
$folder = "img/";
if(is_dir($folder)){
if($handle = opendir($folder)){
while(($file=readdir($handle)) != false){
if($file==='.' || $file==='..') continue;
echo '<a href="index.php?name='.$file.'">';
echo '<img src="img/'.$file.'" width="150" height="150" alt="">';
echo '</a>';
}
closedir($handle);
}
}
echo '<br>'.$file_names;
?>
</body>
You need to wrap your img tag in an anchor tag like so
Assuming your current script is called mypics.php you could do this.
echo '<a href="mypics.php?name="' . $file . '">';
echo '<img src="img/'.$file.'" width="150" height="150" alt="">';
echo '</a>';
Now at the top of your current script you add
<?php
// picture clicks will be returned as GET requests
if ( $_SERVER["REQUEST_METHOD"] == 'GET' ) {
if (isset($_GET['name']) && $_GET['name'] != '') {
// do any sanity checks that you are only
// deleting a sensible file name etc
// delete the file
}
// your existing script follows, which should re-paint the page
// without the deleted image
You can now delete the code you were using for entering the name and processing the delete that way
You can put the img tag inside a tag, with a link to a script that deletes the file, something like:
echo <<< EOF
<img src="img/$file" width="150" height="150" alt="">
EOF;
Then create a file called, deleteFile.php
if(isset($_GET['fileToDelete')){
//NOTE: Make SURE you filter and restrict the content of $_GET['fileToDelete'), or may get all the files removed...
//remove the file here
}
Related
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>
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; ?>
?>
I have a simple register form where the user can upload a profile picture, if the user doesn't it, it should take the default picture name called person-icon.png.
When I register an user and upload a picture it works but if i leave it blank don't do anything and that column is inserted into the DB empty
if(isset($_FILES['image'])){
$img = $_FILES['image']['name'];
}
else if(empty($_FILES['image']['name'])){
$img = 'person-icon.png';
}
I already have tried these options:
Option 1:
if (empty($_FILES['image'])){
$img = 'person-icon.png';
}
else{
$img = $_FILES['image']['name'];
}
Option 2:
if($_FILES["image"]["error"] == 4)
Option 3:
if($_FILES["image"]["name"] == "")
You could check for $_FILE['image']['name'] not equal "" this work;
See code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
//var_dump($_FILES);
$default_pic =" pic.png";
if (isset($_FILES['image'])){
if($_FILES['image']['name'] != ""){
echo "has pic";
}
else{
$_FILES['image']['name'] = $default_pic;
echo "has no pic";
}
}
?>
In order to check if a file has been uploaded you have to look for the tmp_name, because that is what contains the actual copy of your file content on the server.
I would do something like this:
$file = $_FILES['file']['tmp_name'];
if (!file_exists($file)){
//no image
}
else{
//image
}
You can also check $_FILES as long you don't upload other files in that form:
if(empty($_FILES)){
//no image
}
else{
//image
}
For further information check the official manual of file uploads.
I hope this helped you :)
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>
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!"; } } ?>