Upload Image PHP - error in verifying ISSET - php

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?

Related

Image getting deleted from a file path

I have a dashboard where users can login and upload a profile picture of themselves which saves to their profile. This moves the image to the correct folder and also correctly inserts it into the db.
This has been working fine up until recently when I noticed the image disappeared. Within the inspect console I noticed I was getting a 404 not found error on the image, so I checked inside the file path and the image was no longer in there (hence the 404). There is no script at all for the user to delete an image, only to upload.
profile.php:
<p><b>Profile Picture: </b>
<?php
$picture = $row['imagePath'];
if (empty($picture)){
echo "<img src='profiles/no-image.png' width='100' height='100' >";
} else {
echo "<img src='profiles/".$row['imagePath']."' width='100' height='100' >";
};
?>
<form action="scripts/edit-picture.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="edit-picture" value="Upload"/>
</p>
</form>
script for edit-image.php
<?php
require 'db.php';
session_start();
$uploadDir = '../profiles/';
// if edit-picture has been clicked on, run this if statement
if (isset($_POST['edit-picture'])) {
$studentID = $_SESSION['studentID'];
// Creating 4 different variables using the $_FILES global variable to get data about the image that
// you can view data about a file by doing: print_r($image);
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filePath = $uploadDir.$fileName;
// The below doesn't work as it assigns different value to folder and in db for image name
// $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
header("Location: ../profile.php?img=errorFileRelocate");
exit;
}
// Checking file size - working
else if ($_FILES["image"]["size"] > 5000000) {
header("Location: ../profile.php?img=errorFileSizeError");
exit();
}
// Check if file name already exists in db - not working
else if (file_exists($result)) {
header("Location: ../profile.php?img=errorFileNameExists");
exit();
}
// Allow certain file formats - not working
else if($result != "jpg" && $result != "png" && $result != "jpeg") {
header("Location: ../profile.php?img=errorFileTypeError");
exit();
}
// This is to show any errors that may occur if the connection fails, this helps with error checking.
else if(mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
$stmt = $conn->prepare ("INSERT INTO `profileImage` (`imagePath`, `studentID`)
VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
$stmt->bind_param("si", $fileName, $studentID);
$stmt->execute() or die("Failed to insert image into the database");
header("Location: ../profile.php?img=successImageUploaded");
exit();
}
}
?>
My folder structure:
profiles
image1.jpg
image2.jpg
profile.php
scripts
edit-image.php
Has anyone ever come across an image actually disappearing from a folder after it being moved in there via move_uploaded_file as ANY help or guidance would be much appreciated.
Solve conditions for image upload and don't overwrite existing image files:
<?php
require 'db.php';
session_start();
$uploadDir = '../profiles/';
// if edit-picture has been clicked on, run this if statement
if (isset($_POST[ 'edit-picture' ])) {
$studentID = $_SESSION[ 'studentID' ];
// Creating 4 different variables using the $_FILES global variable to get data about the image that
// you can view data about a file by doing: print_r($image);
$fileName = $_FILES[ 'image' ][ 'name' ];
$tmpName = $_FILES[ 'image' ][ 'tmp_name' ];
$fileSize = $_FILES[ 'image' ][ 'size' ];
$fileType = $_FILES[ 'image' ][ 'type' ];
$filePath = $uploadDir . $fileName;
// The below doesn't work as it assigns different value to folder and in db for image name
// $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);
if (file_exists($filePath)) {
header("Location: ../profile.php?img=errorFileNameExists");
exit();
} // Checking file size - working
else if ($_FILES[ "image" ][ "size" ] > 5000000) {
header("Location: ../profile.php?img=errorFileSizeError");
exit();
}
$info = getimagesize($tmpName);
// empty $info - not known image
if (empty($info)) {
header("Location: ../profile.php?img=errorFileTypeError");
exit();
} // This is to show any errors that may occur if the connection fails, this helps with error checking.
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
header("Location: ../profile.php?img=errorFileRelocate");
exit;
}
else if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$stmt = $conn->prepare("INSERT INTO `profileImage` (`imagePath`, `studentID`)
VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
$stmt->bind_param("si", $fileName, $studentID);
$stmt->execute() or die("Failed to insert image into the database");
header("Location: ../profile.php?img=successImageUploaded");
exit();
}
}
?>

Images wont save to project folder

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

upload picture in database using android studio

<?php ## Heading ##
require_once 'include/db_connection.php';
global $connection; $upload_path = 'uploads/';
//this is our upload folder
$server_ip = gethostbyname(gethostname());
//Getting the server ip
$upload_url = 'http://'.$server_ip.'/android_upload/'.$upload_path;
//upload url
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['caption'])) {
$caption = $_POST['caption'];
$fileinfo = pathinfo($_FILES['image']['name']);
//getting file info from the request
$extension = $fileinfo['extension'];
//getting the file extension
$file_url = $upload_url . getFileName() . '.' . $extension;
//file url to store in the database
$file_path = $upload_path . getFileName() . '.'. $extension;
//file path to upload in the server
$img_name = getFileName() . '.'. $extension;
//file name to store in the database
try{
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
//saving the file to the uploads folder;
//adding the path and name to database
$sql = "INSERT INTO photos(photo_name, photo_url, caption) ";
$sql .= "VALUES ('{$img_name}', '{$file_url}', '{$caption}');";
if(mysqli_query($connection,$sql)){
//filling response array with values
$response['error'] = false;
$response['photo_name'] = $img_name;
$response['photo_url'] = $file_url;
$response['caption'] = $caption;
}
//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($connection);
}else{ $response['error'] = true;
$response['message']='Please choose a file';
}
}
/* We are generating the file name so this method will return a file name
for the image to be uploaded */
function getFileName(){
global $connection;
$sql = "SELECT max(id) as id FROM photos";
$result = mysqli_fetch_array(mysqli_query($connection, $sql));
if($result['id']== null) return 1;
else return ++$result['id'];
mysqli_close($connection);
}
?>
Here is picture upload code and get response image url save your database. u hope you try this.
<?php
include('confi.php');
/**********MYSQL Settings****************/
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_FILES["file"]["name"])) {
$file_name=$_FILES["file"]["name"];
$temp_name=$_FILES["file"]["tmp_name"];
$imgtype=$_FILES["file"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("m-Y")."-".rand().$_FILES['file']['name'];
$target_path ='images/'.$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$result = $url.'api/'.$target_path;
$json = array( "status" =>1,"file-url" => $result, "files" => $_FILES);
}else{
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$json = array( "status" =>0, "error" => $_FILES['uploaded']);
}
else{
$json = array( "status" =>0,"files" => $_FILES);
}
}
}
else{
$json = array("status" =>0, "error" => "Problem occurred");
}
}else{
$json = array("status" => 0, "message" => "Request method is wrong!");
}
header('Content-type:application/json');
echo json_encode($json);
?>

When uploading image to server:front camera photo works/rear camera photo doesn't

I have an app in which I select an image and I upload it successfully. My problem is that I can only upload selfies-front camera photos. If I select a photo which was taken with the rear camera I get an error from the server telling me that it hasn't received any file because this line returns false if (isset($_FILES['image']['name'])). How can I solve this ?
I checked in the gallery and both have the same format: JPEG.
This is my php.
<?php
// Path to move uploaded files
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = "IP";
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
exit;
?>
I think the problem is the size of the image.
Front camera has a smaller quality = smaller size.
The php excepts files as form data and if the file size exceeds the upload limit.
Check the "upload_max_filesize" and "post_max_size" in phpinfo().
Test if you increase both values will it upload.

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

Categories