Jump to content

Delete file (array setup)


emediastudios

Recommended Posts

I have this code that i use in a different site that deletes one file(photo).

how can i build an array to delete three files photo1, photo2, photo3,.

 

 

<?php
$myFile = "../images/news/". $_POST['photo']; 
if (!empty($_POST['photo']))
     {

unlink($myFile);
}
else
     {
       echo  "";
     }
?>

Link to comment
Share on other sites

Your next question is going to be how do i submit that through a form :

Your html

<input type="text" name="photos[]" />
<input type="text" name="photos[]" />
<input type="text" name="photos[]" />

 

Your php

<?
$arrayOfFiles = array($_POST['photos'][0],$_POST['photos'][1],$_POST['photos'][2]);
foreach($arrayOfFiles as $file){
  unlink($file);
}
?>

Link to comment
Share on other sites

Added your code.

It deletes the record but no files are deleted?

 

Here is my ful code

 

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

if ((isset($_POST['headline'])) && ($_POST['headline'] != "")) {
  $deleteSQL = sprintf("DELETE FROM news WHERE headline=%s",
                       GetSQLValueString($_POST['headline'], "text"));

  mysql_select_db($database_gcproperty, $gcproperty);
  $Result1 = mysql_query($deleteSQL, $gcproperty) or die(mysql_error());

  $deleteGoTo = "news_deleted.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?";
    $deleteGoTo .= $_SERVER['QUERY_STRING'];

$arrayOfFiles = array($_POST['photos'][0],$_POST['photos'][1],$_POST['photos'][2]);
foreach($arrayOfFiles as $file){
  unlink($file);



  }
  header(sprintf("Location: %s", $deleteGoTo));
}

mysql_select_db($database_gcproperty, $gcproperty);
$query_Recordset1 = "SELECT * FROM news";
$Recordset1 = mysql_query($query_Recordset1, $gcproperty) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>

Link to comment
Share on other sites

Here is my full page

<?php require_once('../Connections/p2w.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "restricted.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

if ((isset($_POST['id'])) && ($_POST['id'] != "")) {
  $deleteSQL = sprintf("DELETE FROM news WHERE id=%s",
                       GetSQLValueString($_POST['id'], "int"));

  mysql_select_db($database_p2w, $p2w);
  $Result1 = mysql_query($deleteSQL, $p2w) or die(mysql_error());

  $deleteGoTo = "news_deleted.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?";
    $deleteGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $deleteGoTo));
}

mysql_select_db($database_p2w, $p2w);
$query_Recordset1 = "SELECT * FROM news";
$Recordset1 = mysql_query($query_Recordset1, $p2w) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?><!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>Prepare 2 Win</title>

<!--[if IE 5]>
<style type="text/css"> 
/* place css box model fixes for IE 5* in this conditional comment */
.thrColAbsHdr #sidebar1 { width: 180px; }
.thrColAbsHdr #sidebar2 { width: 190px; }
</style>
<![endif]-->
<script type="text/javascript">
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
<script src="../Scripts/AC_RunActiveContent.js" type="text/javascript"></script>
<link href="../css/scrollbar.css" rel="stylesheet" type="text/css" />
</head>

<body class="thrColAbsHdr">

<div id="container">
  <div id="sidebar1">
    <script type="text/javascript">
AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','290','height','162','title','navigation','src','admin','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','admin' ); //end AC code
    </script>
    <noscript>
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="290" height="162" title="navigation">
      <param name="movie" value="admin.swf" />
      <param name="quality" value="high" />
      <embed src="admin.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="290" height="162"></embed>
    </object>
    </noscript>
  </div>
  <div id="sidebar2">
    <div align="center"><span class="credit">©2007 Prepare To Win - Jonathan Davie - All Rights Reserved.<br />
      Website Design by <a href="http://www.emediastudios.com.au" target="_blank">Emedia Studios</a></span></div>
  </div>
  <div id="mainContent"><img src="../images/delete_news_title.png" alt="The Philosophy" width="405" height="35" />
    <!-- end #mainContent -->
  </div>
  <div class="credit" id="mainContent2"><img src="../images/delete_news_title1.png" alt="add news" width="405" height="23" />
