PHP File Copy() Not working on IIS 6 - php

I have the following code that attempts to take a users form input of a file, and upload it to the webserver.
This code does work on a Apache server, however I'm now trying to get the same code working on my Windows IIS 6 web server, which has PHP (Version 5.2.3) installed and working. I have set the PHP.INI file so that
file_uploads = On
upload_tmp_dir = "C:\Temp"
My form is
<form method="POST" action="do_upload.php" enctype="multipart/form-data">
<input type="file" name="img1" size="30">
<input type="submit" name="BtnUpload" value="Click To Upload Now">
</form>
My PHP code to do the upload is
$abpath = "C:\MyWebs\Website1\httdocs\images";
#copy($img1, "$abpath/$img1_name") or $log .= "Couldn't copy image 1 to server";
if (file_exists("$abpath/$img1_name"))
{
$log .= "File 1 was uploaded";
}
else
{
$log .= "File 1 is not an image";
}
For some reason when I check the value of $img1 e.g echo $img1; it is empty. Therefore I tried to get the file using $_FILES['img1']['name']. This worked fine, but still I couldn't upload any files
Any ideas why this is happening.

Your code should be:
move_uploaded_file($_FILES['img1']['tmp_name'], "$abpath/$img1_name");
Don't copy() uploaded files. There are a few edge cases where an uploaded file can be tampered with, which is why move_uploaded_file() exists - it checks for those particular types of tampering.
As well, be VERY careful with how you create your filenames when processing the upload. If you directly use ANYTHING provided in $_FILES as part of the destination path/name for the file, you are opening bad security holes on your server, and a malicious user can exploit that to scribble a file anywhere they want on your server.

Related

How To Open Target File Or Folder In PHP

