PHP File Delete Issue? - php

I have the following HTML form:
<form action='delete.php' method='POST'>
<table>
<div class = '.table'>
<?php
$dir = '../uploads/store/';
$newdir = ereg_replace('\.','',$dir);
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!preg_match('/^(\.(htaccess|\.)?|index\.html)/',$file)) {
echo "<tr><td><font color = 'white'><a href='$newdir$file'>$file</a></font></td>";
echo "<td><input type='submit' value ='Delete'></td></tr>";
echo "<input align='right' type='hidden' value='$file' name='file'>";
}
}
closedir($dh);
}
}
?>
</div>
</table>
</form>
Which links to the following PHP script:
<?php
session_start();
$file = $_POST['file'];
$dir = '../uploads/store/';
$file = $dir . $file;
opendir($dir);
if(unlink($file)) {
echo "File sucessfully deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
} else {
echo "Error: File could not be deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
}
?>
However, when the Delete button is pressed in the HTML form, the item above the one intended to delete is deleted.
Hope this makes sense.
NOTE: I'm not going for security with these scripts, I'm going to work on that later. It's only me using this service right now.

Your HTML form needs to have the various submit buttons pass the value for $file instead of using hidden fields.
The problem is that all of the hidden fields are POSTed to delete.php when you submit the form. Then, since you haven't used the PHP-friendly HTML array variable syntax, PHP uses only the last of these to set the value of $_POST['file']. If you do a var_dump of $_POST in delete.php, you will see what the POSTed input is.
The easiest thing to do, with your current markup, is just to have each submit button be named file and pass $file as its value. i.e. you could do:
<button name="file" value="example.txt" type="submit">Delete</button>
Alternately, you could use radio buttons or some other markup.

Related

Reading/Writing boolean values to INI file in PHP

First, forgive me if this is an overly pedantic question. I have searched trying to find answers but perhaps I'm using the wrong search terms.
Trying to use an INI file for a simple PHP application, where there is an admin page to allow application options to be easily changed. I'm able to read in the ini file with no issue, problem I'm coming across is on the write - if any boolean values are false, they won't get put into the _POST and as such don't get written back into the ini file. Here's my sample:
settings.ini file:
[Site options]
bRequireLegal['Require NDA before badge print'] = true ;
bCollectVehicleInfo['Collect vehicle information'] = false;
bShowAdditionalMessageBeforeBadgePrint['Show badge printing message'] = true;
[Company info]
companyname['Company Name'] = 'The Company, Inc.' ;
Code to read in the ini file (settings.php):
$filepath = 'settings.ini'; //location of settings file
$settings = parse_ini_file($filepath, true, $scanner_mode = INI_SCANNER_TYPED);
//pull everything in ini file in as variable
foreach($settings as $section=>$options){
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
${htmlspecialchars($option)} = +$value;
}
else ${htmlspecialchars($option)} = $value;
}
}
}
And finally, the options setting page:
<?php
include 'settings.php';
//after the form submit
if($_POST){
$data = $_POST;
update_ini_file($data, $filepath);
}
function update_ini_file($data, $filepath) {
$content = "";
//parse the ini file to get the sections
foreach($data as $section=>$options){
//append the section
$content .= "[".$section."]\r\n";
//append the values
foreach($options as $option=>$values){
$content .= $option;
foreach($values as $descriptor=>$value){
$content .= "['".$descriptor."'] = '".$value."';\r\n";
}
}
$content .= "\r\n";
}
if (!$handle = fopen($filepath, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
?>
<html>
<body>
<?php
?>
<div class="container-fluid">
<form action="" method="post">
<?php
foreach($settings as $section=>$options){
echo "<h3>$section</h3>";
//keep the section as hidden text so we can update once the form submitted
echo "<input type='hidden' value='$section' name='$section' />";
//print all other values as input fields, so can edit.
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
} else
echo "<p>".$descriptor.": <input type='text' name='{$section}[$option][$descriptor]' value='$value' />"."</p>";
}
}
echo "<br>";
}
?>
<input type="submit" value="Update INI" />
</form>
</div>
</body>
</html>
Any help would be greatly appreciated!
In your update_ini_file() function, replace this:
$content .= "['".$descriptor."'] = '".$value."';\r\n";
with
$content .= "['".$descriptor."'] = '".($value ? 'true' : 'false')."';\r\n";
This will cause it to write the strings 'true' and 'false' instead of literal Boolean values. See How to Convert Boolean to String
Edit to add:
I think you're generating your checkboxes incorrectly:
<input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." />
This will cause the 'true' boxes to be checked, but they will still lack a value (and thus will not be transmitted to the server when the form is submitted). You should change that code to:
<input type='checkbox' name='{$section}[$option][$descriptor]' value='1'".(($value===true)?" checked":"")." />
In other words, all checkboxes should have a value of '1', but the way the browser works, only those which are checked will be submitted.
Edit to add:
Checkboxes that are not checked will not get submitted. That explains why you are not seeing any output for values that are 'false': they simply don't get submitted. When you loop through $data (which comes from $_POST), it is missing those unchecked (and thus 'false') checkboxes.
Using a solution found here: POST unchecked HTML checkboxes
Change this:
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
to this, which includes a hidden field that has the value '0', which will get submitted even if the corresponding checkbox is unchecked:
echo "<p>".$descriptor.": <input type='hidden' name='{$section}[$option][$descriptor]' value='0'><input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
However, this has its own set of potential problems, specifically when a checkbox is checked, you will send two identically named fields: one with a '0' value and the other with a '1' value. This is explained in the link above, and is left as an exercise for you to solve (or ask for further details on) if my answer doesn't work.