There are currently 
    <?php echo $totalRows_Recordset1 ?> records in your database.
    <br /><div align="left">
      <?php if ($totalRows_Recordset1 == 0) { // Show if recordset empty ?>
        
      </MM:DECORATION></MM_HIDDENREGION>
    
        <span class="credit">
        <MM_HIDDENREGION><MM:DECORATION OUTLINE="Show%20If..." OUTLINEID=1>There are currently no news items to delete</MM:DECORATION></MM_HIDDENREGION>
        </span>
        <MM_HIDDENREGION><MM:DECORATION OUTLINE="Show%20If..." OUTLINEID=1></MM:DECORATION></MM_HIDDENREGION>
        <span class="credit">
      <MM_HIDDENREGION><MM:DECORATION OUTLINE="Show%20If..." OUTLINEID=1>
        <?php } // Show if recordset empty ?>
        </span></div>
    <?php do { ?>
        <?php if ($totalRows_Recordset1 > 0) { // Show if recordset not empty ?>
        <form action="" method="POST" enctype="multipart/form-data" name="news" target="_self" id="news" onsubmit="MM_validateForm('headline','','R','contents','','R');return document.MM_returnValue">
          <table width="100%" border="0" background="../images/application_form.png" class="credit">
            <tr>
              <td width="31%" bgcolor="#000066">Headline:</td>
              <td width="69%" bgcolor="#000066"><label>
                <input name="id" type="hidden" id="id" value="<?php echo $row_Recordset1['id']; ?>" />
              <?php echo $row_Recordset1['headline']; ?></label></td>
            </tr>
            <tr>
              <td>Contents:</td>
              <td><label><?php echo $row_Recordset1['contents']; ?></label></td>
            </tr>
            <tr>
              <td>Photo 1 Title</td>
              <td><label><?php echo $row_Recordset1['title1']; ?></label></td>
            </tr>
            <tr>
              <td>Photo 1:</td>
              <td><img src="../news/<?php echo $row_Recordset1['photo1']; ?>" alt="<?php echo $row_Recordset1['title1']; ?>" width="50" /></td>
            </tr>
            <tr>
              <td>Photo 2 Title:</td>
              <td><?php echo $row_Recordset1['title2']; ?></td>
            </tr>
            <tr>
              <td>Photo 2:</td>
              <td><label><img src="../news/<?php echo $row_Recordset1['photo2']; ?>" alt="<?php echo $row_Recordset1['title2']; ?>" width="50" /></label></td>
            </tr>
            <tr>
              <td>Photo 3 Title</td>
              <td><?php echo $row_Recordset1['title3']; ?></td>
            </tr>
            <tr>
              <td>Photo 3:</td>
              <td><img src="../news/<?php echo $row_Recordset1['photo3']; ?>" alt="<?php echo $row_Recordset1['title3']; ?>" width="50" /></td>
            </tr>
            <tr>
              <td>Web Link:</td>
              <td><label><?php echo $row_Recordset1['link']; ?></label></td>
            </tr>
            <tr>
              <td> </td>
              <td><label>
                <input name="submit" type="submit" class="fields" id="submit" value="Delete" />
              </label></td>
            </tr>
          </table>
          <br />
            <br />
        </form>
        <?php } // Show if recordset not empty ?>
        <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?></div>
  <!-- end #container -->
</div>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>

I want to include a unlink function in there somewhere to delete the three photos

Thanks for the help

Link to comment
Share on other sites

You're outputting more than 1 form, you only need 1 form...

Also where are the input fields with the names of the photos?

 

Seriously use my nice simple example, make a simple script using the html i have given you, submit it to the php page i have given you and learn what it's doing. Then apply the same logic to your complex script.

 

Incidently i recommend separating out your logic better, keep your presentation and business logic apart.

Link to comment
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.