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();
}
}
?>
Related
I have a small form to add categories. My table fields are the following:
Name Required
Description Not Required
Photo Not Required
It will create a category with all the information, it will even insert the image name in the database.
The problem I am having is it will not move the image to the uploads folder.
Also it will rename the image as follows: If image name is avatar.jpg it will rename it 85789avatar.jpg in the database field.
I need it to rename the image as follows O1CCJDSXBOM2.jpg.
and the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.
if (isset($_POST['submit'])) {
$Name = $_POST['name'];
$Description = $_POST['description'];
if (empty($Name)) {
$errors[] = "Name Required.";
}
if (!empty($errors)) {
echo validation_errors($errors[0]);
} else {
$file = rand(1000, 100000). $_FILES['photo']['name'];
$file_loc = $_FILES['photo']['tmp_name'];
$file_size = $_FILES['photo']['size'];
$folder = "uploads/";
if (($file_size > 2097152)) {
echo validation_errors("Your avatar exceeds file size");
} else {
move_uploaded_file($file_loc, $folder, $file);
$db = dbconnect();
$stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
$stmt->bind_param('sss', $Name, $Description, $file);
$stmt->execute();
$stmt->close();
header("Location: managecategories.php");
it will not move the image to the uploads folder also it will rename the image as follows. if image name is avatar.jpg ti will rename it 85789avatar.jpg in the database field
move_uploaded_file() takes two arguments, not three. Update this line:
move_uploaded_file($file_loc, $folder, $file);
To this (to append the filename to the folder):
move_uploaded_file($file_loc, $folder . $file);
the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.
Because move_uploaded_file() returns a boolean, the code could be updated to only insert a record if the file was successfully uploaded.
if (move_uploaded_file($file_loc, $folder . $file)) {
$db = dbconnect();
$stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
$stmt->bind_param('sss', $Name, $Description, $file);
$stmt->execute();
$stmt->close();
}
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?
<?php
require_once("database.php");
if(#$_POST['upload']) {
$file_name = $_FILES['cvs']['name'];
$file_type = $_FILES['cvs']['type'];
$file_temp_loc = $_FILES['cvs']['tmp_name'];
$file_error_msg = $_FILES['cvs']['error'];
$file_size = $_FILES['cvs']['size'];
/* 1. file upload handling */
if(!$file_temp_loc) { // if not file selected
echo "Error: please browse for a file before clicking the upload button.";
exit();
}
if(!preg_match("/\.(csv)$/i", $file_name)) { // check file extension
echo 'Error: your file is not CSV.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
if($file_size > 5242880) { // file check size
echo "Error: you file was larger than 5 Megabytes in size.";
exit();
}
if($file_error_msg == 1) { //
echo "Error: an error occured while processing the file, try agian.";
exit();
}
$move_file = move_uploaded_file($file_temp_loc, "\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/{$file_name}"); // temp loc, file name
if($move_file != true) { // if not move to the temp location
echo 'Error: File not uploaded, try again.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
$csvFile = '\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/'.$file_name;
$csvFileLength = filesize($csvFile);
$csvSeparator = ",";
$handle = fopen($csvFile, 'r');
$count = '';
while($data = fgetcsv($handle, $csvFileLength, $csvSeparator)) { // while for each row
$count += count($data[0]); // count imported
mysql_query("INSERT INTO `csv_data` (`product_title`, `product_price`) VALUES ( '$data[0]', '$data[1]' )");
}
fclose($handle);
unlink($csvFile); // delete cvs after imported
header('Location: index.php?success=1&count='.$count);
exit();
}
?>
please check the spelling of file field's name .. it must be csv in html and you called it cvs
$file_name = $_FILES['csv']['name'];
$file_type = $_FILES['csv']['type'];
$file_temp_loc = $_FILES['csv']['tmp_name'];
$file_error_msg = $_FILES['csv']['error'];
$file_size = $_FILES['csv']['size'];
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
Need Help:
I am using a simple PHP code to upload photos into remote database. But.. Everytime, two copies of one photo is saved int the DB.
Can anyone tell me whats I am doing wrong?
PHP Code:
<?PHP
$uploadDir = 'image_folder/';
$uploadDir = 'image_folder/';
if(isset($_POST['Submit'])) //info saving in the variables
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath); //moving the photo in the destination
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
echo "".$filePath."";
$query = "INSERT INTO picture (image) VALUES ('$filePath')";
if (mysql_query($query))
{echo "Inserted";}
mysql_query($query) or die('Error loading file!');
}?>
if (mysql_query($query))
{echo "Inserted";}
mysql_query($query) or die('Error loading file!');
you are calling mysql_query($query) twice
You are doing mysql_query($query) two times, first in IF{} and right after it. :D
ps. mysql_* functions are depricated, use PDO or mysqli
You are using mysql_query two times. Try this:
if (mysql_query($query)) {
echo "Inserted";
} else {
die('Error loading file!');
}
You are executing mysql_query twice. Modify your if to:
if (mysql_query($query)) {
echo "Inserted";
} else {
die('Error loading file!')
}
And, remove the following line:
mysql_query($query) or die('Error loading file!');
Note: Make sure that you read the warning box in http://in2.php.net/mysql_query. mysql_* functions are deprecated.