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.
Related
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!!!
I am trying to generate QR code for each users who signup for my website. I am going to send them QR code in email and they can use that QR code for sign-in. Doing some research work, I found phpqrcode. I tried the following code of lines, which is saving the name of the QR code image in the DB, but is not saving its image to the folder. How can I save the QR image into any folder(say for example: Uploads). SO once image is uploaded into the folder, I can easily send that image to the user.
So on submitting the register form, the following controller will be called and will save user as well as generate unique QR code for that user.
signupController.php
$user = \Model\User::loadFromPost();
if($user->save()){
$tempDir = $_SERVER['SERVER_NAME'].UPLOAD_PATH . 'qrcodes/';
$codeContents = $user->email;
$fileName = $user->id.md5($codeContents).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($codeContents, $pngAbsoluteFilePath);
$user->qrcode = $fileName;
$user->save();
} else {
echo 'File already generated! We can use this cached file to speed up site on common codes!';
echo '<hr />';
}
}
Here $_SERVER['SERVER_NAME'] is example.local/ (for Local) and https://www.example.com/ (for live server) and UPLOAD_PATH is contents/images/uploads. The above code, saves the name of QR code image file in DB but not saving the image of QR into the uploads folder.
Help is appreciated. Thanks.
You cannot have domain as your absolute path. The absolut path has to be path on your server.
So, replace the
$tempDir = $_SERVER['SERVER_NAME'].UPLOAD_PATH . 'qrcodes/';
with path in format such as
$tempDir = __DIR__.DIR_SEPARATOR.UPLOAD_PATH.DIR_SEPARATOR.'qrcodes/';
Of course, you need to modify the path according to your server setup but the __ DIR __ contains the path to the directory of the current file.
If you can specify the framework you are working on, I can help you modifying the path.
This is my folder layout on the server: http://gyazo.com/1331ac0aaaa444bdedad9e91a6dfe23d
I am trying to save an image into the "1" folder.
move_uploaded_file($file_tmp, $_SERVER["DOCUMENT_ROOT"]."/Backend/Sets/".$desired_dir."/".$file_tmp);
That is the line I am using to try to move the file I have uploaded.
I printed out the $SERVER["DOCUMENT_ROOT"] and it ends with "/hub" - which you can see in my screen shot.
The issue is that my image in saving inside the /Backend folder and not going further into the /Sets/1 folders.
All of my .php files are in the /Backend folder. So that may have something to do with it. I am really unsure.
Thanks,
Waq
EDIT:
Here is the block of code that I have changed it to on suggestion from another thread:
if(empty($errors)==true){
print("desired dir = ".$desired_dir);
if(is_dir("Sets/".$desired_dir)==false){
mkdir("Sets/".$desired_dir, 0700);
}
if(is_file("Sets/".$desired_dir."/".$Title)==false){
rename ($file_tmp,$Title);
move_uploaded_file($Title,"/Sets/$desired_dir/$Title");
I have made sure desired_dir = 1.
Still the same problem however.
Add some error checking:
$sets = $_SERVER["DOCUMENT_ROOT"]."/Backend/Sets/".$desired_dir."/";
if (!is_dir($sets))
throw new Exception("Not a folder: " . $sets);
move_uploaded_file($file_tmp, $sets . $file_tmp);
In this way you have a clearer picture of what's going on
I'm sure I'm doing something silly but I've checked and re-checked this. This is my photo uploader, meant to save the photo file itself to a folder (named "reccs"), and then save the name of the photo to a row in my DB. The DB part works perfectly, but my photo isn't showing up in the folder.
It displays no errors and appears to be working (I get the "success" message). Ack!
Code is below. Thanks for ANY insight.
$link = mysql_pconnect($host, $username, $password);
$db = mysql_select_db ($dbname);
$target = "reccs/";
$target = $target . basename($_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
mysql_query("UPDATE login SET recc = '$pic' WHERE username = '".$_SESSION['user']['username']."'");
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
try;
if(move_uploaded_file($pic, $target))
Depending on your server setup you may have to set $target to be an absolute path and not relative. At least it should be absolute to your home dir, so if reccs is a dir in your root site directory then set $target to /reccs/file.name.
The reason for this is that files are uploaded by defualt to /tmp, which is at the root (OS) level, not the hosted level, so paths relative to /tmp are generally meaningless.
saving photo with same name is very bad practice. I will suggest you to do below before uploading the foto.
extract name and extension.
now check that extension is valid or not. if valid then go further
first trim and then clear all multiple spaces with single spaces.
now lowercase filename and change all space with _ and append timestamp with filename.
remove all special characters ( ', " , \ etc )
now add filename with that extension .
then store into database
Should reccs have a forward slash in front of it? It would seem the mysql update query would be better inside the if statement , after you know the move_upload_file was successfull.
I am having a very difficult getting this working and I have yet to come up with a working scenario. Basically, this is a simple user-friendly admin which is supposed to upload an image. However, I can't get the upload to work. The filename is getting added to the database just fine but the image will not upload.
Here's the code as is:
function editMain($data){
array_pop($data);
$where = "main_id = {$data['main_id']}";
unset($data['main_id']);
//upload image
if ($_FILES['main_picture']['size'] > 1){ //if image deal with it
$data['main_picture'] = '/images/'.$_FILES['main_picture']['name'];
$uploadedfile = $_FILES['main_picture']['tmp_name'];
if (move_uploaded_file($uploadedfile, SITE_ROOT.$data['main_picture']))
echo "successfully uploaded {$data['main_picture']}<br />";
else
echo "failed to upload {$data['main_picture']}<br />";
}
Thanks for looking and thanks in advance for pointing me in the right direction!
SITE_ROOT needs to be a local directory, ie "C:\..." or "/home/...", it cannot be a URL structure. Change that to the local directory of where the file should be uploaded, check permissions, and you should be good to go.
I use it that way:
if(!is_dir($dir = $_SERVER['DOCUMENT_ROOT']."/fies_path"))mkdir($dir);
move_uploaded_file($_FILES['file']['tmp_name'],$src = $dir."/$file_name.ext");