How to unlink image in php - php

i upload image to the server and save the path in data base. Now i want to delete that record and also the image with that record
my code is
$id=$_GET['id'];
$select=mysql_query("select image from table_name where question_id='$id'");
$image=mysql_fetch_array($select);
#unlink($image['image']);
$result=mysql_query("delete from table_name where question_id='$id'");
when i echo $image['image']; this will give me http://www.example.com/folder/images/image_name.jpeg
The record is deleted successfully but the image remains there on server.

You'll have to use the path on your server to delete the image, not the url.
unlink('/var/www/test/folder/images/image_name.jpeg'); // correct
you should remove the # before unlink(), in that case you would have seen the error-message saying "file not found" or something like that.

Simply if you use folder/images/image_name.jpeg in place of whole url inside unlink it will work fine
e.g.
unlink("http://www.example.com/folder/images/image_name.jpeg");
should be replaced with
unlink("folder/images/image_name.jpeg");

you should use the relative path for delete a file from the server with unlink. If you save the absolute path in your database, first you have to see from what folder you delete the image. so if you delete image from "delete.php" that is in www.example.com/folder/delete.php than you should do something like this:
$db_path = "http://www.example.com/folder/images/upArrow.png";
$len = strlen("http://www.example.com/folder/");
$new_path = substr($db_path, $len, strlen($db_path)-$len); echo " -> ".$new_path;
if(isset($_POST['Submit'])){
$return = unlink($new_path);
if($return){echo "Succes";}else{echo "Fail";}
}

whenever you select the your code in delete link.
like:<a href=addproduct.php?action=delete&pid=$get_info[pid]>Delete</a>
then you have to check the condition using cuurent select item.
if(isset($_GET['action']) && $_GET['action']=='delete' && isset($_GET['pid']))
{
$query1=("select * from tablename where id='".$_GET['id']."'");
$result1=mysql_query($query1);
while($data=mysql_fetch_array($result1))
{
$delete=$data['file'];
unlink("../upload/$delete");
}
$query=("delete from tablename where id='".$_GET['id']."'");
$result=mysql_query($query) or die("not inserted". mysql_error());
if($result==TRUE)
{
$_SESSION['msg']="product successfully deleted";
header("Location:addproduct.php");
exit;
}
else
{
$_SESSION['msg']="error in deleting product";
header("Location:addproduct.php");
exit;
}
}

//http://www.example.com/folder/images/image_name.jpeg
define("BASE_URL", DIRECTORY_SEPARATOR . "folder" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$folder_upload = "images/";
$image_delete = ROOT_PATH . $folder_upload . pathinfo($image['image'], PATHINFO_BASENAME);
if (!empty($image['image'])) {
/* Delete */
if (unlink($image_delete)) {
echo "<b>{$image_delete}</b> has been deleted";
} else {
echo "<b>{$image_delete}</b> error deleting ";
}
} else {
echo "File image not exist";
}
// http://localhost/folder/images/image_name.jpeg

Related

What's wrong?, I want to copy the image file to my other directory after upload, and input it to the mysql database too

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

Uploading 1000 images via url using PHP

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

PHP unlinking not working with variable

Going out of my mind with php unlinking
Here is my delete file script
$pictures = $_POST['data'];
//print_r ($pictures);
$imageone = $pictures[0];
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/" . $imageone;
echo $filename;
if (is_file($filename)) {
chmod($filename, 0777);
if (unlink($filename)) {
echo 'File deleted';
} else {
echo 'Cannot remove that file';
}
} else {
echo 'File does not exist';
}
The above does not work, error response is file does not exist
however if i change the filename path to this (the echo data from the echo above)
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/1420291529-whitetphoto.jpeg "
works fine and deletes the image.
Why can i not use the $imageone variable?
Do a print_r($pictures) to see if $pictures[0] is indeed the filename you're looking for.
Also note that if $pictures[0] is "//windows/*" you'll loose your windows if the user running PHP has administrative rights... so just using $pictures=$_POST["data"] is very VERY unsafe!

How to delete a file from upload folder

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

Tying in unlink() with sql delete

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.

Categories