PHP & MySQL delete image link problem - php

I'm trying to create a delete image link if the image is present and when the user clicks the delete image link it should delete the image. But for some reason this is not working can someone help me fix the delete image link problem? Thanks!
Here is the PHP code.
if (isset($_POST['delete_image'])) {
$img_dir = "../members/" . $user_id . "/images/thumbs/";
$img_thmb = "../members/" . $user_id . "/images/";
$image_name = $row['image'];
if(file_exists($img_dir . $image_name)){
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli, "DELETE FROM users* WHERE image_id = '.$image_id.' AND user_id = '$user_id'");
}else{
echo '<p class="error">Sorry unable to delete image file!</p>';
}
}
}
if(isset($_POST['image']) || !empty($image)) {
echo 'Delete Image';
}

"DELETE FROM users* WHERE image_id = '.$image_id.' AND user_id = '$user_id'"
should be
"DELETE FROM users WHERE image_id = $image_id AND user_id = $user_id"
This is assuming $image_id and $user_id are both integers. If they're strings, put the single quotes around them.
Also, double check your link:
Delete Image
Is the user really passing in the link via POST?
Your code is vulnerable to SQL injection attacks. Please consider using parametrized queries.

"DELETE FROM users WHERE image_id = $image_id AND user_id = $user_id"
And also
$path = "Your Image folder Path";
$image_name = "Your Image Name";
unlink($path."$image_name);

Related

PHP / MySQL: Rename $_FILES['image']['name'] base on id

can anyone help me to solve my problem? Currently, I created a system that can upload a photo and the function successful. but the name of the photo that saves to the database and also at the server folder is the actual name of the photo.
Now, I want to rename the photo based on id. Below is my code:
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$image = $_FILES['uploadFile']['name'];
// image file directory
$target = "../../../../images/upload/".basename($image);
$ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$image";
// Prepare an insert statement
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Attempt to execute the prepared statement
if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
// Records created successfully. Redirect to landing page
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
?>
Try this code
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$image = $_FILES['uploadFile']['name'];
//set new name for upload image
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $report_id. '.' . end($temp);
$target = "../../../../images/upload/".$newfilename;
$ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$newfilename";
// Prepare an insert statement
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Attempt to execute the prepared statement
if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
// Records created successfully. Redirect to landing page
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
?>
Change one line of your code
$target = "../../../../images/upload/".$report_id . '.'. pathinfo($image, PATHINFO_EXTENSION);

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> ';
}

Android PHP - Upload photo to mySQL using UPDATE

I have an android app that will upload a photo to mysql database. This photo serves as a profile photo. Which means I must UPDATE the existing row of the user.
Table - user
Columns - id, name, photo, schoolid, password
Using the id of the user, he will upload the photo in his row.
I followed this tutorial.
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
This is the script.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$schoolid = $_POST['schoolid'];
$photo = $_POST['photo'];
require_once('dbConnect.php');
$sql ="SELECT schoolid FROM user WHERE schoolid = '$schoolid'";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($res)){
$schoolid = $row['schoolid'];
}
$path = "uploads/$schoolid.png";
$actualpath = "http://192.168.0.20/quizmaker/$path";
$sql = "UPDATE user SET photo = '$actualpath' WHERE schoolid = '$schoolid'";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($photo));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
In my android.
String photo = getStringImage(bitmap);
Map<String,String> params = new Hashtable<>();
params.put("photo", photo);
params.put("schoolid", schoolid);

PHP upload video files to database

I am working on a school project that let users upload video files to a server. Server will compress the video using ffmpeg and store the file in upload folder. Other users will be able to stream the uploaded videos.
My question is how do i retrieve the video that ffmpeg generated and store the link in the database?
i am using this code but it only retrieve path of the original video.
$filePath = dirname(__FILE__);
partial code of Upload.php
$target_dir = "upload/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
$unique_id = rand(1000000,9999999);
shell_exec("C:\\ffmpeg\\bin\\ffmpeg.exe -i ".$newFileName." -vcodec libx264 -crf 20 \"upload\\{$newFileName}\" > logfile.txt 2>&1");
/// save information into database
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "test_database";
//connect to the database
$dbc = mysqli_connect($hostname, $username, $password, $dbname) or die ("could not connect to the database");
//execute the SQL query and return records
$result = mysqli_query($dbc, "INSERT INTO `viewvideo` (`vID`, 'video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."')");
if(!$result){echo mysqli_error($dbc); }
echo $result;
/*
declare in the order variable
$result = mysqli_query($dbc, $sql); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
*/
//close the connection
mysqli_close($dbc);
output
Remember to move the uploaded file to a directory of your choice. A way to prevent files overwriting each other is creating a new name for it. Do this when the upload is a success.
Properly uploading & adding the video to the database
$target_dir = "video/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
After that you'll have to create a table & insert two core things; a unique/token generated ID for the video and the $newFileName path.
You can either use a function which generates a token/id which includes alpha-numeric characters or something simple as this
$unique_id = rand(1000000,9999999);
Lets consider you have a table videos with 3 columns; vID, video_id & video_link
vID should be an auto incrementing INT. video_id would be a INT and the video_link a TEXT type.
After that it's SQL.
$result = mysqli_query($db_connection, "INSERT INTO `videos` (`vID`, video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."'");
if(!$result){echo mysqli_error($db_connection); }
Retrieving it would be something like this. Be sure to add this on another page. Let's consider stream.php as the page's name for streaming the video.
if(isset($_GET['id'])){
$id = trim($_GET['id']);
//check if it exists
$result = mysqli_query($db_connection , "SELECT `video_id`, `video_link` FROM `videos` WHERE `video_id`='".$id."'");
$count = mysqli_num_rows($result);
//does it exist?
if($count>0){
//exists, so fetch it in an associative array
$video_arr = mysqli_fetch_assoc($result);
//this way you can use the column names to call out its values.
//If you want the link to the video to embed it;
echo "Video Link: ".$video_arr['video_link'];
}else{
//does not exist
}
}
And finally, creating a link to it: http://your-website.com/stream.php?id=video id here

Struggling to display blob image with php

I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];

Categories