Name cannot be updated and picture is deleted after editing - php

I have two problems:
Name cannot be updated
Profile picture is deleted (the exist one) even though I did not upload a new one. I have no problem in uploading image though.
Below is the code
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
echo "<img src='" . $imageup . "' />";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = "UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'";
$success = mysql_query($query1);//is mysql query working?
if($success){
$oldprofilepicture = $staff['StaffProfilePicture'];
if(file_exists($oldprofilepicture)){
unlink($oldprofilepicture);//delete now
}
header('location:staff_profile.php');
}
}
Below is the line where a new name is entered.
<tr>
<td width="170">Full Name:</td>
<td><input type="text" name="new_name" size="30" value="<?php echo $staffname ?>" /></td>
</tr>

Regarding the image, create a hidden input field with the same value as from the database, e.g.:
<input type="hidden" value="/path/to/img.ext" name="old-image" />
Before this line:
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
Add:
$imageup = $_POST['old-image'];
Of course you need to do validation on the $_POST data. I've left it out of the above example.
This will set the default value for the image as the saved version. If you upload a new image, then that will override $imageup with the name path details :)
Regarding the name not changing, I cannot see where the value for $staffId is being set?

Related

PHP upload multiple images

This code used to work and now I can't figure why it won't upload, I don't receive errors, I also don't receive any echo's or var_dumps back at all, it's simply like the button only refreshes the page. (Just for clarification there is alot more code doing alot of stuff, but this is the cause of my issue as I isolated it into another project with below code, which gave me the same results).
All it is meant to be doing is creating a folder named by the "ItemName", then it should be moving the images into that new named folder.
Thank you in advance, this problem has been hindering me for a few days now...
HTML PAGE
<form id="newsell" enctype="multipart/form-data" method="post">
<input type="text" class="css-input" name="ItemName" value="">
<input name="file[]" type="file" id="file" multiple />
<input type="submit" name="Upload" class="css-input1" value="Upload">
<?php
if ($_POST['Upload']) {
require_once("random.php");
}
?>
random.php
$MyLocation = "MyName"; // this comes from db, for this case just hardcode
$ItemName1 = htmlspecialchars($_POST["ItemName");
$ItemName = strip_tags($ItemName1);
$parentDir = "C:/wamp/www/HOME/uploadimages/".$MyLocation;
echo "Does it exist...." . $parentDir . "/" . $ItemName;
if(!is_dir($parentDir)) { // Check if the parent directory is a directory
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(!is_writable($parentDir)) { // Check if the parent directory is writeable
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(mkdir($parentDir . "/" . $ItemName) === false) { // Create the directory
echo "File apparently exists...." . $parentDir . "/" . $ItemName;
ExistingSaleName(); // POPUP
die();
}
// die('Created directory successfully'); // Success point
echo "AFTER INSERTION";
movefiles();
}
function movefiles() {
$MyLocation = "MyName";
echo "In movefiles";
$ItemName1 = htmlspecialchars($_POST["ItemName"]);
$ItemName = strip_tags($ItemName1);
extract($_POST);
if (extract($_POST) === null) { // trying to fault find here, but never returns anyway due to some kind of bug as at one point it was returning a null value
echo "PROBLEM...";
}
$error=array();
$extension=array("jpeg","jpg","png");
$res = ("C:/wamp/www/HOME/uploadimages/". $MyLocation. "/" . $ItemName);
foreach($_FILES["file"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["file"]["name"][$key];
$file_tmp=$_FILES["file"]["tmp_name"][$key];
if (!(($_FILES["file"]["type"][$key] == "image/png") || ($_FILES["file"] ["type"][$key] == "image/jpeg") || ($_FILES["file"]["type"][$key] == "image/jpg"))) {
die("Only the .jpg / .jpeg / .png file's were uploaded.");
} else {
echo "SHIT";
}
var_dump($file_tmp);
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$count;
//check if file exist
if (!file_exists($res . "/" . $file_name)) {
sleep(2);
if (isset($_FILES["file"]["tmp_name"][$key])) {
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $res);
++$count;
if ($count >=5) {
// go_to(); // This goes onto the next function
die ("First 5 images are uploaded, <br/> 5 images maximum.");
}
} else {
echo "It exited HERE...";
}
} else {
ExistingSaleName();
die();
}
}
}
I have create simple code to upload multiple images. Changes it yours.
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>

Uploading image not working as expected

I have a form where a user fills out multiple input fields and they can also upload an image. I recently added another input field where the user can upload an additional image.
<label for="photo">Facility Roof Plan:</label>
<input type="file" id="facilityroofplan" name="facilityroofplan" />
When the user submits my form it should upload this image, as well as store a directory path into a db. The information is being saved into my db properly without any issues, however when I check to see if the image was uploaded it is not there.
$directoryPath = "../images/" . $selectedAssocAccount . "/" . $facilityID;
//create the directory
mkdir($directoryPath, 0775);
//facility roof plan
if(!empty($_FILES["facilityroofplan"]["name"])){
//directory path for the facility photo to reside in
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
} else{
echo "Error uploading facility image.";
}
//insert into photo table
$photoQuery = "INSERT INTO facility_roof_plan (facility_id, roof_plan) VALUES ('$facilityID', '$facilityRoofPlan')";
mysqli_query($dbc, $photoQuery)or die(mysqli_error($dbc));
}
And this is what my save_facility_roof_plan function looks like:
function save_facility_roof_plan($from, $to, $status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading a photo.";
return false;
}
I have done this in several other places and I have no issues uploading any images.
where am I going wrong here?
In your code, you have the line
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
But there is no variable $facilityPhoto anywhere in what you posted. My guess is that should be changed to $facilityRoofPlan since you set that path but never use it.
Then the $saved variable is never checked for errors which might have shown you why it isn't working.
Try:
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityRoofPlan, $status_msg);
if (!$saved) {
echo "Error saving roof plan image: {$status_msg}";
}
} else{
echo "Error uploading facility image.";
}

