I use a form where i have listed the data from database like title, date etc. from the database and using checkboxes i use the multiple delete operation
For example my code look like this
<form method="post" action="action.php">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>"/>
<input name="delete" type="submit" id="delete" value="Delete"/>
and in the action.php the code is like this
$checkbox = $_POST['checkbox'];
//count the number of selected checkboxes in an array
$count = count($checkbox);
//Create a for loop to delete
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM news WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
Now the table i want to delete actually have 5 table entities like title, timestamp,pic_title,pic_brief,pic_detail the last three entities i.e pic_title, pic_brief and pic_detail is actually storing the path of the image for example the value stored in one of the 3 entity would look like this upload/file/pic_title1.jpg
My problem is when i run my first for loop it successfully deletes the table without any problem but the file which exist in the file directory remains intact. i want to delete that file too, to remove that file i thought of adding another for loop which i did something like this
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT news.pic_title, news.pic_brief, news.pic_detail FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_detail']);
}
The above code is unable to delete the requested file, my Query string is perfectly working fine i tested it by removing the unlink function and printing the values, it prints all the selected value , but it is refusing to delete the file and when i try to run the loop it shows error in the last three line, while i am pretty sure that, $row['pic_title'], $row['pic_brief'], $row['pic_brief'], have the full path of the image.
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_brief']);
where i am going wrong?
P.S: There is nothing wrong with file permission because when i individually try to run the function unlink it deletes the file from the same directory.
EDIT : This is the error message i get
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 580
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 581
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 582
To be more precise i tested this function individually in php and it is working perfectly fine
$target = 'upload/file/file1.jpg';
unlink($target);
and for this reason i dont think the file permission is causing the error, i guess i am going wrong somewhere with the logic.
#Lekensteyn got me the solution, thank you Lekensteyn.
actually i had to first hold the value in a variable and then unlink the file. the working code looks like this.
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT * FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic_title = $row['pic_title'];
$pic_brief = $row['pic_brief'];
$pic_detail = $row['pic_detail'];
unlink($pic_title);
unlink($pic_brief);
unlink($pic_detail);
}
It could be file permissions. You need to be the owner of the file in order to delete it.
Some hosters run the website under the user 'apache' (or similar), but the files are owned by the ftpuser (accountxxxx for example).
Check the current working dir too, with echo getcwd() if the paths not absolute.
Your script is vulnerable to SQL injection too, a post request with checkbox[]='||1||' deletes everything.
Add
error_reporting(E_ALL);
at the top of your script.
Your problem is program flow related and can be found only by using debugging.
Start from displaying ALL errors occurred and repair them. This will most likely lead you to the reason you could not delete your files.
Probably your path to upload is the problem. In your test script:
$target = 'upload/file/file1.jpg';
unlink($target);
I bet you ran that from a directory right below 'upload/' right?
And this delete script, it's probably not in the same directory?
I recommend using the full path to the 'upload/file/' directory; this will vary depending on your configuration, but probably looks like /www/htdocs/upload/file or /var/www/public_html/upload/file.
To make the script more transportable, you can use the PHP constant FILE to figure out the directory. I usually set this app/site wide in a bootstrap or universal configuration file, along the lines of
define('PATH', dirname(__FILE__)); # sets PATH with the directory name of the bootstrap file where this code lives
I sometimes key on something in my path I can rely on, say my app name. Say my bootstrap is here:
/www/apps/golf-scorecard/bootstrap.php
I might split on 'golf-scorecard'.
list($path,) = explode('golf-scorecard',dirname(__FILE__)); # $path should be /www/apps/
define('PATH', $path.'golf-scorecard'); # since I split on it, I have to add it back in
This means if I move the app/site to another server, or clone it from a repository onto a machine where the document root is, say /home/username/apps/golf-scorecard/htdocs/, then it won't matter. It does couple the app name but I am okay with that.
first thing is you need to check the file permissions .you need to give 777 permission to the folder.and then follow below code
$target = 'upload/file/file1.jpg';
unlink($target);
Related
I'm trying to download a full library of photos from my university housing system.
The system runs on nginx, file parsing for that particular directory is unavailable, 404 returns all the time.
Anyway, every single photo is stored in a /res/up/250x300 directory, with a number, gender indicator and a random(?) hash, example here;
114057-f-95830a765f22b71ad5691adfdec6bfzfc222bb1c7.jpg
There's catalog of users which when called with specific user id returns file in EXACT same format as provided above, and is always stored in:
<div class="uwb-imgcover-photo-wrapper"/>
So, summarizing, it looks like this.
Calling for a specific user;
/kontroler.php?_action=katalog2/osoby/pokazOsobe&os_id=114057
class uwb-imgcover-photo-wrapper gives me a link to the photo:
/res/up/250x300/114057-f-95830a765f22b71ad5691adfdec6bfzfc222bb1c7.jpg
Wget magic doesn't work.
I was thinking about a loop or something like this. This is actually very first time I'm doing anything related to web file catching.
Try this
for($i=114050;$i<=114057;$i++){
$result = file_get_contents('http://domain.com/kontroler.php?_action=katalog2/osoby/pokazOsobe&os_id='.$i);
if($result){
preg_match('/\/res\/up\/250x300\/(.*?)\.jpg/',$result,$match);
if($match){
$filename = $match[1].'.jpg';
$imageURL = 'http://domain.com/res/up/250x300/'.$filename;
$image = file_get_contents($url);
file_put_contents($filename, $image);
}
}
}
I have a directory full of images (40,000 +) that I need sorted. I have designed a script to sort them into knew proper directories, however, I am having issues with the file name.
The images urls with the id they belong to are stored in a database, and I am using the database in conjunction with the script to sort the images.
My Problem:
The image url's in the database are shortened. An example of such corresponding images are like this:
dsc_0107-367.jpg
dsc_0107-367-5478-2354-0014.jpg
The first part of the filenames are the same, but the actual file contains more info. I'd like a way to move the file from the database with the known part of the file name.
I have a basic code:
<?php
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = '$_GET[id']");
while($file = mysqli_fetch_assoc($sfiles)){
$folder = $file['gal_id'];
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir";
$newDir = "mypath/to/new/dir/$file['gal_id']";
mkdir "$newDir";
mv "$fileToMove" "$newDir";
}
Im just confused on how to select the file based on the small part from the database.
NOTE: It's not as simple as changing the number of chars in the db, because the db was given to me from an external site thats been deleted. So this is all the data I have.
PHP can open files using the function glob() . Glob searches your server, or specified directory, for any files containing a "match" to a pattern you specify.
Using glob() like this will pull your images from a partial name.
Run this query separate from the second:
$update = mysqli($dbconn, "UPDATE files
SET filename = REPLACE(filename, '.info', ''));
filename should be the column in your database that contains the list of images. The reason we are removing the .jpg from the db columns is if your names are partial, the .jpg may not match with the given name in your directory. With it removed, we can search solely for the pattern of the name.
Build the query to select and move the folders:
$sfiles = mysqli_query($dbconn, "SELECT * FROM files");
while($file = mysqli_fetch_assoc($sfiles)){
$fileToMove = $file['filename'];
// because glob outputs the result set into an array,
// we will use foreach to run each result from the array individually.
foreach(glob("$fileToMove*") as filename){
echo "$filename <br>";
// I'm echoing this out to see that the results are being run
// one line at a time and to confirm the photo's are
// matching the pattern.
$folder = $file['gal_id'];
// pulling the id from the db of the gallery the photo belongs to.
// This will specify which folder to move the pic to.
// Replace gal_id with the name of your column.
$newDir = $_SERVER['DOCUMENT_ROOT']."/admin/wysiwyg/kcfinder/upload/images/gallery/old/".$folder;
copy($filename,$newDir."/".$filename);
// I would recommend copy rather than move.
// This will leave the original photo in its place.
// This measure is to ensure the photo made it to the new directory so you don't lose it.
// You could go back and delete the photos after if you'd prefer.
}
}
Your MySQL query is ripe for SQL Injection, and your GET statement needs to be sanitized, if I went to your page with something similar to :
pagename.php?id=' DROP TABLE; #--
this is going to end extremely badly for you.
So;
OVerall it's much better to use Prepared Statements. THere's LOTS and LOTS of data about how to use them all over SO and the wider internet. What I show below is only a stopgap measure.
$id = (int)$_GET['id'] //This forces the id value to be numeric.
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = ".$id);
Also keep note of closing your ' and " quotes as your original doesn't close the array key wrapper quotes.
I never used mysqli_fetch_assoc and always used mysqli_fetch_array so will use that as it fits the same syntax :
while($file = mysqli_fetch_array($sfiles)){
$folder = $id //same thing.
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir/".$fileToMove;
//This directory shold always start with Server['DOCUMENT_ROOT'].
//Please read the manual for it.
$newDir = $_SERVER['DOCUMENT_ROOT']."/mypath/to/new/dir/".$folder;
if(!is_dir($newDir)){
mkdir $newDir;
}
// Now the magic happens, copies the file to the new directory.
// Then (optionally) delete the original.
copy($origDir,$newDir."/".$fileToMove);
unlink($origDir); //removes original.
// Add a flag to your Database to know that this file has been copied,
// ideally you should resave the filepath to the correct new one.
//MySQL update saving the new filepath.
}
Read up on PHP Copy and PHP unlink.
And; please use Prepared Statements for PHP and Database interactions.!
this might be a really stupid question but I am getting the following error after the code has successfully deleted the file and I can not work out why, the code is very simple it gets the name and path of the file to be deleted from the database and then deletes it.
Code:
$getFiles = mysql_query("SELECT * FROM tempFiles WHERE pTID='$passedId'");
$numFiles = mysql_num_rows($getFiles);
for ($f=0;$f<$numFiles;$f++) {
$fileName = mysql_result($getFiles,$f,"fileName");
$deleteFile = "../../".$fileName;
unlink($deleteFile);
}
Warning: unlink(../../files/projects/files/643115.jpg): No such file or directory
The script for deleting the file is in a scripts/php/thefile and the file is in files/projects/files/thefile, so the ../../ is definitely needed and not the issue as far as I can tell. I know that the file is being deleted successfully because it is no longer in the folder after I run the script so I have no idea what is causing the error.
Any ideas why I might be getting the error?
Thank you in advance.
Possible causes to the error:
There are more than 1 record in the tempFiles table with the same fileName, so the first attempt removes it and the second causes the error.
The file didn't exists on the folder when you ran the script (as #AxelAmthor said on comment)
To solve it, just add a verification (as #Sammitch said on comment):
if (is_file($deleteFile)) {
unlink($deleteFile);
}
PHP unlink() not working to delete files
my code is deleting in database properly but cant deleted from file how pls help me how to delete data in my uploaded file?
<?php
$id = $_POST['id'];
include_once('db.php');
$objDbCon = new db_connect();
$strSQL = "DELETE FROM study_material WHERE id='$id'";
$objQuery = $objDbCon->Query($strSQL);
unlink('../uploaded/');
if ($objQuery) {
echo "Delete Sucessfully";
} else {enter code here
echo "Error";
}
?>
Use this,
unlink($_SERVER['DOCUMENT_ROOT']).'/projectname'.$filename);
where
$filename is ./folderuploads/filename.extension
unlink() is used to delete files and you try to delete directory using this function ('../uploaded/' is directory not a file). If you want to remove empty directory you need to use rmdir() function instead
The parameter for unlink() function must be a filename rather than a directory.
Try this code:
1:- select file from your table.
2:- unlink file from directory
3:- last delete row from table
unlink('../uploaded/filename');
It's important to make sure that the files/folders have the correct permissions also in addition to the other answers.
PHP usually runs as the user and so if you don't have the correct permissions to manage the file, you won't be able to do anything with it.
In SSH:
chown -R user:user /path/to/folder
This will set all of your files to the user PHP is using. Obviously replace user:user with root:root for example.
I'm currently building a very low level CMS for friend's artist web page that will allow her to upload, edit, and delete images along with designating categories for them and posting news posts about shows and so on.
I'm sure there is a very easy solution to this problem of mine but my inexperience in programming has me left at a loss; so here goes.
The Problem
The problem occurs on a page where the user can delete an image that has been uploaded. Here is the snippet of code where the problem occurs:
// Assign selection to variables in memory...
$img_id = $data["img_name"];
// First, collect the file path to the image being deleted...
$rs = mysql_query("SELECT img_path FROM img_uploads WHERE img_id = '$img_id'") or die(mysql_error());
list($img_path) = mysql_fetch_row($rs);
// Then delete that row from the DB...
mysql_query("DELETE FROM img_uploads WHERE img_id = '$img_id'") or die(mysql_error());
// Now, using the file path collected earlier, delete that file from the server.
unlink($img_path);
// Quickly make sure that the file has been deleted by checking if it exists... if it still exists return error.
if(file_exists($filename)) {
$err[] = "ERROR - There was an error deleting the file! Please try again.";
$_SESSION["errors"] = $err;
header("Location: img_del.php?doDel=failed");
exit();
}
// Scan the directory now that a file has been deleted to see if the dir is empty. If so, delete it. (No use in having empty folders!)
$file_types = array("gif","jpg","png"); // file types to scan for...
$path_parts = pathinfo($img_path); // get the directory from the file path...
$dir = $path_parts["dirname"] . "/"; // assign it to a new variable...
$handle = opendir($dir);
$scan = scandir($dir); // now, scan that directory...
$image_found = FALSE;
for($i=0; $i<count($scan); $i++) {
if ($scan[$i] != '.' && $scan[$i] != '..' && in_array(end(explode('.', $scan[$i])), $file_types)) {
$image_found = TRUE;
}
}
closedir($handle);
if(!$image_found) {
rmdir($dir);
}
I first delete the DB row containing image info, then delete the file from the server. this works fine, however, I also want to check if the directory is left empty after deleting that file. I check if the directory is empty using a loop and if no file is found, I run mkdir(). For some reason it keeps returning an error saying that the directory is not empty
I've searched the web and this site for a solution but I've yet to find one. I'm sure it's out there but I'm having trouble finding it which why I came here. What should I do?
Thanks in advance for any help submitted!
NOTE
I have also checked for hidden files and folders but no luck...
Here is a link to an image that pretty much sums up my problem in a nutshell
Are you sure PHP has permission to delete the file? Since you say you've checked for hidden files, this seems to be the only remaining option. CHMOD 0777 when in doubt (I'd never recommend this usually, but if you're deleting it anyway...), and make sure the folder has the proper owner to let php delete it.