PHP copy and unlink being ignored - php

This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
if ($allowdelete==true && $thepassword == $password)
{
//delete record that delete was set to by button
//$sql = ("DELETE FROM $table WHERE id=$id");
$sql = ("select picfile,title,author from $table where id=$delete");
$file=mysql_query($sql);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
if (file_exists("/pics".$picfile)){
copy("/pics/".$picfile,"/pics/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink("/pics/".$picfile);
echo $available = "image is available.";
$sql = ("DELETE FROM $table WHERE id=$delete");
$result = mysql_query($sql);
if ($result){
echo "Your Picture has been removed from our system.";
Die($available);
}
else{
echo "There was an error in removing your picture.";
$Delete = "";
Die();
}
}
else{
echo $available = "image is not available.";
}
}
The weird part is a have almost the same code in a delete button on my control panel located in "/adminpanel" and it works perfectly. The code for that is the same except I use $id instead $delete and "../" before all the "pics/" because it's in the adminpanel folder. The permissions are right and the folder exists because the code works with that page. And I know $delete is getting set because the record gets deleted from the database. I know picfile, author and title are getting set because I appended them to the print statement and they were all right. Really confused. Any ideas?
Here is the code for the working page
q = ("select picfile,title,author from $table where id=$id");
$file=mysql_query($q);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
copy("../pics/".$picfile,"../pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
unlink("../pics/".$picfile);
$file=mysql_query($q);
$q = ("DELETE FROM $table WHERE id=$id");
$file=mysql_query($q);

why is this line repeated twice $file=mysql_query($q); ?

Try this
$file_path = $_SERVER["DOCUMENT_ROOT"]."/pics/";
if (file_exists($file_path.$picfile))
{
copy($file_path.$picfile, $file_path."/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink($file_path.$picfile);
}
else
{
echo "File not found!!!!!!!!";
}

Related

how to use old profile picture if no image selected in php

this is my code updating data. How is it possible to use old image if no image is selected?
its a profile page when someone updates his profile but don't select the image for update then old image should be remained there..
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
if(isset($name)){
move_uploaded_file($temp_name,$location.$name);
}
else
{
echo $user_img;
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
First, you need to fetch the existing user details from the database and check if the user already has a profile picture.
Next, if the user has uploaded a new image, then you can delete the old profile picture using unlink() function. If the user has not uploaded a new picture, you can retain the old picture.
See the code below.
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
//Fetch user details
$query = "SELECT User_Pic FROM user WHERE Id=" . $update_id;
$result = mysqli_query($con, $query);
$row = false;
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
if (isset($_FILES['user_img'])) { //User uploaded new image
if ($row) {
unlink($location . $row['User_Pic']); //Delete old pic
}
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
move_uploaded_file($temp_name,$location.$name);
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
} else { //User did not upload image
if ($row) {
echo $location . $row['User_Pic']; //Echo current image path
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username' where Id='$update_id'";
}
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
Please note that the code shown here does not change the filename when storing the files on the server. This will cause problems when two person upload pictures with same filename. You need to implement an appropriate solution for that.

PHP Check mysqli_num_rows not working

I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.
The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log

PHP if in POST load only the first if

I have this code :
if(isset($_POST['remove'])){
$con = mysqli_connect(".","","","");
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
It is working, but I want it to do something like this
if(isset($_POST['remove'])){
$con = mysqli_connect("","","","");
while($row = mysqli_fetch_assoc($q)){
if($row['picture'] == ""){
echo "<div class='notemarg'> No pictures to delete</div>";
} else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
}
This means that the picture from database will be removed only if there IS any picture.. if not, then it will display that message "No pictures to delete" ... but it does not work.. it still shows that error message that there is no picture even though there is no blank row in database and so it does not delete the information in row either...
Where is problem?
BTW: first code works fine... and it works even if there is nothing in database so it kinda does not make sense that the "profile picture has been removed." is being displayed...
Try this instead:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con, "SELECT picutre FROM members where username = '". $_SESSION['username']. "'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
You need the mysqli_query statement:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con,"SELECT IFNULL(picture,'') AS picture
FROM members
WHERE username = '".$_SESSION['username']."'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}

delete images through database and directory

can somebody help me for my codes. i can delete the image in the database but in the directory i can't. im tried for long hours but it seems not work at all. would somebody help me please? here's my code: this is the code where the images
<?
//this is were images displayed
$query = "SELECT * FROM images WHERE category='home'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<img src="images/template/delete.png" id="AEDbutton">
echo "<img border=\"0\" src=\"".$row['image']."\" width=\"200\" height=\"100\">";
echo "<br>"; }
?>
,?
include('global.php');
//this is were image were deleted
if($delete != "")
{
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
//but in here , it cannot delete image through directory
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
?>
You already deleted the image entry in table, after that you try to get the same entry in DB. so, first you can delete the image from folder after that you can delete in the table.
<?php
include('global.php');
if($delete != "") {
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
?>
Note:
Make sure your path $file= '/.directory/'.$image; is correct, I think it referring from root directory.
Funny. That's because you are first deleting the image id from the database and after that you are trying to get the ID of the previously deleted image (which no longer exists) and delete the file associated with it. Switch the code like this.
include('global.php');
if($delete != "")
{
//first delete the file
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result))
{
try
{
$image = $delete['image'];
$file= '/images/'.$image;
unlink($file);
} catch (Exception $e) {
}
}
// after that delete the id from the db of that image associated with the deleted file
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
UPDATE: I added a try catch
If you are deleting images, first you need to delete image and then delete in DB

How to delete an image using PHP & MySQL?

I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".

Categories