How to open a specific folder in file explorer using PHP, I already tried some code but it just directing to random folder. Please help me.
I have try some code
if(empty($_POST['importdata'])) {
//Bahagian Kekotak Papar Button Import -mula-
echo '<form action = "" method="POST" name="upload_excel" enctype
="multipart/form-data">';
echo '<fieldset>
<legend>Jadual Import Data Pelajar</legend>
<label>Pilih Fail (CSV) </label>
<input type ="file" name="file" id="file">
<input id="buttonon" type = "submit" name="importdata" value="UPLOAD &
IMPORT"></fieldset>';
echo '</form>';
}else{
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"]>0) { //jika ada fail CSV
//jika fail CSV telah dipilih
$file = fopen($filename,"r");
while (($getData = fgetcsv($file, 1000, ",")) !== FALSE)
{
}
(this should be a comment, but its too long)
Reading the manual is always a good place to start.
Allowing user direct access to write files on your webserver is inherently very dangerous. The way PHP implements file uploads mitigates many of the risks.
How to open a specific folder in file explorer using PHP
The sentence makes no sense.
Files exist in folders, not the other way around. Do you really want PHP to open up (Micorosf) File explorer showing the directory containing a nominated file? Do you mean to create a copy by "uploading" it from your client? Your code example does not use nominated files / does not attempt to invoke other programs on the host.
it just directing to random folder
No. File uploads always go to the location nominated in your PHP.ini. If no directory is nominated, PHP puts the files in your system temp directory (as determined from your environment variables). And you can determine that location from dirname($_FILES["file"]["tmp_name"])

PHP upload files to remote server

I am completely a novice in all this ...
I have created a Social Networking project in which there is a module which allows user to upload photos..
I have hosted this project in my college server
I access that server using bitvise client with my server credentials.
My problem is i don't know how to setup upload mechanism for remote server ... In my localhost i simply use
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
function but i don't know how to do this for remote server ...
I tried FTP by looking at some tutorials but that didn't worked for me.
In my project structure there is a directory
users/user_id (diff for all users)/photos
here i want to place the uploaded files....
A proper description with example and proper functioning might be very helpful for me.... Thank you
EDIT:
Below is my code.
Photos.php
<form class="input-group-btn" method="post" action="editPhotos.php"enctype="multipart/form-data" id="myForm">
<input type="file" name="file" id="imgInp">
<button type="submit" class="btn btn-primary" name="form-submit">Done</button>
</form>
editPhotos.php
if( isset($_POST['form-submit']) ){
$target_file = "users/".$email."/pictures/Photos/" . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$img =str_replace(" ", "",basename($_FILES["file"]["name"]));
rename($target_file, "users/".$email."/pictures/Photos/".$img);
header('Refresh: 1; url=Photos.php?user='.$email);
}
Small tutorial how to upload file.
For sure, you need correct encryption and file's type in your form (ommited other fields, to clear example):
form.html
< form action="upload.php" method="post" enctype="multipart/form-data">< /form>
< input name="test" type=file>
upload.php
In $_FILES you have all data of uploaded file. In given example, we have field named test.
Advice, to always first check error $_FILES['test']['error'] - the values you can find in here.
If this is correct, then prepare upload path. Some advices:
remember that if you use original filename ($_FILES['test']['name']), then is User upload second file, with same name, you will need overwrite file or ignore upload. Other way, is to save data to database and generate temporary name form him.
destination path(target_file) - regardless if upload folder is in the same catalog, you should always use global path, as good practice. You can use DIR for that.
don't use in path data, like email - is you have project, and want give opportunity to change email in configuration, what you will do with files? Better save user to Database and use his ID as key.
If you have path, then you simply need only use of move_uploaded_file, but remember to check result, as it not always will return true. You can have error, when you don't have permissions to destination folder (you'll need debug this).
I see that you, first upload file, then rename (then you should check, if rename was success). Don't extends this process, if it not necessary. Upload file for final path and name.
Example of code (I this rattle off)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$fileName = basename($_FILES["file"]["name"]);
$fileName = str_replace(" ", "", $fileName);
$target_file = sprintf(__DIR__ . "/users/%s/pictures/Photos/%s", $email, $fileName);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// File was uploaded
header('Refresh: 1; url=Photos.php?user=' . $email);
} else {
// File was not uploaded;
throw new \Exception('File was not uploaded. Check warnings.');
}
}
Used other method to check, if this is POST
use method sprintf, for better code quality
checked effect of move_uploaded_file
use global path for destination file
Below code is risky in live environment, please use cautiously
Use a relative path to the uploads folder. For example, if your uploads folder is placed outside your current folder. Then
$PATH = '/absolute/example/path/to/uploads';//from config file
$target_file = "$PATH/file_name";
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
The above code will work both in local and remote server.
Other checks are below:
Check for errors while uploading file in server
To enable error handling use below code in your upload logic:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Another important note is to make uploads folder writable otherwise file upload wont work.

Upload error - file is not writable

