I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();
Related
Is there a way to check whether an image or video already exists in a mysql database or a specific folder when the names are different. Also note there could be 10 to 1000 images in the database or folder and this would need to be done via php.
Thanks for the help
Each file will (for practical purposes) have a unique hash, so you can save the hashes of your files (see sha1_file or md5_file) to the db and if the hash of your new file is in your db, then it already exists.
$newFileHash = sha1_file('myNewFile.txt');
$query = "SELECT 1 FROM myHashes WHERE file_hash = '$newFileHash'";
$rs = mysqli_query($query);
if(mysqli_num_rows($rs)) {
echo "the file already exists!";
}
else {
//insert $newFileHash into your db here
}
You can get the base64 encoded data information of the images/videos
$file = file_get_contents('path/file.zip');
$file_encoded = base64_encode($file);
And then compare the $file_encoded with whatever you have in your database.
if ($file_encoded === $file_encoded_in_db) {
//Files are the same
}
I have a peace of code that stores profile images in the map "images/profiles" and stores the URL in the database. I want to define the name of the uploaded profile picture to be the $ID of the user. How can I do this?
include("../../core/init.inc.php");
$target = "../images/profiles/";
$target = $target . basename($_FILES['photo']['name']);
$pic = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename($_FILES['photo']['name']). " has been uploaded";
} else {
echo "ERROR";
}
mysql_query("UPDATE users SET image_url='includes/images/profiles/$pic' WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'");
Now when someone uploads his profile picture (lets call it pf1.png) it saves it as "pf1.png". I want it to be saved like "$ID.png" (.png being a random extension). I want to accomplish this both for the move_upload_file function and updating the 'image_url' database column correctly.
According to the example in the documentation you can provide the filename in the destination of move_uploaded_file(). If that fails you can simply rename() the file after saving it.
try changing
$target = $target . basename($_FILES['photo']['name']);
to:
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$target = target . $_SESSION["ID"].".".$extension;
side note: You are not escaping $pic this makes your site vulnerable to sql-injection
I don't know how you saved the ID of the user, but to make it easy let's assume you stored the ID in a session.
Then simply change the $target.
$target = $target . $_SESSION['ID'];
Also change your query as follows:
$url = "includes/images/profiles/" . $_SESSION['ID'];
SET image_url="$url"
Note: I don't know why you got an image folder inside an includes folder, but I guess you made that choice for yourself.
you can get the last inserted id and make it as a name of your image/uploaded file
$qry = mysqli_query($dbconnection,"INSERT INTO statements here");
$last_id = mysqli_insert_id($dbconnection);
//$ext= you get the extension of the file uploaded
move_uploaded_file($tmpname,$target.$last_id.$ext);
now if you want it to be accomplished in updating also.
you can always get the ID of the data you want to fetch and make it as a basis in updating.
ex.
$id = $_GET['id'] || $id = $row['id']; //anything depends on how you want it to retrieve
then you can do the query and move_uploaded_file function
$qry = mysqli_query($dbconnection,"UPDATE tblname SET field='$anything' WHERE id = '$id'");
move_uploaded_file($tmpname,$target.$id.$ext);
of course $tmpname will be the basis on what file you have uploaded, $tmpname will be the file you want to move into your desired directory
This seems like such a simple thing to do but for some reason, I can't get this to work.
I have a database with vehicle data stored in it. (Used Cars (I'm developing a car dealership website)).
I successfully display results from the database without images.
The images for each record aren't stored in the database, instead they're dumped on the server in a directory and those images are only referenced in the database.
If I echo the image name out it works fine, and if I echo the actual image out, the path is correct if you look at the image info. But in the info it states that the image is of text. i don't know how to change this.
Please find some of the code below.
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
//this is selecting individual records
$selected_id = intval($_GET['Id']);
//this is the query
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO, MainPic FROM Vehicle WHERE Id = $selected_id";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$mainPic = odbc_result($rs, MainPic);
//this is a failsafe for when there are no images for a specific record
$no_image = "<a href='db/Nopic.gif' data-lightbox='nopic' title='No Image Available'><img src='db/Nopic.gif' /></a>";
//This successfully displays the name of the image referenced in the database
$main_pic = "<img src='db/vehicleImages/'" .$mainPic. "/>";
//this is supposed to display the actual
echo $main_pic . "<br />";
echo $no_image;
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
Any help in the regard would be greatly appreciated.
Thank you. :)
you should use quotations around the attributes of html objects (it looks like you might be breaking things via your method):
yours:
<a href=db/Nopic.gif data-lightbox=nopic title=No Image Available><img src=db/Nopic.gif /></a>
correct:
<a href='db/Nopic.gif' data-lightbox='nopic' title='No Image Available'><img src='db/Nopic.gif' /></a>
whether or not this fixes your problem will be determined by what you come back with :p
User forward slash in front of your image paths. This way you can be sure the image path always starts from the root folder. The image path is relative to the location of the executed php script.
For example if your script.php file is in the folder /root/some_folder/script.php and you use the image path db/vehicleImages/image.jpg the script is starting the path from the same folder where it is itself which results in a path like this /root/some_folder/db/vehicleImages/image.jpg.
If you use forward slash in front of the path like this /db/vehicleImages/image.jpg it tells the script to start from the root folder like so /root/db/vehicleImages/image.jpg.
I think this is the case with your script - you are giving it the wrong path which results in a file not found.
I'm fairly new to PHP programming and I've looked around but I'm still confused. I'm trying to update the image path in my users table and I'm not quite sure how to do it. This is the code I have for putting the image into the database and it works to insert it in, but I'm not sure how to UPDATE the image picture path in my database to use the newly inserted image as opposed to the one the user selected when they created an account.
// Make sure we didn't have an error uploading the image
($_FILES[$image_fieldname]['error'] == 0)
or handle_error("the server couldn't upload the image you selected.",
$php_errors[$_FILES[$image_fieldname]['error']]);
// Is this file the result of a valid upload?
#is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you were trying to do something naughty. Shame on you!",
"upload request: file named " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// Is this actually an image?
#getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you selected a file for your picture " .
"that isn't an image.",
"{$_FILES[$image_fieldname]['tmp_name']} " .
"isn't a valid image file.");
// Name the file uniquely
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// Finally, move the file to its permanent location
#move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or handle_error("we had a problem saving your image to " .
"its permanent location.",
"permissions or related error moving " .
"file to {$upload_filename}");
$insert_sql = "UPDATE users set user_pic_path WHERE user_id = $user_id =
replace(user_pic_path, '$upload_filename', '$upload_filename' );
//insert the user into the database
mysql_query($insert_sql);
</code>
EDIT:
I was missing a " which I fixed and now there is no SQL error, it puts the picture into the database but does not replace the image path in the database. I've been messing with the $insert_sql but it still doesn't update the database with the new image path, what can I do? Here's my new update code:
<code>
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path =
replace(user_pic_path, '$upload_filename', '$upload_filename')";
</code>
In the final lines, insert a test of your SQL:
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path = replace(user_pic_path, '$upload_filename', '$upload_filename')";
// check the query
echo $insert_sql."<br />";
//insert the user into the database
mysql_query($insert_sql);
Then you can watch the query your about to run, test it in PHPMyAdmin, work out what it should be. It's worth doing for other key variables as well. Even better, you should write a "debug" function, that logs what's going on in a file on the server so that when an error occurs, you can track details of it, including values of key variables in every file.
I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);