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.
Related
this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission
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 am trying to delete a photo from upload folder when i press delete all records are deleted except the picture in upload folder here is my delete, how to i code the snippet to delete from upload folder
//trigger
<?php
echo '<td><a href="delete.php?staff_id=' . $row['staff_id'] . '"><input type="button" onclick="confirmDelete(event)" value="delete">';
// check if the 'staff_id' variable is set in URL, and check that it is valid
if (isset($_GET['staff_id']) && is_numeric($_GET['staff_id']))
{
// get staff_id value
$staff_id = $_GET['staff_id'];
// delete the entry
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id") or die(mysql_error());
}
In your delete.php script you would need a line like this :
unlink( "path_to_your_upload_directory/".$staff_id.".jpg" );
If you have various file extensions : One way to achieve it is to first save the filename with extension in an appropriate database table when the user/staff uploads the file . Retrieve the same and use it when deleting the file :
$filename_with_extension = 'retrieve this from database table where it is stored';
unlink( "path_to_your_upload_directory/".$filename_with_extension );
unlink() function in PHP. You have to provide full path to that file in parameter.
NOTE: Do not give http:// path.
Use unlink function. This will remove a file from the specified directory
if(isset($_GET['staff_id'])&&is_numeric($_GET['staff_id']))
{
$Staff_Id = mysql_real_escape_string($_GET['staff_id']);
if($Staff_Id != '.' || $Staff_Id != '..')
{
$extension = '.jpg';
if(unlink('uploads/'.$Staff_Id.$extension))
{
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id")or die(mysql_error());
}
}
}
I have setup a simple while loop which returns all images in a table along with their respective title and description so that users can update the details accordingly for each image.
The images are returned with a checkbox which allows user to delete images as per php code
if($_POST['doDelete'] == 'Delete') {
if(!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
}
}
$ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];;
header("Location: $ret");
exit();
}
How do I incorporate the unlink() function into the page so that the file is also removed from the server?
Just use Unlink() with in loop like :
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
if(mysql_query("delete from landscape where id='$id'")){
unlink( '/path/to/images/' . $id);
}
}
I have used If because if the file deleted successfully from the database only then it will be deleted from the server.
Also If you have moved the file into folder by the name of file then First get information about file from database by $id and then use
unlink( '/path/to/images/' . $file_name);
instead
unlink( '/path/to/images/' . $id);
Hope it will help you.
If the images are named in accordance with the ID:
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
unlink( '/path/to/images/' . $id);
}
Be sure to properly escape $id before using it in your query or in the unlink statement.
Well, where are the files stored on the server? How are they stored? Just call unlink with the file path that leads to where the image is stored.
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.