How to delete an image from the database and folder in PHP - 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

Related

how i insert image name in current logged in user's account?

When i am using this script image name inserted in all user's row. how can i insert in current session user's line
auth.php
<?php
session_start();
if(!isset($_SESSION["username"]) ){
header("Location: login.php");
exit(); }
?>
home.php
<?php
include("php-includes/auth.php");
//Include database configuration file
include_once 'php-includes/dbConfig.php';
//Get current user ID from session
$userId = $_SESSION["username"];
//Get user data from database
$result = $db->query("SELECT * FROM user WHERE username = $userId");
$row = $result->fetch_assoc();
//User profile picture
$userPicture = !empty($row['picture'])?$row['picture']:'no-image.png';
$userPictureURL = 'uploads/images/'.$userPicture;
?>
Just two modifications and you are done:
1) You have to get current user's name from session
$userId = $_SESSION['username'];
2) Add single quote to the username value in query.
$update = $db->query("UPDATE user SET picture = '".$fileName."' WHERE username = '$userId'");
As a note:
If you are providing a value to database query, if it is non-numeric,
you need to add single quotes to it.
This tells that the passed string is a value and not any MySQL
reserved word/Database name/Table name/Field name.
When user logged in on that you must keep their username in session for that you can use code something like given below...
<?php
session_start();
//retrive username from database and then save in session
$_SESSION['username'] = $username;
And when you reach to this script where you need to insert the image for that user
Here can get the username from a session like given below...
session_start();
$userId = $_SESSION['username'];
And then use it in your MySQL query
$update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");
Also, keep in mind when you are using a double quote (") for the database query then you don't need to use dots around variable name. The rather single quotation mark is enough
The complete code is given below...
if(!empty($_FILES['picture']['name'])){
//Include database configuration file
include_once 'php-includes/dbConfig.php';
//File uplaod configuration
$result = 0;
$uploadDir = "uploads/images/";
$fileName = time().'_'.basename($_FILES['picture']['name']);
$targetPath = $uploadDir. $fileName;
//Upload file to server
if(#move_uploaded_file($_FILES['picture']['tmp_name'], $targetPath)){
session_start();
//Get current user ID from session
$userId = $_SESSION['username'];
$update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");
//Update status
if($update){
$result = 1;
}
}
//Load JavaScript function to show the upload status
echo '<script type="text/javascript">window.top.window.completeUpload(' . $result . ',\'' . $targetPath . '\');</script> ';
}

Issues with loading image blob in a separate script

I want to load image, but the solution that I can get so far is loading a separate script with db - reconnection.
I have a init.php file which basically start up the application with db connection.
looks something like this.
if(!isset($_SESSION)){
session_start();
}
//error_reporting(0); //dont show path name errors when error occurs
// include required files
require 'databases/connect.php';
I have this line of code which tells the blob script to retrieve image Data
<img src="../core/functions/images.php?image_id=<?php echo $responses[$i]['product_id']; ?>" height="150" width="180" alt=""/>
And this is the problem script that re-connect db again and then retrieve the image data. If I do not reconnect the db, the mysql script will fail. Any help on this, so I don't need to reconnect db?
$connect_error = "Sry, we are working on an error, try later";
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('SJ3') or die($connect_error);
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
?>

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!

Preventing overwrite of file upload and MySQL record through form?

I have a submission system set up and I'd like to have it so no duplicate entries can be submitted. If one is submitted, the ORIGINAL record and file upload is kept (not overwritten). Also, if it exists I'd like the form to display an error to the user. Here's my upload.php (referred to in the HTML form).
upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
// Connects to your Database
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `Table` VALUES ('$fname', '$lname', '$snumber', '$grade', '$email', '$target')") ;
//Writes the upload to the server
if(move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
//Tells you if its all ok
echo "Your submission ". basename( $_FILES['uploadedfile']['name']). " was successful and we have received your submission. Your result will be sent to $email ";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
How would I go about doing this?
EDIT: Combined suggestions from below, here's updated code however now I'm getting a Parse error: syntax error, unexpected T_ECHO in /path/to/upload.php on line 32
New upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
//Checks if submission already exists
if(file_exists($target))
{
echo "This submission already exists. Please check that you have entered all values correctly. If this is an error please contact support";
}
else
{
//Now that file doesn't exist, move it.
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
//MYSQL CONNECTION
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//MYSQL Entry
mysql_query("INSERT INTO Table (fname, lname, snumber, grade, email, target) VALUES ('".mysql_real_escape_string($fname)."', '".mysql_real_escape_string($lname)."', '".mysql_real_escape_string($snumber)."', '".mysql_real_escape_string($grade)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($target)."')")
echo "Your submission was successful and we have received your portfolio. Your marks will be sent out to $email.";
}
?>
Looks like you're storing the target in your database, so you can either check the database to see if that file already exists or you can use php's file_exists() function.
DB you obviously run the query before that insert statement and make your conditional based off the results.
Otherwise,
if(file_exists($target))
{
echo 'error';
}
else
{
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
// do success things here
}
file exists may require the full path. If it doesn't work right away see if prepending $_SERVER['DOCUMENT_ROOT'] helps.
I have solved this issue by applying an ajax query before submitting the form and the file
var param = "action=testfile&dirpath=" + dirpath + "&file=" + filename;
$.ajax({
type: "GET",
url: 'combi/testfile.php',
data: param,
success: function(data) {
test data .... if OK submit.
}
In testfile.php you test for the file and echo out the data
if($_GET['action'] == 'testfile'){
$msg = '';
$basedirpath = $_GET['dirpath'] . "/";
if(file_exists($basedirpath . $_GET['file'])) {
$msg = 'exists';
}
echo $msg;
}
$msg is returned in the data in the ajax call.

Image upload in a database directory

i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line
upload.php
<?php
include("connecton.php");
$_SESSION['username']="kyle";
$username = $_SESSION['username'];
if($_POST['submit'])
{
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name)
{
//start upload process
$location = "avatars/$name";
move_uploaded_file($tmp_name,$location);
$query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");
die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
}
else
die("Please select a file");
}
echo "Welcome, ".$username."!<p>";
echo "Upload Your Image:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>
</form>
";
?>
view.php
<?php
include("connecton.php");
$username = $_SESSION['username'];
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
die ("User not found");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
echo "<img src='$location' width='100' height='100'>";
}
?>
a) You do not check if the upload succeeded. At least do something like:
if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
... upload went ok
}
b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.
c) You do not check of the move_uploaded_file() succeeded:
if (!move_uploaded_file(...)) {
die("Move failed!")
}
d) You do not check if the database query succeeded:
$stmt = mysql_query(...)
if ($stmt === FALSE) {
die("MySQL query failed: " . mysql_error());
}
e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.
f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.
First php statement of both of upload.php and view.php should be this:
session_start();

Categories