i am storing image in uploads folder an then in a random directory but it is not being shown in my website this is my code
<?php
$query = "SELECT * FROM users WHERE email='$email' or username = '$email'or mobile='$email'";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
$users = mysqli_fetch_assoc($fire);
}
?>
<img src="<?php echo $users['avatar_path']?>" width='100' height='100' class='avatar'>
and this is my upload code
if (isset($_POST['uploadimg'])) {
$avatar = $_FILES['avatar'];
$avatar_name = $_FILES['avatar']['name'];
$avatar_tmpname = $_FILES['avatar']['tmp_name'];
$avatar_size = $_FILES['avatar']['size'];
$avatar_type = $_FILES['avatar']['type'];
$avatar_ext = pathinfo($avatar_name, PATHINFO_EXTENSION);
if (!empty($avatar_name)) {
if ($avatar_size <= 25000000) {
if ($avatar_ext == "jpg" || $avatar_ext == "jpeg" ||$avatar_ext == "png" ) {
$chars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name=substr(str_shuffle($chars),0,15);
mkdir("uploads/$rand_dir_name");
$final_file= "uploads/$rand_dir_name/$avatar_name";
$upload = move_uploaded_file($avatar_tmpname, $final_file);
if ($upload) {
unlink("$avatar_path");
$msg = "file uploaded successfully ";
$query = "UPDATE users SET avatar_path='$final_file' WHERE id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE likes SET avatar_path='$final_file' WHERE user_id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE photos SET avatar_path='$final_file' WHERE uid='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
if ($fire) {
$msg .=" and also inserted into database";
}
# code...
}else{ echo "only jpg,jpeg,png, type format allowed";}
}else{echo "file size is too large";}
}else{echo "please select an image to upload";}
}
}
}
?>
this code used to work on localhost and my upload code is still working and when i inspect my page the avatar path is correct but still the pic is not being shown a broken image is shown i dont know what is being wrong this is the avatar path that is coming
uploads/Un7sL9TwyNzOhco/bhai.jpg
Try adding slash at first like below:
$final_file= "/uploads/$rand_dir_name/$avatar_name";
Related
lets say i have 2 column in my inventory data called category and image_name in my php and database.
image_name are coming from this (basically in my database, image_name contain the link of the uploaded image) :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file = $_FILES['uploadgambar'];
$fileName = $_FILES['uploadgambar']['name'];
$fileTmpName = $_FILES['uploadgambar']['tmp_name'];
$fileSize = $_FILES['uploadgambar']['size'];
$fileError = $_FILES['uploadgambar']['error'];
$fileType = $_FILES['uploadgambar']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 5000000) {
$fileNameNew = uniqid('', true) . "." . $fileActualExt;
$fileDestination = 'uploads/' . $fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: index.php?uploadsuccess");
} else {
echo "File anda terlalu besar (maximal 1gb)";
}
} else {
echo "Terdapat error dalam mengupload file";
}
} else {
echo "Anda tidak bisa upload file ini karena tidak berbentuk JPG/JPEG/PNG";
}
i build some code for update feature for category and image_name column like this
$kategori = mysqli_real_escape_string($conn, $_POST["kategori"]);
$image_name = mysqli_real_escape_string($conn, $fileDestination);
and here's for the update
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
$updatean = mysqli_query($conn, $sql1);
echo "<script type='text/javascript'> alert('Berhasil, Data barang telah diupdate!'); </script>";
echo "<script type='text/javascript'>window.location = '$forwardpage';</script>";
but the problem is, when i update the image its run, but when i update kategori, idk why my picture gone and when i look at the database, column image_name has removed for that id and cause the image gone.
my expected result is, just like update feature, if i update the category, then the image_name wont missing.
I am writing your answer, but maybe it needs some editions. so add some comments if the ways not fix the problem.
one of the reasons maybe due to updating the row of database even if the file name is empty. so you must check the file name before update the database table record.
In this code, whenever you don't have upload file, so $fileDestination will be empty, so the cell of table will be empty and image address will gone!
For that problem, you could change the query:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to something like this:
if ($image_name) {
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
} else {
$sql1 = "update $tabeldatabase set kategori='$kategori' where kode = '$kode';
}
Apart from this I recommend you to change this row:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to a fixed table name like this:
$sql1 = "update my_static_table_name set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
so you can easily debug the problem.
I want a logged in user to add a profile picture. No errors are shown, the picture is just not added to the folder where it should be.
I know I have to use prepared statements, I will. I just want to sort this problem out first.
When the user has not changed the profile pic, the default picture displays perfectly. The file profile pic just wont upload to the folder.
This is the page where you change the picture.
<?php
session_start();
include_once 'dbh.php';
<html>
<body>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
}
else {
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
}
else {
echo "There are no users!";
}
if (isset($_SESSION['id'])) {
echo "You are logged in!";
echo '<form action="includes/upload.inc.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD FILE</button>
</form>';
}
else {
echo "You are not logged in!";
}
?>
This is the php page for the upload
<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
//I now need to create a unique ID which we use to replace the name
of the uploaded file, before inserting it into our rootfolder
//If I don't do this, we might end up overwriting the file if we
upload a file later with the same name
//Here I use the user ID of the user to create the first part of the
image name
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
I suspect logical issue near your below update query:
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
Your logic will run fine for only those users who already having corresponding record in profileimg table. But UPDATE query will do nothing for new user.
So, you will have to first check whether there is a record in profileimg for particular user. If no record then run INSERT query, if record exists then run UPDATE query..
I am using following codes to prevent entry of duplicate username in the database but it always says "username already exists" through the particular username not exists in the database. I can not understand where I am doing wrong. Thanks in advance.
$ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='".$username."'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'],
$ImageName)) {
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
//**insert these new lines
if ($type > 3) {
echo "Sorry, but the file you uploaded was not a GIF, JPG, or " .
"PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
elseif ($rows > 0){
echo "email already exists";
}
else {
//image is acceptable; ok to proceed
//**end of inserted lines
//insert info into image table
$insert = "INSERT INTO xyz (.......)
VALUES (........)";
$insertresults = mysqli_query($insert); //order executes
if($insertresults)
{
header ("Location:https://www.getalifepartner.com/free-matrimonial-site/upload_success.php");
}
Here is one way
$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$res = mysqli_fetch_array($query);
if ($res['username'] == $username)
{
echo 'Username already in use, please choose another one.';
}
else
{
// username not in use
}
Here is another way
$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);
if ($rows > 0)
{
echo 'Username already in use, please choose another one.';
}
else
{
// username not in use
}
UPDATE TO ORIGINAL QUESTION
$ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'], $ImageName))
{
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
//**insert these new lines
if ($type > 3)
{
echo "Sorry, but the file you uploaded was not a GIF, JPG, or PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
}
elseif ($rows > 0)
{
echo "Email already exists.";
}
else
{
//image is acceptable; ok to proceed
//**end of inserted lines
//insert info into image table
}
can somebody help me for my codes. i can delete the image in the database but in the directory i can't. im tried for long hours but it seems not work at all. would somebody help me please? here's my code: this is the code where the images
<?
//this is were images displayed
$query = "SELECT * FROM images WHERE category='home'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<img src="images/template/delete.png" id="AEDbutton">
echo "<img border=\"0\" src=\"".$row['image']."\" width=\"200\" height=\"100\">";
echo "<br>"; }
?>
,?
include('global.php');
//this is were image were deleted
if($delete != "")
{
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
//but in here , it cannot delete image through directory
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
?>
You already deleted the image entry in table, after that you try to get the same entry in DB. so, first you can delete the image from folder after that you can delete in the table.
<?php
include('global.php');
if($delete != "") {
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
?>
Note:
Make sure your path $file= '/.directory/'.$image; is correct, I think it referring from root directory.
Funny. That's because you are first deleting the image id from the database and after that you are trying to get the ID of the previously deleted image (which no longer exists) and delete the file associated with it. Switch the code like this.
include('global.php');
if($delete != "")
{
//first delete the file
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result))
{
try
{
$image = $delete['image'];
$file= '/images/'.$image;
unlink($file);
} catch (Exception $e) {
}
}
// after that delete the id from the db of that image associated with the deleted file
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
UPDATE: I added a try catch
If you are deleting images, first you need to delete image and then delete in DB
I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".