PHP, using $_FILES and $_POST at the same time

I have a problem in using $_FILES and $_POST at the same the because I have a form to upload an image and some data bus when I use one of them it works but when I used the other one id doesn't work.
my code is :
<?php
include 'debugging.php';
//phpinfo();
echo '<br />';
echo '<h1>Image Upload</h1>';
//create a form with a file upload control and a submit button
echo <<<_END
<br />
<form method='post' action='uplaodex.php' enctype='multipart/form-data'>
Select File: <input type='file' name='picName' size='50' />
name: <input type='text' name='usName' size='50' />
username : <input type='text' name='usUsername' size='50' />
pass: <input type='password' name='usPass' size='50' />
email: <input type='text' name='usEmail' size='50' />
<br />
<input type='submit' value='Upload' />
<input type="hidden" name="submit" value="1" />
</form>
<br />
_END;
//above is a special use of the echo function - everything between <<<_END
//and _END will be treated as one large echo statement
//$_FILES is a PHP global array similar to $_POST and $_GET
if (isset($_FILES['picName'])and isset($_POST['submit'])) {
//we access the $_FILES array using the name of the upload control in the form created above
//
//create a file path to save the uploaded file into
$name = "images//" . $_FILES['picName']['name']; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if (move_uploaded_file($_FILES['picName']['tmp_name'], $name)) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
//we are going to store the file type and the size so we get that info
$type = $_FILES['picName']['type'];
$size = $_FILES['picName']['size'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//select the ID of the image just stored so we can create a link
//display success message
echo "<h1> Thankyou </h1><p>Image stored successfully</p>";
//this above line of code displays the image now stored in the images sub directory
echo "<p>Uploaded image '$name'</p><br /><img src='$name' height='200' width='200'/>";
//create alink to the page we will use to display the stored image
echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
} else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
}
} else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
echo "</body></html>";
?>
I don't know what is the problem, any help??
Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit'])) doesn't work because the superglobal $_FILES is probably not having a key named picName. To check this out, try var_dump-ing the $_FILES, like var_dump($_FILES);
By the output of the var_dump you'd get to know if there is any content inside $_FILES. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On in the ini file for php.
Hope it helps!
You have to validate the size of the file if you want to do an isset. I don't know if this is works, but the better way for do that is check first the size for validate if isset or was send to the server.
Then, in your <form method='post' action='uplaodex.php' enctype='multipart/form-data'> you have to create another PHP file with the name uplaodex.php where you'll send al the data. So, your code with be like the below code following and considering the step 1. This will be your uploadex.php
$name_file = $_FILES['picName']['name'];
$type = $name_file['type'];
$size = $name_file['size'];
$tmp_folder = $name_file['tmp'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
if ( $size > 0 ) {
//REMOVE another slash images//
$name = "images/" . $name_file; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if ( move_uploaded_file($tmp_folder, $name) ) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//USE PRINTF
printf('<h1> Thankyou </h1><p>Image stored successfully</p><br>
<p>Uploaded file: %s</p>. <img src="%s" height="200" width="200" />',
$name_file, $name );
#WHAT IS $fileId? In which moment was define?
//echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
}
else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
} //ENDIF OF if (move_uploaded_file($_FILES['picName']['tmp_name'], $name))
} //ENDIF OF if ( $size > 0 )
#ELSE OF YOUR if ( $size > 0 )
else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
I solved the problem, you can't perform $_FILES and $_post at the same time or one of them inside the other.
start with $_Post and then $_FILES and outside the $_FILES run your saving function
thats it

Display previous logged in timestamp from txt file

