How to delete an image from a folder in PHP - php

I'm trying to delete an image from data base as well as from a folder in PHP5, but I am unable to delete it. Here is my code:
<?php
$obj=new Crud("localhost","root","","3g");
class Crud{
public $mysqli;
public $data;
public function __construct($host,$username,$password,$db_name) {
$this->mysqli = new mysqli($host, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
} /*else{
echo"Your Database successfully connected";
}*/
}
public function __destruct() {
$this->mysqli->close();
}
public function read() {
$query="SELECT * FROM fashion";
$result= $this->mysqli->query($query);
$num_result=$result->num_rows;
if ($num_result>0) {
while($rows=$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function delete($id){
$query="DELETE FROM fashion WHERE id='$id'";
$result= $this->mysqli->query($query) or die(mysqli_connect_errno() . "Data cannot inserted");
if ($result) {
header('location:fashion.php');
}
}
}
?>
By using the above code, the record was deleted only from database, but the image remains in the folder.

To delete an image from your folder you have to use unlink
$file = "yourimage.jpg";
unlink($file);
if image is in any other directory you have to specify full directory Path like
$file = "www/images/yourimage.jpg";

The solution you are looking for is the unlink function which does that - unlinks and deletes a file.
You need the name of the file and the path to the file from the PHP current working directory to make it work. Kamrans answer shows this.
So:
public function delete($id){
$query = "SELECT filepath FROM fashion WHERE id = ? LIMIT 1";
$fileLocale = $this->mysqli->prepare($query);
$fileLocale->bind_param("i",$id);
$fileLocale->execute();
$result = $fileLocale->get_result();
$fileLocale->close();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
/***
* only 1 result is returned so easy to collect
***/
foreach ($row as $r)
{
$filepath = $r;
}
}
unset($r,$row);
/***
$filepath is now the string of the location of the file.
***/
if (unlink($filepath)){
$query="DELETE FROM fashion WHERE id=? LIMIT 1";
$delete = $this->mysqli->prepare($query);
$delete->bind_param("i",$id);
$delete->execute();
$affectedRows = $delete->affected_rows;
if ($affectedRows == 1) {
header('location:fashion.php');
die();
}
when using header always place a die command after it.
use unlink to delete a file, it will return TRUE on success.
filepath is the column in your database that you store the file location.
connect and use the database using OOP principles, use prepared statements rather than queries, there is FAR less risk to you or your code.
Add LIMIT to your SQL statements so if there is an issue, it will not mess up your whole table, for example. A safety measure.

Before you delete the database reference, use it to fill the file name, which is what I am assuming is stored in the database. If $id is the file name, just add it into a system command to remove the file. This assumes Linux.
public function delete($id){
exec('rm /path to file/' . $id);//delete the file via system command.
$query="DELETE FROM fashion WHERE id='$id'";
$result= $this->mysqli->query($query) or die(mysqli_connect_errno() . "Data cannot inserted");
if ($result) {
header('location:fashion.php');
die();
}
}

Related

Querying image from MySQL server results in corrupt file

I am running into an issue when querying an Image that is stored as a longblob from a MySQL. I understand that this is not an optimal way to do this, but it is a requirement for the project I am working on.
The server that is running on my local machine is running and querying the data properly, but the live server doesn't return the images properly (the browser believes that the file is corrupted). The code is the same on both devices. The returned longblob from the server has the same sum as the files that was created on the local environment (both files have the same data in theory).
Are there any settings that could be enabled that would cause this to fail on a live server vs a local environment?
Simplified code for creating the image in the database
$productImage = "images/" . time() . $productImageImage["name"];
move_uploaded_file($productImageImage["tmp_name"] , $productImage);
$productImageImage = file_get_contents($productImage);
$query = $connection->prepare("INSERT INTO product (productImage) VALUES (?)");
$query->bind_param("s", $ProductImageImage);
$result = $query->execute();
Code for displaying the file
<?php
header("Content-Type: image/jpeg");
include 'include/db_connection.php';
function getId(){
if(isset($_GET['id']))
$selected = $_GET['id'];
return $selected;
}
function alt_getImage($connection){
$s = getId();
$query = $connection->prepare("SELECT productImage FROM product WHERE productId = ?");
$query->bind_param("i", $s);
$query->execute();
$result = $query->get_result();
return $result;
}
function createImage($connection, $id){
if ($id != null){
$result = alt_getImage($connection);
$row = $result->fetch_assoc();
echo $row["productImage"];
$connection->close();
}
}
$id = $_GET['id'];
$connection = createConnection();
createImage($connection, $id);
?>

How to delete an image from the database and folder in PHP

I have PHP code that I am trying to delete the image from the database and uploads folder as well. I have researched and it seems
like I need the unlink option but I don't know enough about PHP or
coding on how to implement it. The code I have will delete from the
MySQL database just fine but when I try to add the uplink code it
breaks it and doesn't do anything.
I have tried adding in the following:
$file_path = 'uploads/' . $_POST["images"];
if(unlink($file_path))
to the code below.
//start PHP session
session_start();
if (!isset($_SESSION['success']))
{
header("Location: login_page.php");
die();
}
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
$file_path = 'uploads/' . $_POST["image"];
if(unlink($file_path))
{
// delete query
$query = "DELETE FROM dhospital WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_id']);
}
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Record was deleted.";
}else{
echo "Unable to delete record.";
}
}
I am using PHP - PDO - MySQL

How to COUNT the number of times a FILE from my database has been downloaded?

I am new to this and I am having problems trying to get my website to count the number of times a files has been downloaded. The website has download buttons linking to the files which are stored on my database, and I would like to be able to count the amount of downloads per file to display as a statistic, ideally once they click the link to download, the column in the files table should be incremented, but I cannot wrap my head around it. please help?
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username= $_SESSION['username'];
?>
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('dragon.kent.ac.uk', 'repo', '3tpyril', 'repo');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `files`
WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No files exists with that ID.';
}
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
The download link would point to a php file, such as download.php?id=123 -- this file would then take the ID and check the downloads database. If the ID exists, you run a query such as UPDATE files SET downloads = downloads + 1 WHERE id = 123.
Afterwards, you set the headers using header() to set content-type. Then use readfile().
See How to force file download with PHP on how to set headers and force a download.
Cheers!

Cannot remove image using unlink, are my permissions wrong?

I'm trying to use unlink to delete pictures from deleted comments but it's simply not working. The comment from the database gets deleted but the actual picture doesn't. What am I doing wrong? The folder permissions are 755 and the image permissions are 644.
if (loggedin()) {
$dblink = mysqli_connect($DBhostname, $DBusername, $DBpassword, $DBname);
if (!$dblink) {die("Connection error (".mysqli_connect_errno.") " . mysqli_connect_error());}
$commentid = mysqli_real_escape_string($dblink, $_GET['c']);
$qry = "SELECT * FROM comments WHERE id='$commentid' LIMIT 1";
$result = mysqli_query($dblink, $qry) or die(mysqli_error($dblink));
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$commenter = $row["commenter"];
$thereisimg = $row["thereisimg"];
$imgtype = $row["imgtype"];
// if logged in email = email of commenter
if ($_SESSION["logged-in"] == $commenter) {
// delete comment
$qry = "DELETE FROM comments WHERE id=$commentid";
$result = mysqli_query($dblink, $qry) or die(mysqli_error($dblink));
// if image, delete image
if ($thereisimg) {
// delete image
$imglink = "/imgs/commentpics/".$commentid.".".$imgtype;
echo $imglink;
unlink($imglink);
}
}
}
}
To diagnose, try one of the following:
Add an error handler to the PHP code to capture the error
Use strace to trace the process and get the exact result of the unlink() system call
Here's a document for (1): http://www.w3schools.com/php/php_error.asp.
To do 2:
strace -e unlink php myScript.php
That assumes the script can be run directly from the command line.
Setting an Error Handler
<?php
function my_error_handler($error_level,$error_message,
$error_file,$error_line,$error_context)
{
echo $error_message;
}
set_error_handler("my_error_handler");

PHP code included in HTML won't update

I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.

Categories