Images wont save to project folder - php

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");
?>

Related

Need to unlink image from folder when updating in PHP

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");
}

Upload Image PHP - error in verifying ISSET

I followed this link to upload image from android to server. But the upload is failed on PHP part, so I added some echo to keep track on which one triggered the error. And I found that even though I already set an image to upload (I use Postman), the error of 'Please choose a file' is triggered.
<?php
//importing dbDetails file
require_once('dbDetails.php');
//this is our upload folder
$upload_path = 'uploads/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://xxx/xxx/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
echo "method OK";
//checking the required parameters from the request
if(isset($_POST['name']) && isset($_FILES['image']['name'])){
echo "isset ok";
//connecting to the database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//getting name from the request
$name = $_POST['name'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['image']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO uploads (id, fileUpload, name) VALUES (NULL, '$file_url', '$name');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($con);
} else{
echo "isset error";
$response['error']=true;
$response['message']='Please choose a file';
}
}
function getFileName(){
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
$sql = "SELECT max(id) as id FROM uploads";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['id']==null)
return 1;
else
return ++$result['id'];
}
?>
Screenshot from Postman
Please guide me what did I missed?

How to Upload images into folder directory on the server using php

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;
}
}
?>

AJAX PHP Upload file to database

I am working on a script that uploads a file, calls a php script via ajax that uploads it to a folder on the server. This part is working correctly. The next step is to then take this file and insert it into a database (I know its not best practise but I have to due to exising db/software constraints) but I cant seem to get this to work at all.
I'll leave out the ajax as that is working correctly, here's the PHP:
$upload_dir = "./uploads";
$result["status"] = "200";
$result["message"] = "ERROR!";
if (isset($_FILES['file']))
{
echo "Uploading File...<br />";
if ($_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$filename = $_FILES['file']['name'];
$destination = 'uploads/' . $filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
//THIS IS THE SECTION THAT DOESN'T WORK CORRECTLY. IT JUST DOES NOTHING AT ALL
//upload the image as a blob
$image = file_get_contents ($destination);
//see if there is anything already stored in blob
$sqlcheck = "select id from blobstore where id='$custid'";
$result = sasql_query($connect, "$sqlcheck");
if (!isset($row['id']))
{
$sql = "update blobstore set class='j', id='$custid', blob='".sasql_real_escape_string($connect,$image)."', createdby='$userid', createdat='". date_format($date, 'Y-m-d H:i')."' where id='$custid' ";
$insert = sasql_query($connect, "$sql");
}
else if (isset($row['id']))
{
$sql = "insert into blobstore (class, id, blob, createdby, createdat) VALUES ('j','$custid', '".sasql_real_escape_string($connect,$image)."','$userid', '". date_format($date, 'Y-m-d H:i')."') ";
$insert = sasql_query($connect, "$sql");
}
//WHEN I INCLUDE THE ABOVE SECTION TO UPLOAD THE IMAGE TO THE DB THIS ALSO RETURNS NOTHING, WHEREAS IF I TAKE OUT THAT SECTION IT RETURNS AS EXPECTED
$result["status"] = "100";
$result["message"] = "File was uploaded successfully!";
}
}
elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
{
$result["status"] = "200";
$result["message"] = "The file is too big.";
}
else
{
$result["status"] = "500";
$result["message"] = "Unknown error.";
}
When I run this I am getting the error
Warning: Cannot use a scalar value
This error goes when I remove the following code
$result["status"] = "100";
$result["message"] = "File was uploaded successfully!";
Any help would be much appreciated.
Thanks

How to upload and display images in mysql

I would like to ask you how can I properly stored an image both in mysql and in a folder at the moment with this code:
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$data')";
$results = mysql_query($query, $conn);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
?>'
Also how properly to display it.
My database for the images is id, images. Do I need anything more for the job or that is enough.
Thank you.
From the above code, image will be saved in database not in folder.
To save in folder you have to use a below code after insert query.
move_uploaded_file($tmpName,"upload/" .$filename );
here upload is folder name.
If you want to store image in database you can use base64_encode method
$image = file_get_contents('filename.gif');
$imencoded = base64_encode($image);
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$imencoded')";
But storing image in db is not recommended and it will not support in IE6 & 7.

Categories