i am running a localhost project. i'm uploading image and some text into localhost phpmysql server. the image file save into images folder. when i upload a image called 1.png its save on the folder as a same name. like this - images/1.png.
what i want - is it possible to change automatically the image file name to a unique one? Like this - images/1.png into images/sgaggjhdzfndzfnd1.png
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
// Create database connection
include_once('db.php');
// 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']);
$text01 = mysqli_real_escape_string($db, $_POST['text01']);
$text02 = mysqli_real_escape_string($db, $_POST['text02']);
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO images (image, image_text, text01, text02) VALUES ('$image', '$image_text', '$text01', '$text02')";
// 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 ORDER BY id DESC");
?>
You can use PHP's random functions to create random strings for the uploaded file.
mt_rand()
md5()
substr()
So, please modify the line:
$target = "images/".basename($image);
To
$target = "images/". substr(md5(mt_rand(0, 9999)), 0, 21) . '-' . basename($image);
Explanation:
You are adding random string to uploaded file using PHP functions.
Using random strings to rename/save uploaded files fix a severe issue: An image my get overridden if the same image name's file is uploaded.
The uploaded file now has 21 random characters prepended to it. So, there is hardly possibility to have file with same name.
You can use try this it may resolve your issue.
$imageName = GetRandomFileName().".".strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION));
move_uploaded_file($temp['tmp_name'], $imageName);
public function GetRandomFileName() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$randomString .= time();
return $randomString;
}
Related
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 am trying to upload an image to a server using PHP and calculate the hash of the same image using md5_file. but somehow it is not referring to the directory either and not calculating the hash of the image.
Code:-
<html><body style="background-color:powderblue;">
<?php
session_start(); //declare you are starting a session
if(isset($_POST['submit'])){
include'connect.php';
$fname = $_POST['fi'];
$filename = $_FILES['fileupload']['name'];
$filetmp = $_FILES['fileupload']['tmp_name'];
$filesize = $_FILES['fileupload']['size'];
$file_basename = basename($_FILES['fileupload']['name']);
$dir = "upload/";
$final_dir = $dir.$file_basename;
$hash = md5_file($final_dir);
$_SESSION['hash'] =$hash;
$upload = move_uploaded_file($filetmp,$final_dir);
}
/* image_name= "$file_basename";
image_path ="$final_dir";
*/
/*Database Query*/**strong text**
if($filesize > 1024000){
echo("Greater then expected");
}
if($selected){
echo nl2br("Operation successful\n");
echo nl2br("URL Record successfully\n");
echo nl2br("$fname \n \n");
}
else{
echo("No No No ...");
}
?>
Just hash the temporary file before moving it to the final destination.
$hash = md5_file($filetmp);
...
$upload = move_uploaded_file($filetmp,$final_dir);
I am trying to upload images onto server.
On the Server the folder name:{photo}
I check the permissions on the folder and it currently on 0755.
When I run my php code, I get this error code:
"Error uploading file - check destination is writeable."
The post that was similar to my issues is this: How to upload photo to my hosting server folder directory
but I already have these functions in my code:
Here my php code:
<?php
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filesize = $_FILES["file_img"]["size"];
$fileinfo = getimagesize($_FILES["file_img"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../photo/".$filename;
$filepath_thumb = "../photo/thumb/".$filename;
if($_POST['btn_upload'])
{
$sPhotoFileName = $filename;
$nPhotoSize = $filesize;
$sTempFileName = $filetmp;
chmod($filepath_thumb,0755);
chmod($filepath,0755);
if(file_exists('photo/' . $_FILES['file_img']['name'])){
die('File with that name already exists.');
}else{
if ($sPhotoFileName) // file uploaded
{ $aFileNameParts = explode(".", $sPhotoFileName);
$sFileExtension = end($aFileNameParts); // part behind last dot
if ($sFileExtension != "jpg"
&& $sFileExtension != "png"
&& $sFileExtension != "gif")
{ die ("Choose a JPG for the photo");
}
}
if($_FILES['file_img']['error'] > 0){
die('An error ocurred when uploading.');
}
if ($nPhotoSize == 0)
{ die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 300K, using the button.");
}
if ($nPhotoSize > 30240000000)
{ die ("Sorry.
The file $sPhotoFileName is larger than 300K.
Advice: reduce the photo using a drawing tool.");
}
// read photo
$oTempFile = fopen($sTempFileName, "r");
$sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
// Try to read image
$nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
$oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
error_reporting($nOldErrorReporting);
if (!$oSourceImage) // error, image is not a valid jpg
{ die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
}
}
$nWidth = imagesx($oSourceImage); // get original source image width
$nHeight = imagesy($oSourceImage); // and height
// create small thumbnail
$nDestinationWidth = 80;
$nDestinationHeight = 60;
//$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
$oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
/*$oResult = imagecopyresampled(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
*/
imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
ob_start(); // Start capturing stdout.
imageJPEG($oDestinationImage); // As though output to browser.
$sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
ob_end_clean(); // Dump the stdout so it does not screw other output.
// attempt insert query execution
$sql = "INSERT INTO UploadImg (img_name, img_path, img_type) VALUES ('$sPhotoFileName', '$filepath', '$filetype')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!move_uploaded_file($_FILES["file_img"]["tmp_name"],"../photo/".$_FILES["file_img"]["name"])){
die('Error uploading file - check destination is writeable.');
echo "Error Code: " .$_FILES["file_img"]["name"] . "<br>";
}else{
$sBinaryThumbnail = addslashes($sBinaryThumbnail);
$oDatabase = $link;
mysqli_select_db("upload", $oDatabase);
$sQuery = "insert into Uploadimg (thumbnail) VALUES ('$sBinaryThumbnail')";
echo $sQuery;
mysqli_query($sQuery, $oDatabase);
die('File uploaded successfully.');
mysqli_close($link);
}
}
?>
Now I read an article say that even if your folder permission setup up to do all three read, write, and executed on all three level. the code still will not be able to read it depending on the settings on the server.
So I am confused and looking for clarification. Please assist me?
You can upload the image by binary data encoded and save the file with the image format on the server.
755 means it is not world writable. You can set it writable and executable with 777.
This is still vulnerable as anyone with access to your server os can write to the folder, so you should probably just make the web server user the owner of the folder and keep the permissions as they are now. If you're running apache, the user is usually www-data or apache.
I figure it out you gotta set the GID and UID permissionsfilepermission
The set group identification GID allows the owner to execute all applications to read, write and pull to the folder.
Same thing with the User identification UID. the problem is the your folder will be wide open for strangers to manipulate it but it works.
My images are uploading into the folder. Tell me what yall think?
First in your php.ini put
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
Make sure that the form uses method="post"
Then use the php code below to upload image
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path