I was asked to do this by my college staffs so kindly help me out with this! I have a php file with a text box and login id is supposed to be entered in it and login button is to be pressed. Once this button is pressed, the login id and timestamp is stored in a txt file. Next time the same login id is used then the timestamp is to be overwritten. I have done this part successfully. Now, i wanna display the timestamp before overwritting it. This is something similar to last seen of whatsapp. How can i display it?
This is my code:
<html>
<head><title>Login Portal</title></head>
<body><center>
<h1>TPF EMPLOYEE LOGIN</h1><hr><br><br>
<?php
session_start();
if(isset($_POST['submit']))
{
$myfile = file_get_contents('data.txt');
$_SESSION['name']=$_POST['id'];
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s');
$txt=$_SESSION['name'].",".$date.",\n";
$name = $_SESSION['name'];
if(preg_match("/$name/", $myfile))
{
$results = preg_replace("/$name.*\,/", $txt, $myfile);
file_put_contents('data.txt', $results);
}
else
{
file_put_contents('data.txt', $txt, FILE_APPEND);
}
}
else
{
echo "<form name='login' method='post'>";
echo "Enter your login id : <input type='text' name='id' id='id' /><br><br>";
echo "<input type='submit' name='submit' value='Login' />";
echo "</form>";
}
?>
</center>
</body>
</html>
This is the contents of my txt file:
a,2014-10-05 19:00:40,
b,2014-10-05 19:00:31,
Using the comma after the name as an identifier how do i display the previous timestamp before overwritting it?
Change:
if(preg_match("/$name/", $myfile))
{
to include $matches and alter the regexp, then work with $matches array:
if(preg_match("/$name\,(.*),/", $myfile, $matches))
{
echo 'Previous Login: ' . $matches[1];
Example: http://ideone.com/1diNNd
Hints: use a db, ensure $name is unique...

delete image from folder PHP

I have a folder where I keep my images, named img/. I have a table with all of my images:
<table border="3">
<tr>
<td>
<?php
$files = glob("img/*");
foreach ($files as $file) {
echo "<div class='divimages'>";
echo '<img src="'.$file.'"/>';
echo "<input type='submit' value='Delete image'/><br>";
echo "</div>";
}
?>
</td>
</tr>
</table>
How can I delete the image associated to the button with the value:"Delete image".
There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink
DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.
Each image's display markup would contain a form something like this:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
...and at at the top of that same PHP file:
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
// existing code continues below...
You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.
Documentation and Related Reading
unlink - http://php.net/manual/en/function.unlink.php
$_POST - http://php.net/manual/en/reserved.variables.post.php
file_exists - http://php.net/manual/en/function.file-exists.php
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
"Using PHP With HTML Forms" - http://www.tizag.com/phpT/forms.php
You can delete files in PHP using the unlink() function.
unlink('path/to/file.jpg');
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
For deleting use http://www.php.net/manual/en/function.unlink.php
Hope you'll can to write logic?
You can try this code. This is Simple PHP Image Deleting code from the server.
<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>
<?php
if (isset($_POST['submit']))
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
{
echo ("Error deleting $photoname");
}
else
{
echo ("Deleted $photoname");
}
}
?>
<?php
require 'database.php';
$id = $_GET['id'];
$image = "SELECT * FROM slider WHERE id = '$id'";
$query = mysqli_query($connect, $image);
$after = mysqli_fetch_assoc($query);
if ($after['image'] != 'default.png') {
unlink('../slider/'.$after['image']);
}
$delete = "DELETE FROM slider WHERE id = $id";
$query = mysqli_query($connect, $delete);
if ($query) {
header('location: slider.php');
}
?>
<?php
$path = 'img/imageName.jpg';
if (is_file($path)) {
unlink($path);
} else {
die('your image not found');
}

PHP not receiving values for radio buttons

I'm using a PHP webpage to give me a list of all files with a .264 extension in a specific folder. The file is then selected and sent to a command to playback the video on a display attached to the computer.
I'm having difficulties trying to get the radio buttons to maintain their values, so that when they are selected and the form button is pressed, they do not know their values and are therefore not able to execute the script.
I know the script works, because I tested it with just a fill-in-the-blank type form and had no problems.
Now I'm listing the files with a radio button to select the file and submit it to the form to play, but it isn't working as I had hoped.
I've looked around and tried to figure it out. I'm not sure if I need to use a linked list or something instead of an array. This is my first time doing php coding, so I'm not sure where I should start to try to resolve this.
<?php
$FileCount = 0;
$currentdir = '/data/'; //Location of Hard Drive
$dir = opendir($currentdir);
$array = array();
echo '<ul>';
while ($File = readdir($dir)){
//if (is_file($file))
$ext = pathinfo($File, PATHINFO_EXTENSION);
if ($ext == '264'){
$array[] = "$File";
echo "<INPUT class='radio' type='radio' name='FileName' value='$File' /> <span>$File</span><p>";
$FileCount++;
}
}
echo '<form action="test.php" method = "post">';
echo "<INPUT TYPE = 'Submit' name = 'FormSubmit' value = 'Submit'>";
echo '</form>';
if ($_POST['FormSubmit'] == "Submit")
{
echo $_POST["FileName"];
}
Nothing returns with this code. Any help would be great. Thanks.
If you want the values of the radio button controls to be sent along with the form post, then the controls themselves must be children of the form element.
<form method = "post" action = "">
<?php while ($File = readdir($dir)) {
if(pathinfo($File, PATHINFO_EXTENSION) == '264')) { ?>
<input type = "radio" ... >
<?php
}
}
?>
<input type = "submit" value = "Submit" name = "FormSubmit">
</form>
As you have it now, the radio buttons exist outside of the form, so they are not part of the form.
echo '<form action="test.php" method = "post">';
add this code below
while ($File = readdir($dir)){

Categories