Issue with uploading file from local file system to php server - php

I am trying on upload file from local file system to a remote server using php.
I am using move_uploaded_file function but when i select a file on my local file system, it tries to find the file on remote server and hence fails. maybe i am missing something. Let's say if i am trying to upload a file from C:\Data\abc.txt. It tries to find the file on /server/abc.txt and hence fails to upload the file. Please let me know if i am missing something.
<?
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$original = $root_path .$file_name;
echo $_FILES['image']['tmp_name'];
if($file_size > 100097152){
$errors[]='File size must be less than 100 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp, '/uploads');
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>

I dont know if I have understood you correctly, but you means with remote server your webserver?
This server doesnt access your file system directly because of your browser's sandbox mode. It gets only the submitted file, the origin path doesnt matter.
The second parameter of the function move_uploaded_file has to be the target file, not the target dictionary.
Example:
move_uploaded_file($file_tmp, '/uploads/' . $file_name);

diffcult to answer pls tell me the php version and as a hint: have you checked is_uploaded_file() php.net/manual/function.is-uploaded-file.php

could help to use the error/status-reporting in $_FILES['image']['error'] - gives feedback on error/status code of your file upload, so you can better understand what the source of the problem possibly is:
0 = success
1 = file too big (php.ini set)
2 = file too big (max file size directive)
4 = no file was uploaded
6 = no access to temp folder on server
7 = file could not be written to server
8 = upload stopped by a php extension
hope that helps

Related

Permission issues viewing photos uploaded with php

I'm following a tutorial for uploading image files using php on udemy. I can choose an image and upload it to a folder without any problems.
When I click on the image after it has been uploaded to the folder, windows photo viewer says: "photo.png It appears that you don't have permission to view this file. Check the permissions and try again".
When I checked permissions it said "You must have read permissions to view the properties of this file".
I used the chmod function set to 0755, which allows the owner to read and write, and lets everyone else read it. I tried changing the chmod codes but it didn't help.
I'm thinking it has something to do with my server permissions, but can't find any solution on google. My images are uploaded to Abyss Web Server.
Here is the code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function upload_file() {
//setup
$tmp_name = $_FILES['file']['tmp_name'];
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['file']['name']);
$max_file_size = 5000000; //5mb
$allowed_file_types = array('application/pdf; charset=binary');
$allowed_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
//check if image type is allowed
$image_check = getimagesize($tmp_name);
if(! in_array($image_check[2], $allowed_image_types)) {
//if not allowed image check if allowed file type
exec('file -bi' . $tmp_name, $file_check);
if(! in_array($file_check[0], $allowed_file_types)) {
return 'This file type is not allowed';
}
}
//check if file already exists
if(file_exists($target_file)) {
return 'Sorry that file already exists';
}
//check file size
if(file_exists($target_file)) {
return 'Sorry this file is too big';
}
//store the file
if(move_uploaded_file($tmp_name, $target_file)) {
chmod($target_file, 0644);
return 'Your file was uploaded';
}
else {
return 'There was a problem storing your file. Try again?';
}
}
if(! empty($_FILES)) {
echo upload_file();
}
?>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file">
<input type="submit" Value="upload">
</form>
Since loading the file using a custom made HTML page specifically for testing motives does show the image correctly, then it's most likely a hotlink protection issue. (This was found out after a few comments to the question).
In cPanel, for example, there is a tool to manage this feature and it revolves around the usage of a file called .htaccess. This file is used for a lot of things in the web development world.
Some people don't like their copyrighted images to be accessed, so one way to avoid inexperienced people (let's say, "people in userland") from doing that is to enable this protection. This works for any given file extension that you set it up to.
One way to address this issue is to go to cPanel and disable (or modify accordingly) the Hotlink Protection feature. Another way, is to find the .htaccess file that is causing the issue, which requires understanding the way it works and the syntax it uses.

Why is my PHP file upload code not working?

