?
Solved

How to delete and replace images using php

Posted on 2012-03-22
11
Medium Priority
?
222 Views
Last Modified: 2012-03-22
Ok so lets say I have a form that displays the users images that he had inserted and now he wants to either replace or delete the images. How canI write the php script?

Form

<?php
session_start();
if(empty($_SESSION['myusername'])){

// send them back to login

header('location: index.php');

}
$_SESSION['id'];
$_SESSION['$myusername'];


$id = (int)$_GET['id'];
$id = substr($id, 0,5);
	
if($id < 1 || $id > 99999) exit;
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name=""; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// get value of id that sent from address bar
$id=$_GET['id'];


// Retrieve data from database 
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);

$rows=mysql_fetch_array($result);
?>
<!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>Untitled Document</title>
</head>

<body>
<form method="post" action="modifyform.php" enctype="multipart/form-data"/>
        <input type="hidden" name="id" id="id" value="<?php echo $id; ?>"  />
<table width="914" height="300" border="0">
  &gt;
  <tr>
    <td style="text-align: center"><img src="<? echo $rows['imageurl1']; ?>" alt="" width="200" /><br />
      <input type="radio" name="radio" id="delete" value="<? $rows['imageurl1']; ?>" />
      <label for="delete"></label>
      Delete<br /></td>
    <td width="213" style="text-align: center"><img src="<? echo $rows['imageurl2']; ?>" alt="" width="200" /><br />
      <input type="radio" name="radio" id="delete2" value="<? $rows['imageurl1']; ?>" />
      <label for="delete"></label>
Delete</td>
    <td width="180" style="text-align: center"><img src="<? echo $rows['imageurl3']; ?>" alt="" width="200" /><br />
      <input type="radio" name="radio" id="delete3" value="<? $rows['imageurl1']; ?>" />
      <label for="delete"></label>
Delete</td>
    <td width="188" style="text-align: center"><img src="<? echo $rows['imageurl4']; ?>" alt="" width="200" /><br />
      <input type="radio" name="radio" id="delete4" value="<? $rows['imageurl1']; ?>" />
      <label for="delete"></label>
Delete</td>
  </tr>
  <tr>
    <td style="text-align: center"><div align="center">
      <input id="image1" type="file" name="image1" />
    </div></td>
    <td style="text-align: center"><div align="center">
      <input id="image2" type="file" name="image2" />
    </div></td>
    <td style="text-align: center"><div align="center">
      <input id="image3" type="file" name="image3" />
    </div></td>
    <td style="text-align: center"><div align="center">
      <input id="image4" type="file" name="image4" />
    </div></td>
  </tr>
  <tr>
    <td colspan="4" style="text-align: center"><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
  </tr>
</table>
</form>
</body>
</html>

Open in new window

0
Comment
Question by:genesisvh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 37752711
That would all depend on where you have the images stored.
0
 

Author Comment

by:genesisvh
ID: 37752837
I have the files stored in a folder but the paths are stored in a MySQL database. I don't want the files to be deleted just the paths in the MySQL database deleted or replaced with the new one.

This what would be a script that I would like it to work with in order the process the images but before that I would like to know how to delete if any chose to delete them or replace only the ones that are chosen.

Script:

