Problem with updating and unlinking old image PHP - php

So problem is that I created 2 methods to set files and check the image if there is an image in tmp, it should delete the old image before moving a new one. But when I upload an image, unlink gives an error like this unlink(\Users\Murat\Desktop\xampp\htdocs\new\usersimages\42\1593769114256123131.jpg): No such file or directory in this number belongs to what I uploaded not the old image.
It moves a new image to the folder and try to delete new image but not delete old. this is the main problem. Probably I do a mistake but can't find where. The codes are below.
public function set_file($file){
$this->image = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
$this->image = preg_replace('#[^a-z.0-9]#i', '', $this->image);
$kaboom = explode(".", $this->image); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$this->image = time().rand().".".$fileExt;
}
public function checkPhoto($user_id){
global $database;
if(!empty($this->tmp_path)) {
$path = $this->upload_directory.$user_id.DS.$this->image;
unlink($path);
move_uploaded_file($this->tmp_path,
$path);
// unlink("album_uploads/$this->image");
} elseif (empty($this->tmp_path)) {
$sql = "SELECT * FROM users WHERE user_id = :user_id ";
$query =$database->query($sql, [':user_id'=>$user_id]);
$row = $query->fetch();
$this->image = $row['image'];
$this->type = $row['type'];
$this->size = $row['size'];
} else {
$this->errors[] = "Unexpected error please try again after refresh the page!";
}
}

So I added this part in the checkphoto method and it works now. if I did a mistake please let me know who can have more knowledge.
public function checkPhoto($user_id){
global $database;
$sql = "SELECT * FROM users WHERE user_id = :user_id ";
$query =$database->query($sql, [':user_id'=>$user_id]);
$row = $query->fetch();
$path = $this->upload_directory.$user_id.DS;
if(!empty($this->tmp_path)) {
$this->image = $row['image'];
if (file_exists($this->image)) {
unlink($path.$this->image);
}
// unlink("album_uploads/$this->image");
} elseif (empty($this->tmp_path)) {
$this->image = $row['image'];
$this->type = $row['type'];
$this->size = $row['size'];
} else {
$this->errors[] = "Unexpected error please try again after refresh the page!";
}
}

Related

How to save an image to the database with a path file

I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.

how to upload image using php function

This is my code. I tried to upload an image using this PHP code. $mainCName, $mainCImage save in the database. But, the image does not upload to the uploadedimage folder. Can you help me please?.
public function add_main_category($mainCName, $mainCImage){
$query = "SELECT * FROM mainCategory WHERE mainCName='$mainCName'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
if($count_row == 0){
$imgfile=$_FILES["$mainCImage"];
$extension = substr($imgfile,strlen($imgfile)-4,strlen($imgfile));
$allowed_extensions = array(".jpg",".jpeg",".png",".gif");
if(!in_array($extension,$allowed_extensions))
{
echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
}
else{
$imgnewfile=md5($imgfile).$extension;
move_uploaded_file($_FILES["mainCImage"]["tmp_name"],"uploadedimage/".$imgnewfile);
}
$query = "INSERT INTO maincategory(mainCName,mainCImage) VALUES('$mainCName','$mainCImage')";
$result = $this->db->query($query) or die($this->db->error);
return true;
}
else{return false;}
}

Use a variable from one IF - Statement into the other IF - Statement in PHP

I have a variable $target inside an IF - Statement in my login.php. I created the folders and sub-folders based on this variable. Now i want to move the uploaded file to this location. How can I do that?
here is the code
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
}
else if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
//$target4 = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
else
{
echo "asdfg";
}
Userid and Pid comes from login.html and Image value comes from upload.html
Nest the else-if as an if in the first if. Otherwise it won't be executed.
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
}
$upload = "Your desired location";
//comes from the login.html page
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "Whatever coloumn you wish to echo from database".'<br/>';
echo $row['col1'].'<br/>'.'<br/>';
echo "Second Coloumn".'<br/>';
echo '<a href="upload.html"/>'.$row['col2'].'</a>'.'<br/>';
//create the folders and subfolders based on the data from the database
$target = $upload.'/'.$row['col1'].'/'.$row['col2'].'/'.$row['col3'].'/'.$row['col4'].'/'.$row['col5'].'/';
//for renaming the image.
$imagename = $row['col1'].'.'.$row['col2'].'.'.$row['col3'].'.'.$row['col4'].'.'.$row['col5'].'.'.'jpg';
//create the folders and subfolders
if(!file_exists($target))
{
mkdir($target,null,0777);
}
//start session and store the value of $target and $imagename in a variable
session_start();
$_SESSION['str'] = $target;
$_SESSION['img'] = $imagename;
//This comes from other HTML page but to the same PHP.
if(isset($_FILES['image']))
// image upload from upload.html
// Want the value of target here.
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
//Move the uploaded file to the desired location.
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Successful";
Hope this would be helpful for all.

Update a record by taking an id from the url

Hello everyone i'm taking a value from a URL by get and pass it into an update statement, when i put WHERE ID= 1 , it work fine but when i put the ID=$id, the code work but there is no update, the record remain the same, can some help me to resolve this problem please
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
if (!empty($_POST) ) {
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
echo"error";
}
How about this:
$id = strip_tags(intval($_GET['id']));
mysqli_query($dbc,"UPDATE `movie` SET `Title`='{$title}', `Year` =
'{$year}', `Cast`='{$cast}',
`Cover`='{$actual_image_name}',`Tag`='{$tag}', `Comment`='{$comment}',
`IMDB` ='{$IDBM}' WHERE `MovieID`='{$id}';");
To verify if $id have same value:
echo $id;
It sounds like maybe your MovieID isn't defined as an integer but we can't tell for sure because you haven't told us the error message that mysqli_query is throwing.
You need to be checking the error message created by mysqli_query to know. See http://www.php.net/manual/en/mysqli.error.php
try this
$id = $_GET['id']; // taking the value from URL
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id); // the sql statement of the query
and best you protect the get by using intval() to prevent injections
$id = intval($_GET['id']); // taking the value from URL

Unexpected result after file upload

This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.

Categories