I am trying to make a simple file upload form using PHP. Here's my code:
<?php
$uploads_dir = '/uploads';
if(isset($_FILES['thefile'])){
$errors= array();
$file_name = $_FILES['thefile']['name'];
$file_size =$_FILES['thefile']['size'];
$file_tmp =$_FILES['thefile']['tmp_name'];
$file_type=$_FILES['thefile']['type'];
$tmp_name = $_FILES['thefile']["tmp_name"];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($tmp_name, "$uploads_dir/$file_name");
echo "Success";
}
else{
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="thefile" />
<input type="submit"/>
</form>
</body>
</html>
I realize that I'm not limiting file types, but I'll worry about that once I can get a simple .jpg or .zip file uploaded. Using the above code, I go to the page on my local server located at
C:\wamp\www\simpleupload (this contains index.php, the file posted above)
When I select a small image file and click submit, I'm presented with the following errors:
Warning: move_uploaded_file(/uploads/session_timeout_formatting_bug.png): failed to open stream: No such file or directory in C:\wamp\www\project_fileshare\index.php on line 18
and
Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpEFDE.tmp' to '/uploads/session_timeout_formatting_bug.png' in C:\wamp\www\project_fileshare\index.php on line 18
Line 18 is the line that calls the move_uploaded_file() function.
How do I fix this error? I have an 'uploads_dir' folder located in the same folder as my index.php file. (reference the file path above). What am I doing wrong here? I must be misunderstanding some small part of this process and have put my directory in the wrong place, or I'm doing something wrong in the code.
Can someone spot my mistake and tell me what I need to do to fix it?
You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).
Since you are working in windows and your document root is C:\wamp\www\simpleupload
Which means, your files are located like this:
C:\wamp\www\simpleupload\index.php (your upload script)
C:\wamp\www\simpleupload\uploads (where the files should be uploaded)
Why don't you use absolute path like this:
$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';
The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads
Try this.
If your upload directory is in the same location as your index.php remove the "/" in your $uploads_dir variable. This, or add a "." before the slash because now it refers to the root which might be something else then your current working directory. Speaking of the devil; http://php.net/manual/en/function.getcwd.php
$uploads_dir = getcwd() . '\uploads';
$uploads_dir = __DIR__ . '\uploads'; #php > 5.6
Also, check if your directory is writeable for php:
http://php.net/manual/en/function.is-writable.php
Also what Latheesan said, better to go cross platform as I made the same mistake seen in my edit.
<?php
function buildPath(...$segments){
return join(DIRECTORY_SEPARATOR, $segments);
}
echo buildPath(__DIR__, 'uploads');
?>
And i would change
if(isset($_FILES['thefile'])){
for this
if($_FILE['thefile']['error'] === UPLOAD_ERR_OK){
Because I think that this is the best way to know if the user upload a file or the input is blank.
Or
if (isset($_FILE["thefile"]["name"])){

Error during uploading a file with php

Ok, I used google over the last 2 days and didn't got what is wrong with my code. First it seemed that I used the wrong path but the official "Hilfe Center" (like helping center or so) from 1&1 said that this must be the right path "e:\Kunden\Homepages\11\d12345678\www\UploadTest" (obviously you have to adapt it to your path, which i got throught phpinfo() )
so I'm using the following code:
<form action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"datei\"><br>
<input style=\"position:absolute;left:5px\" type=\"submit\" value=\"Hochladen\">
</form>
on the site where you upload the file and
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = "e:\\Kunden\\Homepages\\11\\d12345678\\www\\UploadTest";
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.'); // if we upload large file then we get error.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.'); // if we have no enough permission then got error.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)){
// if everything is fine then we upload file and go to somewhere else
header ('location: whereeveryouwantogo.php');
} else {
echo 'There was an error during the file upload. Please try again.';
}
on the site where the php script is running (upload.php). I got the code on another thread here and wanted to use it for troubleshooting. Later I'm going back to my own code.
I am now at the last error:
'There was an error during the file upload. Please try again.';
I just want to upload .txt files that are later used on a news based site. Thx for any helps in advance!
I think the problem is name of the input or name of the files variable.
$files=$_FILES['datei']['tmp_name'];

PHP Upload File - right code but can't find the file/path

First question for quite a while. Essentially, I've got some code that (1) works perfectly in the live environment, (2) used to work in my home OSX environment but (3) doesn't work now.
The HTML:
<form id="upload_form" action="php/upload_class_list.php" method="post" accept-charset="UTF-8" enctype="multipart/form-data" target="upload_target" >
<label>File:</label>
<input name="myfile" type="file" size="35" />
<input id="upload_submit" type="submit" value="Upload" />
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
The PHP file:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
...
}
sleep(1);
?>
<script language="javascript" type="text/javascript">top.upload_class_list(<?php echo $result; ?>);</script>
The script fires at the end, but the PHP code doesn't enter the if (in the local development environment) and so $result remains at 0.
It seems it's not picking up the path of the file to be uploaded; $destination_path points to the folder where the PHP file is located, and not where the file is found.
I think my local environment may have stopped working when I changed to Mountain Lion and rebuilt the PHP setup.
What is missing to stop the file being found?
Let me emphasise: exactly the same code works fine in my live Hostmonster setup, so it's an environment problem, I guess :)
Thanks.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
...
}
What is missing to stop the file being found?
What makes you think the problem is the file being found? Maybe the file is found, but what fails is the move... for example because the Web server has no permissions to write into the target_path.
You can check:
$src = $_FILES['myfile']['tmp_name'];
$dst = $target_path;
if (!file_exists($src))
die("Okay, the file is actually not found");
if (!is_readable($src))
die("Very bad hosting juju. The file was uploaded but I can't read it?!?");
if (!is_writeable($destination_path))
die("As expected, you can't upload a file here. This is a good thing.");
#touch($dst);
if (!file_exists($dst))
die("So call me a Marine, the file SHOULD be writeable (which is not so good), and yet I could not write it! Perhaps disk full? User overquota? Some weird security setup?");
The reason why it's a good thing is because that directory holds executable PHP files, and if anyone could upload a PHP file in there, well, that would be a major security hole.
You can set aside another directory and make it writeable (remember to put in there a .htaccess or other system to prohibit read/execute access from the outside).
may be this
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>

