php file uploading cannot retrieve the path - php

I am trying to upload photos in to folder uploads and its path to be recorded under photo in DB. This is my code:
$folder ="uploads";
$destFile = $folder . basename($_FILES["photo"]["name"]);
$sourdeFile = $_FILES["photo"]["tmp_name"];
if(move_uploaded_file($sourdeFile,$destFile)){
echo "File has been uploaded";
$photo = $destFile;
}else{
echo $_FILES['photo']['error'];
$photo = "images/default.png";
}
When I upload photos they successfully uploaded into folder but the problem is its path recorded as follow :
uploads42141402_1866830986743601_8538143552767524864_n.jpg
But to view photos in a page there should be \ next to uploads. So I tried to change my code as follow.
$folder = "uploads\";
But it generates this error
Can anyone say how to fix this ?

How about
$folder ="uploads/";
I've tried and it works. Maybe $folder ="uploads" . DIRECTORY_SEPARATOR; will better than "/".

For the error its looks uploads folder is not there or it not have permission
create a upload folder or try with absolute path
you can make use of dirname(__FILE__) or $_SERVER['DOCUMENT_ROOT'] for creating dynamic path

Related

how can i make an image file downloadable from apache server using php?

I don't know if this has been asked before, please pardon in advance.
I created an image compression web app using the tinyPNG API, and it works as intended - that is users can upload an image file and it is compressed and saved in the server.
But then I create a download functionality for the user to download/save the compressed image.
On clicking the download link it throws up an error:
can’t find the file at http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
Even though the compressed image is in the server.
Please help!!!
MY CODE:
require_once("vendor/autoload.php");
//makes PHP execute faster
set_time_limit(0);
//API key
\Tinify\setKey("API_KEY_HERE");
//Main code
if (isset($_POST['submit'])) {
//supported image formats.
$supported_image = array('image/jpg', 'image/jpeg', 'image/png');
foreach($_FILES['images']['name'] as $key=>$val){
$file_name = $_FILES['images']['name'][$key];
// get file extension
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
// get filename without extension
$filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);
if (in_array($_FILES['images']['type'][$key], $supported_image)) {
if (!file_exists(getcwd(). '/uploads')) {
$oldmask = umask(0);
mkdir(getcwd(). '/uploads', 0777, true);
umask($oldmask);
}
$filename_to_store = $filenamewithoutextension. '_' .time(). '.' .$ext;
move_uploaded_file($_FILES['images']['tmp_name'][$key], getcwd(). '/uploads/' .$filename_to_store);
$compress_file = getcwd(). '/uploads/' .$filename_to_store;
// optimize image using TinyPNG
try {
$source = \Tinify\fromFile(getcwd(). '/uploads/' .$filename_to_store);
$source->toFile(getcwd(). '/uploads/' .$filename_to_store);
//The code to show a modal for downloading the converted file.
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
}
}
echo "<a href=".$compress_file." download>Download</a>";
}
?>```
The problem in your code is, that you create the link with $compress_file that contains absolute path to the file.
/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg
So when the link is clickend and the url is resolved in browser the result is
http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
So if the localhost domain is pointed to /var/www/html/imgtest/ than the server is looking for the file in this path which doesn't exist:
/var/www/html/imgtest/var/www/html/imgtest/uploads/...
When you are generating the path to the compressed file you should put it's url into other variable where you wouldn't prepend the current directory.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
Then you should use the $compress_file_url instead of $compress_file when creating a link
echo "<a href=\"$compress_file_url\" download>Download</a>";
This should work assuming your localhost domain is pointed to /var/www/html/imgtest. If your localhost domain is pointed to /var/www/html you might need to prepend $compress_file_url with /imgtest before it's used to create a link.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
$compress_file_url = '/imgtest' . $compress_file_url;

Image is getting uploaded to the folder but not getting displayed - php upload image

I am trying to make the user upload the image and from my app and I am trying to upload it to the uploads folder. I have shown the folder structure below). I am able to save the image in the respective folder correctly and also able to store the name of the image-file into DB, but when I am trying to show that image into the user account, I am not able to make it visible. I think I am messing up with the PATH.
Folder structure:
htdocs
demo_app
app
config
config.php
controllers
core
views
models
uploads
userImage
.htaccess
public (This is a root folder)
assets
css
js
images
uploads
userImage
index.php (This is a root index file)
.htaccess
vendors
.htaccess
So with the above folder structure, I have tried couple of things:
Uploading the image to the userImage folder (app/uploads/userImage/), and I was able to upload an image successfully to this folder. But when I tried to display it, I am not getting any image.
I also tried uploading and storing the image to the userImage folder (/public/assets/uploads/userImage/), but this time I was not even successful to store it in the folder.
Following code snippets is from both of my tries.
config.php
<?php
$site_url = '/';
define('SITE_URL', $site_url);
define('APP_ROOT',dirname(dirname(__FILE__))); // (Path to 'app' folder)
define('URL_ROOT', 'http://localhost/demo-app');
// Following path is to upload image to public/assets/uploads/) folder
define('UPLOAD_PATH',
dirname(dirname(dirname(__FILE__)))."/public/assets/uploads");
controller (userController.php)
$img_name = $_FILES["image"]["name"];
$upload_folder = APP_ROOT . "/uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);
// The above uploading code works perfect for me to upload the image to app/uploads/userImage/ folder
// Following code doesn't work for me to upload it to the public/assets/uploads/userImage folder
//Approach 2
$upload_folder = UPLOAD_PATH . "/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);
**View (index.php) **(app/views/users/index.php)
// Following for showing image from app uploads folder
<?php $img_path = APP_ROOT . "/uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">
// Following for showing image from public uploads folder
<?php $img_path = URL_ROOT . "/assets/uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">
I think I have problem with the PATHs, so if anyone can help me with this, it would be great. Appreciate in advance.
Assuming the file userController.php is inside the controllers folder. Change your first part to
$img_name = $_FILES["image"]["name"];
$upload_folder = "../uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);
and change your second path to
$upload_folder = "../../public/assets/uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);
For displaying, your file is in app/views/users/index.php, so do this
<?php $img_path = "../../uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">
<?php $img_path = URL_ROOT . "/assets/uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">

Upload image to a folder

In my localhost image is uploading to folder and path is saved in database, It is working in local server but on godaddy server it is saving path in database but not uploading image into a folder. Give suggestion how can I solve this..
$temp = explode(".",$_FILES['company_logo']['name']);
$newfilename = rand(1,999999999) . '.' .end($temp);
$source=$_FILES['company_logo']['tmp_name'];
$destination='images/'.$newfilename;
#move_uploaded_file( $source , $destination );
$query2="insert into zoho_customers (company_logo)values('$destination')";
$res2=mysqli_query($con,$query2)or die(mysqli_error($conn));
where company_logo specified as below
<input type="file" name="company_logo"/>
The problem is destination $destination contain the image file.
move_uploaded_file($_FILES["company_logo"]["tmp_name"], "images/" . $_FILES["company_logo"]["name"]);
You can get a clear idea here
https://www.w3schools.com/php/php_file_upload.asp

How to store uploaded files in a directory of the main domain from a subdomain upload form

please how can store uploaded file in my main domain directory should it be like this:
move_uploaded_file(https://example.com/uploads)
First step is to start here with handling uploaded files:
http://php.net/manual/en/function.move-uploaded-file.php
The first example is almost exactly what you want:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:
$uploads_dir = __DIR__ . '/../public_html/uploads';
__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.
The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)
Im assuming youre uploading an image. if not make the changes as necessary
chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder
$filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
if (!file_exists($filepath)) {
mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
}
chdir($filepath);
$filename = 'file_name_you_want';
$info = pathinfo($_FILES['img']['name']);
$ext = $info['extension'];
$newname = $filename . "." . $ext;
$types = array('image/jpeg', 'image/jpg', 'image/png');
if (in_array($_FILES['img']['type'], $types)) {
if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
$img_path = 'images' . DIRECTORY_SEPARATOR . $newname;
} else {
// do what needs to be done
}
If youre using php 7 you might want to take a look at string
dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__

PHP bot assigning upload path

I'm having an issue where the path of my file upload isn't being assigned to the correct folder. It actually amends the file path to the file name of the file being uploaded. Weird right? Here's the code I'm working on...
<?php
$allowed_filetypes = array('.mp4','.gif','.bmp','.png','.html','.psd','.zip','.xml','.css','.js',);
$max_filesize = 5904288;
$upload_path = 'video';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('Sorry, cannot take files over blankKB.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('Sorry, cannot take files over blankKB.');
if(!is_writable($upload_path))
die('We are very sorry, a problem is occurring with the CHMOD of this directory');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo ' Your file was uploaded successfully, view it here';
else
echo 'Sorry, but there was an error during the file upload. Please try again.';
?>
Here's what the file looks like after being uploaded,
videoHello.png
plus it doesn't upload the file to the directory I want it in, located at /video
When you write $upload_path . $filename you are only concatenating the two strings, which does indeed result in videoHello.png;
You should either concatenate your system's directory separator (On Unix based systems it's /)
$upload_path . '/' . $filename
or build the separator into your string $upload_path
$upload_path = 'video/';
Though my final advice would be to use Absolute Paths like this:
$upload_path = dirname(__FILE__) . '/video/';

Categories