php image checkbox deleter - php

I am having trouble making a image deleter in php i do not know what is wrong
PHP:
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
$image = $_POST['dcheck'];
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
?>
HTML:
<form action="Admin3.php" method="post">
<?php
while($check = mysql_fetch_array($query2)){
echo '<img class="images2" src= "/PhotographyMML/Uploads/resized' . $check['PhotoName'] . $check['PhotoType'] . '" height="100" width ="100" ><input type="checkbox" name="dcheck[]" value="'. $check['PhotoNumber'] .'" />';
}
?>
<input type="submit" value="Delete Image(s)" />
</form>

Your dcheck variable is an array. You will want to create an outer loop around the existing query code you have and foreach through the array, deleting each time.
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
foreach ($_POST['dcheck'] as $image) {
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
}
?>
A small optimization would be to alter the query so it uses WHERE A small optimization would be to alter your delete query so that it uses WHERE PhotoNUmber IN (1, 2 ...).
This would cause your deletion to happen in one query rather than N queries.
What seems to be missing is any code to actually remove the original file you're alluding to. That would require some sort of file deletion function typically utilizing http://php.net/manual/en/function.unlink.php

Related

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

Variable for file directory path not being recognized

so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!
try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..

issue with blob image from mysql database

i have store an image into my database.
but i am unable to display the image what i have done till now is under.... any help will be appreciated. thanks in advance!
<?
$query="SELECT * from testimonial";
$ret = mysqli_query($mysql,$query);
if (isset($ret) && $ret->num_rows>0)
{
while($row=mysqli_fetch_array($ret))
{
$body=$row['body'];
$name=$row['name'];
$image=$row['img'];
?>
<li>
<div class="frame-icon"><? echo "<img src=test_img.php?id=".$row['id']." width=150 height=150/>";?></div>
<p class="quote"><?php echo $body; ?><span><?php echo $name; ?></span></p>
</li>
<?php }
echo "</table>";
}
?>
and my test_img code is
<?
<?php if (isset($_GET['id'])){
$id=mysql_real_escape_string($_GET['id']);
$query=mysql_query("SELECT *FROM testimonial WHERE id='$id' ");
while($row = mysql_fetch_assoc($query))
{
$image=$row["img"];
}
header("content-type: image/png");?>
hi Abhik i have try this one but i get something like this
and in my case i have png image so just change the jpeg to png the code you have given
but i got this <img src="data:image/png;base64,iVBORw0KGgpcMFwwXDANSUhEUlwwXDBcMGRcMFwwXDBkCAZcMFwwXDBw4pVUXDBcMFwwCXBIWXNcMFwwCxNcMFwwCxMBXDCanBhcMFwwCk9pQ0NQUGhvdG9zaG9wIElDQyBwcm9maWxlXDBcMHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHBcMBAIs2Qhc/0jAVww+H48PCtcIsAHvlwwAXjTCwhcMMBNm8AwHIf/D+pCmVxcAYCEAcB0kThLCIAUXDBAeo5CplwwQEYBgJ2YJlNcMKAEXDBgy2Ni41wwUC1cMGBcJ3/m01wwgJ34mXsBXDBblCEVAaCRXDAgE2WIRFwwaDtcMKzPVopFXDBY...6B2flQRKMpIP+DXCJ7HsLarL6Op8HdHo/cKIqsCFA4DsBDRQIS30pzU8aoX9JqqWYOntZjRPR6URKyCQVTCOGPXDDMiu8BWVM0P8z8cAzyOrJpdSgciP8+C8AX4VVUgLKOiHrSGqWC6QdFLGWnXDDsXCeivfHIulwiVdcZGHyV9mig3UVcMJKeKGdE9F/oUmo/Dlww+FmRXhaI6N+6UAzZjx8x875m3kOYV2AIXCJa34ViiLYU1XDWiO/o4jBEm9P9GoWpLFwwfUVV7o1CG/J8UW1nbUi5Qy85GdUkXCLPEtFzhQJcIlwiIFwiiMh1XCKyehwb863MfGHeNWQN25BDdoEyX4nB4+tmmtkUNHdwFxFRPxH93MymmNkxRPQGEf23mR0Xq82tfRqHXDDgpeiwnBj7tdvM2MzSVL5l7n+TmXcDWGdmvYWqy/FSWP3/Rkq7Q9AFpEtdQLqAdKkLyNig/xtcMETk0l30p0FqXDBcMFwwXDBJRU5ErkJggg==">
How about if you store the location of the image in DB then store the image itself in the file system? It's a better choice I think.
Proper way to display the blob images stored in DB is
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['img']) . '">';

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');
}

Cannot Update Image In PHP&MYSQL

hi guys i am working on a project where i have a student_edit.php file which updates the students
details all my data is updated successfully but there is one problem when i update lets say only two fields and not all then image is blanked and my fields updated successfully.
what i am doing is that i am showing student picture and besides it i have another input fields to browse image to update image. What i want is simple that if i am not updating image instead i update other fields image should be still there and not become blank.
Necessary code snippets is like that:
<?php
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (copy($tmp_name, "images/" . $file_name)) {
$picture = "images/" . $file_name;
}
if (!isset($_POST['picture'])) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
else {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
}
?>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
Just a quick guess by looking at your code, you are not escaping the value of $picture when you place it in the database, which could be why the image value in the database is not updating.
Also, don't use if(!isset($_POST['picture'])), but try if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == ""). The $_POST super global won't work, because files are sent via the $_FILES super global.
Putting it all together:
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == "")) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
} else {
copy($tmp_name, "images/" . $file_name)
$picture = mysql_real_escape_string("images/".$file_name);
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
Also, I REALLY recommend that you use the MySQLi extension: http://php.net/manual/en/book.mysqli.php
The above code is totally untested, but should work.

Categories