PHP error uploading file

Okay, so I set up an upload engine for a website so that an authenticated user can upload a audio file (a key) for a song in the library, but I come across this strange problem when I try to upload any file over 5MB.
I set my php.ini max filesize to 50MB by the way
Everything uploads properly, but there is no data associated with the file on the other end.
HTML CODE:
<form action="keyUpload.php?id=<?php echo $id;?>" method="post" enctype="multipart/form-data">
<p style="color:#fff;font-size:30px;font-family:Times">
Add a new Key:<br/><input name="uploaded" type="file" id="file"><br />
<input type="text" name="kname" id="kname" value placeholder="Key Name (Ex. Demo, A#, etc.)" style="width:300px;"><br/>
<button class="button">Upload File</button><br/>
<span style="font-size:12px;">*Max Filesize is 50 MB*</span>
</p>
</form>
PHP CODE:
<?php
$id=$_GET["id"];
$name=$_POST["kname"];
$name = str_replace(" ","%20",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
Both $filename and $ext are empty variables when I upload a file larger than 5 MB. In all other cases, this engine works perfectly.
When echoed, simply nothing happens, so obviously the engine will not save the file if it doesn't exist. What's going on?
var_dump:
array(0) { }
Thanks for all your help!
Check for upload errors:
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['uploaded']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
As well, do NOT use filenames to validate the uploads. It is beyond trivial for a malicious user to fake a filename and upload malicious files, eg.
ren nastyvirus.exe good_tune.mp3
And don't use string operations on filenames. There's a whole whack of PHP functions for filename manipulation, e.g. http://php.net/basename
Set max_post_size in php.ini as well.

Categories