I want to upload multiple files to the server.
As far as I can see files are not writable.
What can I do so my code can actually work and upload files.
PHP:
if(isset($_FILES ['uploaded_files']))
{
foreach($_FILES['uploaded_files']['name'] as $key=>$value)
{
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{
$filename = $_FILES['uploaded_files']['name'][$key];
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
{
//code
}
else
{
die ('There was a problem uploading the pictures.');
}
}
else
{
die ('There is a problem with the uploading system.');
}
}
}
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="input_clone_id" name="input_clone_id" value="'.$row['id'].'"/>
<input type="hidden" id="input_clone_var" name="input_clone_var" value="V"/>
<input type="file" name="uploaded_files[]" id="input_clone" multiple="multiple" /><br />
<input type="submit" style="margin-left:0" value="Upload Files" />
</form>
I see two problems with this. The first is a security issue and the second is probably what is causing your problem
You have a security problem here:
$filename = $_FILES['uploaded_files']['name'][$key];
...
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
...
Problem a: Since $filename comes from the $_FILES array, it CANNOT be trusted. The user told your site what the name of their file was and put it there. They could feed you some bogus filename that could cause your script to fail in interesting ways. You need to sanitize that filename before using it in any way.
Problem b: By allowing the user to specify the filename, they could potentially overwrite other files in your "images/gallery" directory simply by specifying a conflicting filename. The way to avoid this is to use a database, generate a unique identifier for the uploaded file, store the file under that unique name, and in the database keep a record of the original filename and other information. That way you always know what the original filename was and you don't have the chance of someone trying to overwrite files in that directory.
Writing problem:*
Your "check for writable" statement is wrong. The filename that comes back is the one that the user used when submitting. This will not point to any point on your filesystem...it points to a spot on theirs (sometimes) which you cannot see. What you need to check is that your "../images/gallery" directory is writable rather than $filename. If that fails, you need to do either "chmod -R 777 gallery" while in the images folder if you have command line access or give it world write access through whatever FTP client you are using if you are using FTP to talk to your server.
So, what you should have instead for that check is:
if (is_writable("../images/gallery")) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
After doing that, if your script comes back and says "the file is writable", it should have been able to copy the file into your images/gallery folder (remember to not use the name of the file the user gave you). If not, perhaps you don't have permissions to move uploaded files.
As for the location of uploaded files, I think sometimes they are deleted after the script execution ends sometimes, but if not, you can echo the 'tmp_name' of the file and if you go to that directory you should find it sitting there. That would be just a verification test to make sure the file was actually getting to your server. So long as you have write permissions (that what chmod 777 does) on the directory you are moving the uploaded file to, you should be able to copy it there.
You are checking to see if a file that you recently uploaded, but not yet saved is writable, I don't think such a file will ever be writable.
Better remove that if, or just check if the folder you are uploading to is writable.
Other than that, I checked your code and it works.

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.

PHP Uploading Issue

I've worked with a few scripts to begin uploading files on my development machine. Problem is, despite the expected ease of this operation, Apache seems to time-out whenever I try to upload an image. Uploading is set to On and the tmp directory is set in php.ini.
I tried uploading the main gif from Google, an 8.36KB image. It should be fine and well within the limits to PHPs uploading capabilities.
Here is a copy of the script. There should be an easy fix. As requested, I changed the tilde to an actual directory.
<?php
if (!isset($_GET['upload'])) { ?>
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
<? } else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err..."
}
} ?>
Thanks,
Dan
EDIT:
I fixed it, with help from a few of the answers, to one of which I will mark.
A few things here were causing this behavior.
Permissions on the images directory were not set to allow the _www user to access it. A chmod -R 777 images seemed to fix it, as well as a sudo chown _www images.
The form output may have been corrupting the PHP script itself. As suggested, an ECHO <<< ...END helped, I think.
What is it that leads you to believe that Apache is timing out rather than, say, outright failing in some way? Because what leaps out at me is that you're trying to move the file to ~/file.jpg, which I'm nearly certain will not work; ~ is a construct that only normally has meaning inside shells, unless one of PHP's freakish obscure features is processing it in contexts like this. Anyway, try putting the actual directory.
This is more than likely an issue with the size of the file and/or a permission issue between the Apache user and the directory specified. For instance make sure the Apache instance is not running under user (nobody).
Comment to chaos:
He is right the tilde (~) can cause issues, but would probably not cause a timeout; it would display a warning. Even if it does work on your system it would probably deposit the file into an unexpected directory or run into some issues if the Apache user (ie www) does not have a valid home directory set.
If the issue is filesize, add the following lines to your php.ini file and it should work:
upload_max_filesize = 500M ;
post_max_size = 500M ;
PHP by default has a 30 second timeout on the page. So if your upload takes longer than 30 seconds it will fail. Set the timeout either in your php.ini or put the following code at the top of the file.
ini_set(max_execution_time, 90);
The second argument represents the time in seconds before the page will timeout. Set it to whatever time you feel is appropriate. Also, chaos is correct in that '~' is a construct that commonly has meaning only inside shells.
Re: http://ca2.php.net/manual/en/ini.list.php
EDIT:
The problem is that you reopened the tag in the middle of a conditional. Trying your code I get a syntax error. It's strange that you were able to see any web form. This is the fixed code (that works for me).
<?php
if (!isset($_GET['upload'])) {
ECHO <<<END
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
END;
} else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err...";
}
} ?>

Categories