move_uploaded_file - File only changed after directly loading that page - php

So, I'm making a chat room and I want to allow my users to upload a profile image. I know the AJAX is working, and the file is being uploaded and moved to users/[their username], but on other accounts their profile image isn't changing to the new one until they load up the actual profile image.
It's kind of confusing, so I'll simplify it:
User successfully changes profile image (file is uploaded)
Same user goes back to the chat room and the their profile image has changed
New user who was on the chat room before the new profile image was uploaded reloads the page to find the profile image of the other user is still the same.
Also, I've found if the second user goes to the file that contains the other user's profile image, it hasn't changed, but on reloading the image file it does. It's very confusing and I have no clue why all this is happening. There aren't any errors either. Here's my code:
(I've also tried copy instead of move_uploaded_file)
if(!isset($_FILES["profileImage"])){
echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
die("No image recieved.<br>Automatically redirecting in 3 seconds...");
}
$target_file = "users/" . $username;
$file = $_FILES["profileImage"];
if(!exif_imagetype($file["tmp_name"])){
echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
die("File type not an image.<br>Automatically redirecting in 3 seconds...");
}
if(filesize($file["tmp_name"]) > 2000000){
echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
die("Image size over 2MB (".(round(filesize($file["tmp_name"])/100000)/10)." MB)<br>Automatically redirecting in 3 seconds...");
}
/*Deletes file if it exists*/
if(file_exists($target_file)){
unlink($target_file);
}
if(move_uploaded_file($file["tmp_name"], $target_file)){
echo "The file '" . basename($file["name"]) . "' has been uploaded to " . $target_file . "<br>Automatically redirecting in 3 seconds...";
} else {
die("Error in file upload.<br>Automatically redirecting in 3 seconds...");
}
Also, in the code it looks like $username and $password aren't defined, but they are defined earlier. Please help, I have no clue what's going on.
Finally, this needs to be able to override pre-existing files, I want the user to be able to change their profile image.
Thank you so much!!!

Related

Image cannot be display after uploading

Previously, when I tried uploading image into the database, the image won't display. When I check the path in the db and in the folder, it is correct.
Correct path in db and folder.
And then when I tried to view the image that has been uploaded it says that I don't have the permission to view it.
I have also tried uploaded different photo extension and different photo viewer application and I still cannot view the image. Apart from that, I have tried
W3School PHP5 File Upload. Again same thing happen, I cannot view my image.
This is my code :
if (!isset($_FILES['image']['tmp_name']))
{
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$location= $_SERVER['DOCUMENT_ROOT'] . '/ehars/photo/' . $_FILES["image"]["name"];
move_uploaded_file($_FILES["image"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'] . '/ehars/photo/' . $_FILES["image"]["name"]);
mysql_query("INSERT INTO photo (location,emp_id) VALUES ('$location','$emp_id')");
}
Why can't I view my image? Is it because of the document root? Or is it something else? Please help me thank you.
UPDATED :
Based on the image below, my code (as shown above) is inside the admin folder. The reason why I would like to save my images in /ehars/photos so that, every level of user, admin admin2 and user can view the same photo that has been uploaded. If you could advice me what is the best way to do in order to achieve my objective above. Thanks again!
If your URL scheme is not "file://", you should authorized your browser.
I remember that you can't easily link CSS and image to the local machine due to security reasons.
change your code into this
if (!isset($_FILES['image']['tmp_name']))
{
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$location='/ehars/photo/' . $_FILES["image"]["name"]; //remove $_SERVER['DOCUMENT_ROOT']
move_uploaded_file($_FILES["image"]["tmp_name"], '/ehars/photo/' . $_FILES["image"]["name"]); // remove $_SERVER['DOCUMENT_ROOT'] .
mysql_query("INSERT INTO photo (location,emp_id) VALUES ('$location','$emp_id')");
}
why tou should change your code, because your server not gonna read windows path (c:/apache/htdocs/yourimagespath/yourimages.jpg); it should read (/images/yourimages.jpg), i asume htdocs is your root directory. and the result in your database is /ehars/photo/yourimages.jpg not c:/apache/htdoc/ehars/photo/yourimages.jpg.
hope it help you.

File can be opened in FTP but not in HTTP after upload from site

I am writing a PHP script that enables a user to upload a picture and then displays it on their page. Everything works fine up until the part where they need to display it. I run the form and submit it and the picture shows up in the directory in my FTP. I can download that file from the FTP and view it on my computer. I can visit the FTP url of that image, login and see it fine.
When I go to the HTTP version of the exact same URL, I get a 404 error. I have checked the permissions on the folder and it's ok to read and write for a user. I even checked the permissions on the file itself after it's uploaded and it's fine. Here's my PHP code when uploading the file:
<?php
include('connect.php');
$user_id = $_SESSION['user_id'];
if($_POST['submit']){
//GET FILE ATTRIBUTES
$name = $_FILES['myfile']['name'];
$size = $_FILES['myfile']['size'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name){
//start upload process
$location = "pics/$name";
move_uploaded_file($tmp_name,$location);
$sql = "UPDATE tbl_name SET imagelocation='$location' WHERE user_id='$user_id'";
$query = $mysqli->query($sql);
header('location:profile.php');
}
else{
die("Please select a file! <a href='profile.php'>GO BACK</a>");
}
}
?>
Any idea what this could be? I haven't seen this problem before.
i think folder permission may not be right when you created the folder with mkdir(). hope setting right permission will solve the problem.
It works now. I deleted the folder and recreated the folder with the same name. The folder was initially created through mkdir in PHP so I'm sure that had something to do with it. If anybody has any insight into why the folder wouldn't work with mkdir, feel free to post here. Thanks!

Error with Image field

This script is giving error if name field and file field is same. That if I want to upload file with a.jpg and name field is also a than its giving error of rename. Let me know to remove this problem and help to remove previous file.
$username=$name ;
move_uploaded_file($_FILES["pic"]["tmp_name"],"albumpic/".$_FILES["pic"]["name"]);
$ext=substr($_FILES["pic"]["name"],strpos($_FILES["pic"]["name"],"."));
if(file_exists("albumpic/$username$ext")) { unlink("albumpic/$username$ext"); }
rename( "albumpic/".$_FILES["pic"]["name"],"albumpic/$username$ext");
$newphoto="$username$ext";
//var_dump($photo);
$err="";
This is horribly bad code. You first move the user-provided file, which overwrites anything that was there before. You extract the file's extension in an unreliable manner (think of what happens if someone uploads mypic.jpg.exe). You then rename the uploaded file AFTER it's possibly trashed something what was there before.
Consider the case that you've got users "Joe" and "Fred" with profile pictures "joe.jpg" and "fred.jpg". What if Fred uploads a new profile picture called "joe.jpg". Your system will destroy Joe's image.
Try this instead:
$ext = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION);
if (file_exists("albumpic/$username$ext")) {
unlink("albumpic/$username$ext");
}
if (!move_uploaded_file($_FILES['pic']['tmp_name'], "albumpic/$username$ext")) {
die("Unable to move user $username's picture to album directory");
}

Php File upload, rename file, and then return new filename on 'successful upload' page?

I'm trying to return the name of a file uploaded using PHP after changing image files name upon uploading it.
I thought I could create a $_session['image_name'] and then call that session up on the subsequent "successful upload" page. I can't seem to get it correct. I need the name so that I can store it in the mysql database. Here's the part of my upload code that does the renaming and my attempt at creating a session:
/
/ make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
$_SESSION['image_name'] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'];
}
On my successfulUpload php page I was returning:
<p>Congratulations! Your file <? echo $_Session['image_name']; ?> upload was successful</p>
I have session_start(); at the very top of both the uploadProcessing code and the Successful uploads page.
Thanks for any help!
I see now, on your success page, $_SESSION should be capitalized.

Uploaded photo results in "500 Internal Server Error" - PHP/IIS7/Windows Server 2008

I recently moved a website that was written for a LAMP environment to Windows Server 2008. I've managed to get just about everything working now, but I've got one last problem that I can't seem to solve.
I am letting the admin user upload a photo that will get resized to a large file and small file by the PHP script. Both files are getting uploaded perfectly but the large file won't display and will result in a "500 internal server error" when viewed?
I can log onto the server and open both the small and large file, but only the small file is showing on the website? I've copied the PHP script below but the permissions on both files seem to be the same.
I'm using PHP, IIS7 and Windows Server 2008. Hope someone can help,
Steven.
// only process if the first image has been found
if(isset($image_file)) {
// get photo attributes
$image_filename = $image_file['name'];
$image_temp = $image_file['tmp_name'];
$image_ext = substr($image_filename,strpos($image_filename,'.'),strlen($image_filename)-1);
// validate photo attributes
if(strtolower($image_ext) == '.jpg' && filesize($image_temp) <= 4194304) {
// create custom timestamp
$image_timestamp = date('dmYHis');
// clean up filename
$image_filename = trim(str_replace('\'','',$image_filename));
$image_filename = str_replace('\\','',$image_filename);
$image_filename = str_replace('&','',$image_filename);
$image_filename = str_replace(' ','-',$image_filename);
// set file names
$image_large_file = strtolower($image_timestamp . '-large-1-' . $image_filename);
$image_small_file = strtolower($image_timestamp . '-thumb-1-' . $image_filename);
// image url source
$image_source = $_SERVER['DOCUMENT_ROOT'] . '/images/';
// upload image file
if(move_uploaded_file($image_temp,$image_source . $image_large_file)) {
// resize, save & destroy LARGE image
list($image_width,$image_height) = getimagesize($image_source . $image_large_file);
$image_container = imagecreatetruecolor(420,315);
$image_temp = imagecreatefromjpeg($image_source . $image_large_file);
imagecopyresampled($image_container,$image_temp,0,0,0,0,420,315,$image_width,$image_height);
imagejpeg($image_container,$image_source . $image_large_file,75);
imagedestroy($image_container);
// resize, save & destroy SMALL image
list($image_width,$image_height) = getimagesize($image_source . $image_large_file);
$image_container = imagecreatetruecolor(90,68);
$image_temp = imagecreatefromjpeg($image_source . $image_large_file);
imagecopyresampled($image_container,$image_temp,0,0,0,0,90,68,$image_width,$image_height);
imagejpeg($image_container,$image_source . $image_small_file,100);
imagedestroy($image_container);
}
else
$status = '<h3 class="red">Sorry, but there was a problem uploading one of the images to the server</h3>';
}
else
$status = '<h3 class="red">Please check that all the image size\'s are less than 4MB and they\'re all in JPG format</h3>';
}
I know this questions was asked 4 years ago, but I just ran into this same problem, and thought I'd leave an answer for anyone who may come here later.
I found an answer here, but the basic premise is to modify the permissions of the temp folder that PHP initially uploads into. Allowing the IUSR account read access to the temp folder will allow them to view the file when it hits its final destination. Supposedly IIS7 will grant the permissions from the temp folder to the temporary upload file, which, when moved to your website directory, will keep those temp folder permissions.
Security-wise, you are allowing read access to your temp folder; so if you have sensitive information that ends up there at any point, you may have to find another solution.
A little more information can be found here
I got stuck into the same problem and i think this will help somebody
Right-Click uploads directory / folder and select ‘Properties’
Go to ‘Security’ tab
Click Edit
Select ‘IUSR’ under group or user names
Select ‘Read & Execute’ under permissions for IUSR
Click ‘Apply’ and ‘Ok’
Found this on http://wingedpost.org/2016/07/preventing-500-internal-server-error-uploaded-files-iis-php-sites/

Categories