I am working with php on my localhost server. I want to unlink the image from my server folder whenever I change the image when edit. The picture is changing when I update but the past picture stays in folder.
if (isset($_POST['update'])) {
$image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if (!empty($image)) {
$del_is = $_GET['deleteUser'];
$sql = "SELECT * FROM users WHERE id = '$del_is'";
$del_user = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($del_user)) {
$user_image = $row['image'];
}
unlink("dist/img/users/$user_image");
}
Related
I have an image upload index for a project. An link to the image is created and saved to a phpMyAdmin DB and the image is supposed to save to my /image folder in the project files. The index saves the link/directory access in the DB but the image itself is not saved. So essentially I have a link to an empty image in my image folder!
I had no issues with the code until I moved from a localhost to a blacknight server.
Any suggestions would be greatly appreciated.
I have tried using BLOB instead of TEXT for images in the database and that has not worked.
I have given permissions to access that for Read/Write in FileZilla.
I have corrected all the DB connections and file paths.
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I expected that this line would submit the file into the /images folder
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
No need of specifying full path to folder
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "./images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
I have a system that allows user to upload PDF files and save the name of the file on the database.
How can I make this script works so user can delete all files from server whose name is not in my database?
This is what I actually have, but the script deletes all files. I don't know how to proceed.
<?php
include 'fimg.class.php';
require('../../../php/cone.php');
//header('Location: ../produccion.php');
$directory = "upload/";
//get all image files with a .jpg extension.
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT imagen FROM r_alumnos");
if(mysql_num_rows($sql) == 0)
unlink($image);
}
?>
You could create something like a maintenance-script which handels this.
First, load everything in an array (I personally don't like the multiple queries execute):
$database_files = array();
$result_db_files = mysqli_query("SELECT imagen FROM r_alumnos");
while ($row = $result_db_files->fetch_assoc())
{
$database_files[] = $row['imagen'];
}
Then check each file:
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
if (!in_array($name, $database_files))
{
unlink($image);
}
}
Essentially, the following code works fine except for the 'unlink' sections. The record is located and deleted in the database, but the file in the server directory remains untouched.
I know that 'pageLocation' is accurate because I've used it to load files.
<?php
session_start();
if(isset($_POST['btnSubmitEdit']))
{
$allowed_filetypes = array('.jpg','.jpeg','.png');
$max_filesize = 10485760;
$setComic = $_SESSION['comicID'];
$setPage = $_SESSION['currentPage'];
$upload_path = 'comics/'.$setComic.'/';
$filename = $_FILES['fileToEdit']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['fileToEdit']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
include_once('includes/conn.inc.php');
$query1 = ("SELECT pageLocation FROM page WHERE pageID = '$setPage'");
$result1 = mysqli_query($conn, $query1);
while ($row = $result1->fetch_assoc())
{
unlink('/"'.$row['pageLocation'].'"');
}
if(move_uploaded_file($_FILES['fileToEdit']['tmp_name'],$upload_path . $filename))
{
mysqli_query($conn, "UPDATE page SET pageLocation='".$upload_path . $filename."' WHERE pageID=".$setPage."");
mysqli_close($conn);
}
else
{
echo 'There was an error during the file upload. Please try again.';
}
header('Location: uploadPage.php');
}
if(isset($_POST['btnSubmitDelete']))
{
$setPage = $_SESSION['currentPage'];
include_once('includes/conn.inc.php');
$query2 = ("SELECT pageLocation FROM page WHERE pageID = '$setPage'");
$result2 = mysqli_query($conn, $query2);
while ($row = $result2->fetch_assoc())
{
unlink('/"'.$row['pageLocation'].'"');
mysqli_query($conn, "DELETE FROM page WHERE pageID = '$setPage'");
}
header('Location: uploadPage.php');
}
?>
UPDATE.
I can only display the images inside a query e.g.
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = $row['path'];
echo '<img src="'.$img.'">';
}
}
I want to display them inside a table but this code doesn't work :
<td class="tcgimagecell" colspan="5"><?php echo '<img src="'.$img.'">'; ?></td>
BELOW ISSUE RESOLVED :
I have images stored in a folder (uploads) and the path is stored in a database table in a field named path. I am trying to display the stored images.
$Link = mysqli_connect($Host, $User, $Password, $Database);
$Query = "SELECT * FROM $images";
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = "uploads/" . $_FILES["file"]["name"];
echo '<img src="'.$img.'">';
}
}
Your folder permissions for "uploads/" might not be set to public read. Have you checked those already? What is the URL that is output for your image? Have you tried Copying URL and linked directly to it from your browser? If the URL is coming back blank, try $row instead of $_FILES since you are just wanting the path to the file.
This line is wrong: $img = "uploads/" . $_FILES["file"]["name"];.
Replace it with $img = "uploads/" . $row[x]; where x is the number of column where file name is
OR
with $img = "uploads/" . $row['columnname'];. Here you have to replace columnname.