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());
}
}
}
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 have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>
Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.
The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy
So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help
I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);
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.