Upload file path no display

I have a problem with uploading path in my sql database. Not displaying all path.
This is the php code:
$rd2 = mt_rand(1000, 9999) . "_File";
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"));
$newname = "uploads/" . $rd2 . "_" . $filename;
if (!file_exists($newname));
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)));
$query = "insert into files (file_id,floc,subid,fname,fdesc,tcid)
values ($newstd,'$newname',
'".htmlspecialchars($_REQUEST['subid'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fname'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fdesc'], ENT_QUOTES)."',
'".$_SESSION['tcid']."')";
if (!#executeQuery($query)) {
if (mysql_errno () == 1062) //duplicate value
$_GLOBALS['message'] = "Given Subject Name voilates some constraints,
please try with some other name.";
else
$_GLOBALS['message'] = mysql_error ();
}
else
$_GLOBALS['message'] = "Successfully New Subject is Created.";
}
closedb();
The code is working and shows like this in database: http://i.stack.imgur.com/Z5jmb.png
It suppose to display uploads/2654_File_filename.docx
And the file is not uploaded.
The form is in a table:
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
</tr>
I used this:http://www.w3schools.com/php/php_file_upload.asp but same no working
I'm using xampp 5.6.8 and php.ini and file_uploads directive is set to On.
EDIT - newstd is:
$result = executeQuery("select max(file_id) as fid from files");
$r = mysql_fetch_array($result);
if (is_null($r['fid']))
$newstd = 1;
else
$newstd=$r['fid'] + 1;
$result = executeQuery("select fname as fid from files where
fname='" . htmlspecialchars($_REQUEST['fname'], ENT_QUOTES) . "'
and tcid=" . $_SESSION['tcid'] . ";");
// $_GLOBALS['message']=$newstd;
if (empty($_REQUEST['fname']) || empty($_REQUEST['fdesc'])) {
$_GLOBALS['message'] = "Some of the required Fields are Empty";
} else if (mysql_num_rows($result) > 0) {
$_GLOBALS['message'] = "Sorry Subject Already Exists.";
} else {
}
$rd2 = mt_rand(1000, 9999) . "_File";
...
...
EDIT: I forgot to mention that when i dont use a path he upload it in database.
I had a "global" form and i putted enctype="multipart/form-data" in it and it worked with saving the path in table.
Before was in form below and dont recognise it.
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
But still no uploading files...
Can you check if the file is not too large and exceeds the limitations of these two configurations:
post_max_size
upload_max_filesize
You can see the values from a file with:
<?php
phpinfo();
?>
Edit:
Another suggestion is to put the body brackets of the if's because the single line execution if the statement is valid, cant be trusted. I think the problem can be the :
if (!file_exists($newname));
Also the way you insert into the DB you take the name from the $_REQUEST and not the new name and where do you store the path ?

How To Upload two files in PHP

I'm trying to upload two file in one submit button using the following code:
<label>Logo Image *</label>
<input type="file" name="ufile[]"/>
<label>Banner Image *</label>
<input type="file" name="ufile[]"/>
PHP
$logo = $_FILES['ufile']['name'][0];
$block_img = $_FILES['ufile']['name'][1];
if ($_FILES['ufile']['name']["error"] > 0) {
echo "error<br>";
}
else {
if (file_exists("small-image/" . $_FILES['ufile']['name'][0])){
echo $_FILES['ufile']['name'][1] . "File already exists in server. ";
}
else {
move_uploaded_file($_FILES['ufile']['name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
}
}
$sql_query = "UPDATE header_img SET logo_img = '$logo', block_img = '$block_img' WHERE banner_id = 1";
My database is updating correctly but the file is not uploaded. Yes there is a 777 directory call 'small-image'.
Any idea?
Thanks.
When you use move_uploaded_file, you want to use $_FILES['ufile']['tmp_name'], that's where the file is currently located.
move_uploaded_file($_FILES['ufile']['tmp_name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['tmp_name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
Check the example in the docs: http://php.net/manual/en/function.move-uploaded-file.php

php file upload not working right

I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.

Categories