Jump to content

Recommended Posts

<?php
// Include Databse
include ("common.php");

// VARIBLES	
$delete = $_POST['delete'];
$id = $_POST['id'];
$filename = $_POST['filename'];
$fields = array('id', 'filename');
$dir = "images/";
$file_to_delete = $dir. $filename;
$error = false;

// Check if form has been submitted
if (isset ($delete))
{
// Check filename & id is not empty
foreach($fields AS $fieldname) { 
  if(empty($_POST[$fieldname])) {
    $status = "Please enter a $fieldname " ;
	$error = true;
  }


/* 
HERE I WISH TO CHECK THAT $filename CONTAINS 
.JPEG,.JPG,PNG OR .GIF AT THE END SO OTHER FILE TYPES CANNOT BE DELETED

I ALSO WANT TO ENSURE THAT THE USER CANNOT GO TO
ANOTHER FOLDER AND STAYS IN THE CURRENT /images FOLDER

THIS IS SO USER CAN ONLY INPUT A NAME OF A FILE WITH A IMAGE FILETYPE AND CANNOT DELETE FROM ANY OTHER FOLDERS OTHER THAN /images

AS AT THE MOMENT YOU CAN TYPE ../FILENAME.WHATEVER AND IF IT EXISTS IT WILL DELETE IT
*/

//Check file exists
else if (!file_exists($file_to_delete))
{
$status = "File not found please check your filename";
$error = true;
}
}

if (!$error)
{
// Delete File From Directory
unlink($file_to_delete);

// Delete File Information From Database
$query = "DELETE FROM `test` WHERE `id` = $id" ;
   
try { 
// Run Query To Delete File Information From Database
        $stmt = $db->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    {  
        die("Failed to run query: Please report issue to admin"); 
    }


$status = "File Deleted";

}
}
?>

<?php 
$query = "SELECT id,photo FROM test";
      
try 
 { 
// Run Query To Show The Current Data In Database
        $stmt = $db->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    {   
        die("Failed to run query: Please report issue to admin"); 
    } 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<style type="text/css">
.table {
	text-align: center;
}
.table {
	font-weight: bold;
}
</style>
</head>

<body>
<form action="delete.php" method="post" enctype="multipart/form-data" class="table">
Please enter the Filename and ID of the image you wish to delete
  <table width="178" align="center">
    <tr class="table">
      <td width="144" class="table">Filename</td>
      <td width="30" class="table">ID </td>
    </tr>
    <tr>
      <td><input name="filename" type="text" value="<?php echo $filename; ?>" />      </td>
      <td><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="3" />      </td>
    </tr>
  </table>
  <p><?php echo $status; ?><br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  <p>IMAGE DETAILS </p>
  <table width="400" align="center" class="table">
    <tr>
      <th width="61">ID</th>
      <th width="185">Filename</th>
      <th width="138">Image</th>
    </tr>
  </table>
  <table width="400" align="center" class="table"> 
    <?php foreach($rows as $row): ?> 
        <tr> 
            <td width="61"><?php echo $row['id']; ?></td>

            <td width="185"><?php echo $row['photo']; ?></td>
            <td width="138" height="138">
<img src="images/<?php echo $row['photo'] ; ?>" width="138" height="138" /></td> 
        </tr>
    <?php endforeach; ?> 
</table> </p>
  <p><br />
  <br />
  </p>
</form>
</body>
</html>

Can somebody help me please I am currently creating a php/sql image slideshow I am currently coding the delete image page the code works as it should but am unsure how to code the bit in the /* */ comments in the code

 

Thanks in advance

 

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/
Share on other sites

HERE I WISH TO CHECK THAT $filename CONTAINS

.JPEG,.JPG,PNG OR .GIF AT THE END SO OTHER FILE TYPES CANNOT BE DELETED

Use pathinfo to get the extension. Remember that the extension may not be entirely lowercase.

 

I ALSO WANT TO ENSURE THAT THE USER CANNOT GO TO

ANOTHER FOLDER AND STAYS IN THE CURRENT /images FOLDER

 

THIS IS SO USER CAN ONLY INPUT A NAME OF A FILE WITH A IMAGE FILETYPE AND CANNOT DELETE FROM ANY OTHER FOLDERS OTHER THAN /images

 

AS AT THE MOMENT YOU CAN TYPE ../FILENAME.WHATEVER AND IF IT EXISTS IT WILL DELETE IT

You can omit the directory portion of the filename by using basename. Also check that the filename is a file, which will make sure the file exists and block any attempt to delete directories like . or .. (which would fail anyways). Edited by requinix
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513822
Share on other sites

<?php
// Include Databse
include ("common.php");

// VARIBLES	
$delete = $_POST['delete'];
$id = $_POST['id'];
$filename = $_POST['filename'];
$error = false;
$imagecheck = false;
$ext = end(explode('.',$filename));

// Check if form has been submitted
if (isset ($delete))
{
// Check filename is not empty
if(empty($filename)) {
    $status = "Please enter a Filename " ;
	$error = true;
	$filecheck = false;
}

// Check ID is not empty
else if(empty($id)) {
    $status = "Please enter a ID " ;
	$error = true;
	$filecheck = false;
}

else {
	$filecheck = true;
}

if ($filecheck)
{
//Check filename is a image ext
$imagetest=false;
$ext = end(explode('.',$filename));
switch(strtolower($ext)) {
    case 'jpeg':
        $error = false;
        break;
    case 'jpg':
        $error = false;
        break;
    case 'gif':
        $error = false;
        break;
    case 'png':
        $error = false;
        break;
    case 'bmp':
        $error = false;
        break;
    default:
        $error = true;
}
// ensure user stays in correct directory
if(!preg_match('/^[\w,\s-]+\.[A-Za-z]+$/',$filename)) {
	$error = true;
	$status = "Check Filename";
} 

else {
    $file_to_delete = 'images/' . $filename;
}
// Checks the file exists
if(!getimagesize($file_to_delete)) {
	$error = true;
	$status = "File not found please check Filename";
}

else 
{
	$error = false;
}

}
 
/*
HERE I WISH TO CHECK THAT $filename CONTAINS 
.JPEG,.JPG,PNG OR .GIF AT THE END SO OTHER FILE TYPES CANNOT BE DELETED

I ALSO WANT TO ENSURE THAT THE USER CANNOT GO TO
ANOTHER FOLDER AND STAYS IN THE CURRENT /images FOLDER

THIS IS SO USER CAN ONLY INPUT A NAME OF A FILE WITH A IMAGE FILETYPE AND CANNOT DELETE FROM ANY OTHER FOLDERS OTHER THAN /images

AS AT THE MOMENT YOU CAN TYPE ../FILENAME.WHATEVER AND IF IT EXISTS IT WILL DELETE IT
*/

if (!$error)
{
// Delete File From Directory
unlink($file_to_delete);

// Delete File Information From Database
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES (:firstname, :lastname, :email)");

$query = "DELETE FROM `test` WHERE `id` = $id" ;
try { 
// Run Query To Delete File Information From Database
        $stmt = $db->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    {  
        die("Failed to run query: Please report issue to admin"); 
    }


$status = "File Deleted";

}
}
?>

<?php 
$query = "SELECT id,photo FROM test";
      
try 
 { 
// Run Query To Show The Current Data In Database
        $stmt = $db->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    {   
        die("Failed to run query: Please report issue to admin"); 
    } 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<style type="text/css">
.table {
	text-align: center;
}
.table {
	font-weight: bold;
}
</style>
</head>

<body>
<form action="delete.php" method="post" enctype="multipart/form-data" class="table">
Please enter the Filename and ID of the image you wish to delete
  <table width="178" align="center">
    <tr class="table">
      <td width="144" class="table">Filename</td>
      <td width="30" class="table">ID </td>
    </tr>
    <tr>
      <td><input name="filename" type="text" value="<?php echo $filename; ?>" />      </td>
      <td><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" />      </td>
    </tr>
  </table>
  <p><?php echo $status; ?><br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  <p>IMAGE DETAILS </p>
  <table width="400" align="center" class="table">
    <tr>
      <th width="61">ID</th>
      <th width="185">Filename</th>
      <th width="138">Image</th>
    </tr>
  </table>
  <table width="400" align="center" class="table"> 
    <?php foreach($rows as $row): ?> 
        <tr> 
            <td width="61"><?php echo $row['id']; ?></td>

            <td width="185"><?php echo $row['photo']; ?></td>
            <td width="138" height="138">
<img src="images/<?php echo $row['photo'] ; ?>" width="138" height="138" /></td> 
        </tr>
    <?php endforeach; ?> 
</table> </p>
  <p><br />
  <br />
  </p>
</form>
</body>
</html>

Done it with code below but only problem I have is if the user enters incorrect or not aloud filename I get this

"Warning:getimagesize(): Filname is cannot be empty in ../delete.php on line 67

 

ASWELL as my $status "File not found Please check filename"

 

I only want the user to see my status not the Warning how do I go about this please?

Edited by ricpurcell
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513862
Share on other sites

ye I noticed the $image test thanks this was an error which have now changed to $error

ok so what I basically want that part of the code to do is if the file doesn't exists or if the user has input incorrect data therefore the file doesn't exist only display the $status error to inform the user the filename they entered is incorrect and not show the warning atall (as they'll already know they entered it incorrectly)

 

would it be better to use my previous code of as I already know the image is a image I just need to check that the user had input a image name ext and not another file type in an attempt to manipulate the code

 

if(!file_exists($file_to_delete))

{

$status = "File not found please check filename";

$error = true;

}

 

INSTEAD OF

 

if(!getimagesize($file_to_delete))

{

$status = "File not found please check filename";

$error = true;

}

 

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513910
Share on other sites

Does not matter if you use file_exists or getimagesize the problem remains as requinix mentioned earlier

 

$file_to_delete will only be set in certain circumstances but your code will try to getimagesize() it regardless.

 

Either do the file check in the else statement where $file_to_delete is defined or check whether that variable is defined first.

Edited by Ch0cu3r
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513919
Share on other sites

// ensure user stays in correct directory
if(!preg_match('/^[\w,\s-]+\.[A-Za-z]+$/',$filename)) {
	$error = true;
	$status = "Please Check FILENAME";
} 

else {
    $file_to_delete = 'images/' . $filename;
}

// Checks the file exists
if(!file_exists($file_to_delete))
{
$status = "File not found please check FILENAME";
$error = true;
}

 When I do this I get the result I want tho ? but the getimagesize() is to ensure the file is a image and not another type

 

(with file_exists if the user puts a filaneme of anything that doesn't exist I receive only $status which I want but the its not checking the file isn't a image but if I use getimagesize and it doesn't exist then I get the $status aswell as warning error at top(the warning error is what I don't want) only the $status)

 

so say if the user inputs a filename of test.php and it exists with with file_exists they are able to delete that file where as with getimagesize they'd reveieve the $status aswell as warning but I don't want them to see the warning

 

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513934
Share on other sites

// ensure user stays in correct directory
if(!preg_match('/^[\w,\s-]+\.[A-Za-z]+$/',$filename)) {
	$error = true;
	$status = "Please Check FILENAME";
} 

else {
    $file_to_delete = 'images/' . $filename;
}

// Check file_to_delete is set
if ($file_to_delete)
{
// Checks the file exists
if(!file_exists($file_to_delete))
{
$status = "File not found please check FILENAME";
$error = true;
$idcheck = false;
}

else 
{
$idcheck = true;	
}
}

if($idcheck)
{
// Check ID is not empty
if(empty($id)) {
    $status = "Please enter a ID " ;
	$error = true;
	$filecheck = false;
}

//Check if ID is not numeric
else if(!is_numeric($id))
{
	$error = true;
	$status = "Please check ID";
}
else
{
// Check ID exists in database
$query = "SELECT id FROM `test` WHERE `id` = :id" ;
$stmt = $db->prepare($query);
$stmt->bindParam(":id", $id);
$stmt->execute();

//if ID exists.
if($stmt->rowCount() > 0)
{
	$error = false;
}

else {
	$error = true;
	$status = "Please check ID";
}

this is my new code is this what you meant by it running whatever?

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513947
Share on other sites

I have gone a head and cleaned your code up (untested). There was a lot of unnecessary if statements/variables used. Have a look through the comments to see what going on

<?php
// Include Databse
include "common.php";

// validation errors
$error = array();

// Check if form has been submitted
if (isset ($_POST['delete']))
{
    // get the filename. See php.net/basename for more info
    $filename = basename($_POST['filename']);
    
    // get file extension, see php.net/pathinfo for more info
    $ext = pathinfo($_POST['filename'], PATHINFO_EXTENSION);

    // allowed file extensions
    $allowedExtensions = array('jpeg','jpg','gif','png','bmp');
    
    // Check ID is not empty    
    if(empty($_POST['id']))
    {
        $error[] = "Please enter a ID";
    }

    // Check filename is not empty
    if(empty($filename))
    {
        $error[] = "Please enter a Filename";
    }

    // Check valid file extension used
    if(!in_array($ext, $allowedExtensions))
    {
        $error[] = "Invalid file extension";
    }

    // path to the image
    $file_to_delete = 'images/' . $filename;

    // delete file from database if there are no errors
    if (empty($error))
    {

         // Checks the file exists and that is a valid image
        if(file_exists($file_to_delete) && getimagesize($file_to_delete))
        {
            // Delete File From Directory
            unlink($file_to_delete);
        }
        else
        {
            $error = true;
            $error[] = "File not found please check Filename";
        }
        
        try
        { 
            // Run Query To Delete File Information From Database
            $query = "DELETE FROM `test` WHERE `id` = :id";
            $stmt = $db->prepare($query); 
            $stmt->execute(array('id' => intval($_POST['id']))); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: Please report issue to admin"); 
        }


        $status = "File Deleted";
    }
}
      
try 
{ 
    $query = "SELECT id,photo FROM test";
    // Run Query To Show The Current Data In Database
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{   
    die("Failed to run query: Please report issue to admin"); 
} 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<style type="text/css">
.table {
    text-align: center;
}
.table {
    font-weight: bold;
}
</style>
</head>

<body>
<form action="delete.php" method="post" enctype="multipart/form-data" class="table">
Please enter the Filename and ID of the image you wish to delete
  <table width="178" align="center">
    <tr class="table">
      <td width="144" class="table">Filename</td>
      <td width="30" class="table">ID </td>
    </tr>
    <tr>
    <?php
    // Show validation errros here
    if(!empty($error)):
    ?>
        <td>Error: <?php implode('<br />', $errors); ?></td>
    <?php
    endif; 
    ?>
      <td><input name="filename" type="text" value="<?php echo $filename; ?>" /></td>
      <td><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" /></td>
    </tr>
  </table>
  <p><?php echo $status; ?><br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  <p>IMAGE DETAILS </p>
  <table width="400" align="center" class="table">
    <tr>
      <th width="61">ID</th>
      <th width="185">Filename</th>
      <th width="138">Image</th>
    </tr>
  </table>
  <table width="400" align="center" class="table"> 
    <?php foreach($rows as $row): ?> 
        <tr> 
            <td width="61"><?php echo $row['id']; ?></td>

            <td width="185"><?php echo $row['photo']; ?></td>
            <td width="138" height="138">
                <img src="images/<?php echo $row['photo'] ; ?>" width="138" height="138" />
            </td> 
        </tr>
    <?php endforeach; ?> 
</table> </p>
  <p><br />
  <br />
  </p>
</form>
</body>
</html>
  • Like 1
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513953
Share on other sites

<td>Error: <?php implode('<br />', $error); ?></td>
<td>Error: <?php implode('<br />', $errors); ?></td>

get Error: Warning: implode(): Invalid arguments passed in ../delete.php on line 117

 

Think see why says $errors changed this to $error

Edited by ricpurcell
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513957
Share on other sites

I forgot the echo before implode. You may need to change line 117 to 

<td colspan="2"><?php echo implode('<br />', $error); ?></td></tr><tr>

Otherwise the error messages will be all squished into one column in your table.

 

Also change line 33 to be a else if statement and delete line 53 $error = true;

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513967
Share on other sites

ive already edited that so its outside the table as when I do the stylising this isn't going to be a table anymore just focussing on the code atm

its working now thankyou just want to check is there a reason the ID checks aint in there? think I know how to change them if need to add them ?

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513971
Share on other sites

<?php
// Include Databse
include "common.php";

// validation errors
$error = array();

// Check if form has been submitted
if (isset ($_POST['delete']))
{
// get the filename & id. See php.net/basename for more info
    $filename = basename($_POST['filename']);
	$id = basename($_POST['id']);
    
// get file extension, see php.net/pathinfo for more info
    $ext = pathinfo($_POST['filename'], PATHINFO_EXTENSION);

// allowed file extensions
    $allowedExtensions = array('jpeg','jpg','gif','png','bmp');

// Check filename is not empty
    if(empty($filename))
    {
        $error[] = "Please enter a Filename";
    }

// Check valid file extension used
   else if(!in_array($ext, $allowedExtensions))
    {
        $error[] = "Please check Filename";
    }
	
// Check ID is not empty    
  else if(empty($_POST['id']))
    {
        $error[] = "Please enter a ID";
    }
	
	else if(is_numeric($id))
{
// Check ID exists in database
$query = "SELECT id FROM `test` WHERE `id` = :id" ;
$stmt = $db->prepare($query);
$stmt->bindParam(":id", $id);
$stmt->execute();

if(!$stmt->rowCount() > 0)
{
	$error[] = "Please check ID";
}
}

else {
	$error[] = "ID is not numeric";
}

// delete file from database if there are no errors
    if (empty($error))
    {
// path to the image
    $file_to_delete = 'images/' . $filename;
	
// Checks the file exists and that is a valid image
        if(file_exists($file_to_delete) && getimagesize($file_to_delete))
        {
// Delete File From Directory
            unlink($file_to_delete);
        }
        else
        {
            $error[] = "File not found please check Filename";
        }


// Run Query To Delete File Information From Database
        try
        { 

            $query = "DELETE FROM `test` WHERE `id` = :id";
            $stmt = $db->prepare($query); 
            $stmt->execute(array('id' => intval($_POST['id']))); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: Please report issue to admin"); 
        }


        $status = "File Deleted";
    }
}


// Run Query To Show The Current Data In Database
try 
{ 
    $query = "SELECT id,photo FROM test";
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{   
    die("Failed to run query: Please report issue to admin"); 
} 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<style type="text/css">
.table {
    text-align: center;
}
.table {
    font-weight: bold;
}
</style>
</head>

<body>
<form action="delete2.php" method="post" enctype="multipart/form-data" class="table">
Please enter the Filename and ID of the image you wish to delete
  <table width="178" align="center">
    <tr class="table">
      <td width="144" class="table">Filename</td>
      <td width="30" class="table">ID </td>
    </tr>
    <tr>
      <td><input name="filename" type="text" value="<?php echo $filename; ?>" /></td>
      <td><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" /></td>
    </tr>
  </table>
  <p>
    <?php 
// Show validation errros here
    if(!empty($error)):
    echo  implode('<br />', $error);
	echo $status;
	endif; 
    ?>
    <br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  <p>IMAGE DETAILS </p>
  <table width="400" align="center" class="table">
    <tr>
      <th width="61">ID</th>
      <th width="185">Filename</th>
      <th width="138">Image</th>
    </tr>
  </table>
  <table width="400" align="center" class="table"> 
    <?php foreach($rows as $row): ?> 
        <tr> 
            <td width="61"><?php echo $row['id']; ?></td>

            <td width="185"><?php echo $row['photo']; ?></td>
            <td width="138" height="138">
                <img src="images/<?php echo $row['photo'] ; ?>" width="138" height="138" />
            </td> 
        </tr>
    <?php endforeach; ?> 
</table> </p>
  <p><br />
  <br />
  </p>
</form>
</body>
</html>

ok so ive added it and slightly edited few parts like so ? Just noticed a problem if filename does exist it still continues and delets from sql if id is correct

Edited by ricpurcell
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513980
Share on other sites

You are almost there. A couple of issues

 

On line 13 you do not want to use basename.

$id = $_POST['id'];

basename was used on $_POST['Filename'] so only the filename is returned if someone had typed in a filepath into the filename field.

 

Line 34 should be an if statement not an else if statement

if(empty($_POST['id']))

The previous if and else if statements is used for validating the filename. On line 34 the if statement is the start of validating the id

 

On line 47 you want check $stmt->rowCount() is equal to 1, meaning has one row been returned from the query

if($stmt->rowCount() == 1)
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513982
Share on other sites

<?php
// Include Databse
include "common.php";

// validation errors
$error = array();

// Check if form has been submitted
if (isset ($_POST['delete']))
{
// get the filename & id. See php.net/basename for more info
    $filename = basename($_POST['filename']);
	$id =($_POST['id']);
    
// get file extension, see php.net/pathinfo for more info
    $ext = pathinfo($_POST['filename'], PATHINFO_EXTENSION);

// allowed file extensions
    $allowedExtensions = array('jpeg','jpg','gif','png','bmp');

// Check filename is not empty
    if(empty($filename))
    {
        $error[] = "Please enter a Filename";
    }

// Check valid file extension used
   else if(!in_array($ext, $allowedExtensions))
    {
        $error[] = "Please check Filename";
    }
	
// Check ID is not empty    
if(empty($_POST['id']))
    {
        $error[] = "Please enter a ID";
    }
	
	else if(is_numeric($id))
{
// Check ID exists in database
$query = "SELECT id FROM `test` WHERE `id` = :id" ;
$stmt = $db->prepare($query);
$stmt->bindParam(":id", $id);
$stmt->execute();

if(!$stmt->rowCount() == 1)
{
	$error[] = "Please check ID";
}
}

else {
	$error[] = "ID is not numeric";
}

// delete file from database if there are no errors
    if (empty($error))
    {
// path to the image
    $file_to_delete = 'images/' . $filename;
	
// Checks the file exists and that is a valid image
        if(file_exists($file_to_delete) && getimagesize($file_to_delete))
        {
// Delete File From Directory
            unlink($file_to_delete);
        }
        else
        {
            $error[] = "File not found please check Filename";
        }

if (empty($error))
{
// Run Query To Delete File Information From Database
        try
        { 

            $query = "DELETE FROM `test` WHERE `id` = :id";
            $stmt = $db->prepare($query); 
            $stmt->execute(array('id' => intval($_POST['id']))); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: Please report issue to admin"); 
        }


        $status = "File Deleted";
    }
}
}

// Run Query To Show The Current Data In Database
try 
{ 
    $query = "SELECT id,photo FROM test ORDER BY id";
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{   
    die("Failed to run query: Please report issue to admin"); 
} 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<style type="text/css">
.table {
    text-align: center;
}
.table {
    font-weight: bold;
}
</style>
</head>

<body>
<form action="delete2.php" method="post" enctype="multipart/form-data" class="table">
Please enter the Filename and ID of the image you wish to delete
  <table width="178" align="center">
    <tr class="table">
      <td width="144" class="table">Filename</td>
      <td width="30" class="table">ID </td>
    </tr>
    <tr>
      <td><input name="filename" type="text" value="<?php echo $filename; ?>" /></td>
      <td><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" /></td>
    </tr>
  </table>
  <p>
    <?php 
// Show validation errros here
    if(!empty($error)):
    echo  implode('<br />', $error);
	echo $status;
	endif; 
    ?>
    <br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  <p>IMAGE DETAILS </p>
  <table width="400" align="center" class="table">
    <tr>
      <th width="61">ID</th>
      <th width="185">Filename</th>
      <th width="138">Image</th>
    </tr>
  </table>
  <table width="400" align="center" class="table"> 
    <?php foreach($rows as $row): ?> 
        <tr> 
            <td width="61"><?php echo $row['id']; ?></td>

            <td width="185"><?php echo $row['photo']; ?></td>
            <td width="138" height="138">
                <img src="images/<?php echo $row['photo'] ; ?>" width="138" height="138" />
            </td> 
        </tr>
    <?php endforeach; ?> 
</table> </p>
  <p><br />
  <br />
  </p>
</form>
</body>
</html>

Ok resolved that problem by adding another if(empty($error)) before sql runs this is new code after them ajustments just mentioned

Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1513983
Share on other sites

  <p>Current Images Inside Gallery
    <br />
<?php foreach($rows as $row): ?>
  <div class="t">
    <table class="table2">
    <tr>
      <td class="table2"><?php echo $row["id"]; ?></td>
    </tr>
    <tr>
      <td><img src="images/<?php echo $row["photo"] ; ?>" alt="" width="130" height="130" /></td>
    </tr>
    <tr>
      <td><textarea class="js-copyfilename" readonly="readonly" ><?php echo $row["photo"];?></textarea>

  <button class="js-copyfilenamebtn">Copy Filname</button>
  </td>
    </tr>

    </table>
  </div>
<?php endforeach;?>
</div>
<script type="text/javascript">
        var copyfilenameBtn = document.querySelector('.js-copyfilenamebtn');

copyfilenameBtn.addEventListener('click', function(event) {
  var copyfilename = document.querySelector('.js-copyfilename');
  copyfilename.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
    </script>

Could somebody help me further please I am trying to create a Button so the user can copy the $filename the code works for the first one but not for the rest I understand that this is because I would probably need to array the js-copyfilename and js-copyfilenamebtn but I know very little about JavaScript so wouldn't know where to start

 

Many Thanks

Edited by ricpurcell
Link to comment
https://forums.phpfreaks.com/topic/296798-delete-form/#findComment-1514107
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.