<?php
session_start();
include('SimpleImage.php');
$image = new SimpleImage();    
//error_reporting(E_ALL); 


	// image upload folder
    $image_folder = 'images/'; 
	// fieldnames in form
	$all_file_fields = array('image1', 'image2' ,'image3', 'image4',);
	// allowed filetypes
	$file_types = array('jpg','gif','png');
	// max filesize 5mb
	$max_size = 5000000;
	//echo'<pre>';print_r($_FILES);exit;
	
	$time = time();
	$count = 1;
	
	foreach($all_file_fields as $fieldname){ 
		if($_FILES[$fieldname]['name'] != ''){
			
			$type = substr($_FILES[$fieldname]['name'], -3, 3);
						
			// check filetype
			if(in_array(strtolower($type), $file_types)){
				
				//check filesize
				if($_FILES[$fieldname]['size']>$max_size){
					$error = "File too big. Max filesize is ".$max_size." MB";
				
				}else{
				
					// new filename	
					$filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type;
			
					// move/upload file
					$image->load($_FILES[$fieldname]['tmp_name']);
					if($image->getWidth() > 150) { //if the image is larger that 150.
						$image->resizeToWidth(500); //resize to 500.
					}
					$target_path = $image_folder.basename($filename); //image path.
					
					$image->save($target_path); //save image to a directory.					
				
					//save array with filenames
					$images[$count] = $image_folder.$filename;
					$count = $count+1;

				}//end if

			}else{ $error = "Please use jpg, gif, png files";
			
			}//end if
		}//end if
	}//end foreach



if($error != ''){ echo $error;	
}else{ 

////OTHER STUF GOES HERE
	
	?>

Open in new window

0
 
LVL 17

Expert Comment

by:nanharbison
ID: 37752854
In pseudocode:
If $_FILES['image1'] is set, update the database table to replace the image being shown - $rows['imageurl1'] - with the one being uploaded.
0
WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

 

Author Comment

by:genesisvh
ID: 37752911
I'm fairly new to php but where can I put that statement, "If $_FILES['image1']" ?

Can you show me an example of the way this is used?
0
 
LVL 17

Accepted Solution

by:
nanharbison earned 1002 total points
ID: 37752991
if (isset($_FILES['image1'])) {

$updatechosenphoto = "UPDATE $tbl_name SET  imageurl1  = '$_FILES['image1']' WHERE id='$id'";
$updatechosenphotoresult = $result = mysql_query($updatechosenphoto) or die('Query failed: ' . mysql_error());
}

(Assuming imageurl1 is the name of the table column). You want the error message to show if there is some typo in this query to see what happened. You would set this up for all 4 images, there are ways to do this more efficiently but I thought you should understand the concept.

I am also assuming the imageurl has the path to the image where you are uploading it to.

Also, notice that the name of my query is very descriptive, not just $sql.
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 498 total points
ID: 37753254
I'm fairly new to php
You might want to get this book and give yourself a little time with some structured learning.  It will save you a lot of time in the long run, I promise!
http://www.sitepoint.com/books/phpmysql4/

Here is my teaching example of how to upload files.  You will have the additional need to connect these concepts to your data base.  But at least the upload part is shown here.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY (MUST ALREADY EXIST)
$uploads = 'RAY_junk';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'mp3'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 
LVL 17

Expert Comment

by:nanharbison
ID: 37753418
Are you using a file upload class?
0
 

Author Comment

by:genesisvh
ID: 37753461
No I'm not using a file upload class, but I'm to figure how I can implement this:

if (isset($_FILES['image1'])) {

$updatechosenphoto = "UPDATE $tbl_name SET  imageurl1  = '$_FILES['image1']' WHERE id='$id'";
$updatechosenphotoresult = $result = mysql_query($updatechosenphoto) or die('Query failed: ' . mysql_error());
}

into the script this might work I think?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37753512
The structure of $_FILES is documented in the online man pages.
http://php.net/manual/en/reserved.variables.files.php

You can use var_dump() to print out the contents of any variable, including $_FILES.
http://php.net/manual/en/function.var-dump.php

I would not use an external variable in a query statement without checking to see that its values are acceptable for my purposes.
0
 
LVL 17

Assisted Solution

by:nanharbison
nanharbison earned 1002 total points
ID: 37753538
If this is a website that will be available for all to use/see, then you need a class or you have to do a lot of coding to make the file uploads secure. Allowing file uploads introduces HUGE security risks to your website if not done correctly.
Here is one:
http://www.tutorialchip.com/php-upload-class/
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37753584
What was wrong with the answers that caused you to mark the grade down to a "B"?  Please explain, thanks.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question