I wrote a PHP script to delete files selected in a gridview. This is the first time I've done this. The script works fine on my local development machine but I don't know if this is the proper way to do it. I'd like to find out what possible problems can I run into when deleting files and how can I modify this to prevent problems.
I was looking at this page to get the basic idea: http://www.php.net/manual/en/function.unlink.php
<?php
// get required includes
require_once(ROOT_PATH.'user/controls/snippets/error_messages.php');
require_once(ROOT_PATH.'user/controls/accordion/get_user_name.php');
// ------------------------------------------------------------
// DELETE SELECTED FILES
// ------------------------------------------------------------
if(isset($_POST['delete_file']) && isset($_POST['checked2']))
{
$checked = array_map('intval',$_POST['checked2']);
$delete_list = implode(", ", $checked);
// DB: get file names to delete
$get_file_names = mysqli_query($conn, "SELECT FileName FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
// delete files from server
while($row = mysqli_fetch_array($get_file_names))
{
$dir = DOWNLOAD_DIRECTORY;
$file_name = $row['FileName'];
$file_to_delete = $dir.$file_name;
unlink($file_to_delete);
}
// DB: delete selected file references from db
$delete_selected = mysqli_query($conn, "DELETE FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
$effected_rows = mysqli_affected_rows($conn);
echo "<div class='msgBox2b noBorder'>SUCCESS: ($effected_rows) FILE(S) have been DELETED..</div>";
}
}
elseif(isset($_POST['delete_file']) && !isset($_POST['checked2']))
{
echo $msg_error;
}
?>
Thank you!
Edit: Would it be better this way?
$fh = fopen($file_to_delete, 'w') or die($failed_to_open_file);
fclose($fh);
unlink($file_to_delete);
Not all files can be unlinked because of permissions, so check the return value of that call.
Related
How do I delete a single file from a folder? When I click my delete link, it removes all uploaded files from the folder.
The link:
<td>Delete
The code:
<?php
// Including the database connection file
include_once 'Ad_updbconnect.php';
// Getting Id of the data from url
$Id = $_GET['Id'];
$Del = glob('uploads/*'); // Get all file names
foreach ($Del as $File) {
if (is_file($File)) {
unlink($File); // delete file !
}
}
// Deleting the row from table
$Result = mysqli_query ($Con, "DELETE FROM ibgsec_uploads WHERE Id=$Id");
$Row = mysqli_fetch_array($Result);
// Redirecting to the display page.
header("location: Ad_uploads.php");
?>
This is the only thing left I'm working on, I've tried lots of ways to properly execute the command but it does not work.
Your code explicitly deletes every file in uploads. What did you expect?
$Del = glob('uploads/*'); // Get all file names
foreach ($Del as $File) {
if (is_file($File)) {
unlink($File); // delete file !
}
}
Is $Id a file name? Seems risky but all the same you would want to try comparing that to $File. Compare something to $File otherwise you're just deleting them all.
You also are naming your param in the link $Id: <a href="Ad_delete.php?$Id=<?php echo $Row['Id'];?>" but fetching it as Id: $Id = $_GET['Id'];. Then you open yourself up to SQL injection by including that in the database query.
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
I'm not quite sure where the problem lies.
But the code won't unlink the file :(
<?php include_once("sessions.php");
require_once("connect.php");
if(isset($_POST['delete'])){
$album_id = $_SESSION['album_id'];
$checkbox = $_POST['photo_checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
$query = "SELECT * FROM media WHERE id = $id";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($result)){
$file = $row['path'];
if(!unlink($file)){
$_SESSION["edit_message"] = "<br>Something went wrong while deleting shit ... please try your editing again." .$file;
header ("Location: ../fotos.php?album=".$album_id."");
exit;
}
}
$query = "DELETE FROM media WHERE id = $id";
$result = mysqli_query($connection, $query);
}
}
if($result){
$_SESSION["edit_message"] = "<br>Successfully deleted !";
header ("Location: ../fotos.php?album=".$album_id."");
exit;}
}
?>
If I take out the unlink loop part and just go straight to the deleting from the db it works fine.
What am I missing?
Might it be the permissions that are hindering the code from executing ?
EDIT :
Changed the permissions of the file to 0777 now. So it should really work ...
But still doesn't seem to. ! :/
I have no ideas now.
Maybe the loop isn't working properly ?
Thanx for your help
Cheers
Chris
$file2 = chmod($file, 0777);
if(!unlink($file2)){
$file2 is getting the return value of chmod, which is a bool. You're then trying to unlink a true/false value. Perhaps you meant to unlink($file) ?
Edit to reflect your changes:
If $file is not a fully qualified path name $file will be relative to the current working directory of where ever the script is running from. Ensure $file is a full path name.
Write permissions on the file are not sufficient you need write permissions on the directory itself to be able to delete a file within it.
You should first check the file exists, you should then check that you have the correct permissions on the directory NOT the file.
if(file_exists($file) && is_writeable(dirname($file))){
unlink($file);
}else{
//invalid path or permission problems
}
I have to delete a file from the database and also to delete the file from the folder which is stored in server as files(folder)/newsletter(subfolder)/file1 using php.Iam using following code,the file is deleting from the database,but its not deleting from the folder,..plz help,thanks in advance.
my code is..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from newsletters where id=$id");
$results = mysql_fetch_array($sql);
if ($results["file"] != "") {
$image = $results["file"];
unlink('../files/newsletter/' . $image);
}
$sql = "delete from newsletters where id=$id";
$result = #mysql_query($sql);
if ($result) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('msg' => 'Some errors occured.'));
}
?>
Take care of this path "../files/newsletter/" should mention correct path and if your server is ubuntu based then change permissions to files ,newsletter folders.
I want to delete the image from the storage folder at the time of deleting from the database also.
The image file is getting deleted from database but unable to delete from server storage folder.
The image is getting stored in http://url.com/foldername/files/newsletter
The below is the code i used..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from tablename where id=$id");
$results=mysql_fetch_array($sql1);
if($results["file"]!="") {
$image=$results["file"];
unlink("../files/newsletter/".$image);
}
$sql = "delete from tablename where id=$id";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array('success'=>true));
} else {
echo json_encode(array('msg'=>'Some errors occured.'));
}
?>
Plz help in resolving..Thank you
try to add document root with your code to something like code below.
$imageWithPath = $_SERVER['DOCUMENT_ROOT']."/files/newsletter/".$image;
#unlink($imageWithPath);
Can you print out what your $results["file"] value is and check.
You are using mysql_fetch_array it should be inside while loop
$sql1 = mysql_query("select * from tablename where id=$id");
while($row = mysql_fetch_array($sql1)){
$image = $row["file"];
//make sure below path is correct.
$image_path = $_SERVER['DOCUMENT_ROOT'].'/foldername/files/newsletter/'.$image;
echo $image_path;//you can compare if the path is correct or not
//Also check if file exists here
if(file_exists(image_path)){
unlink($image_path);
}
else{
echo 'file doesnot exist';
}
}
Also you will need to have permissions to be able to delete the file. Make sure the apache or user that runs your script file have correct permission or ownership of the file.