Uploading file on server apache via php - php

I'm trying to download a file from my website to my server but can't find why or where I'm doing that wrong.
Here my php code :
$fn = $_FILES['file']['name'];
if (is_writable('.')) {
echo "Writable<BR>";
} else {
echo "Not writable<BR>";
}
$upfile = './'.basename($fn);
echo $upfile.'<BR>';
shell_exec("echo 'baaaaah' > test.baaaah");
$f = $_FILES['file']['tmp_name'];
echo $f.'<BR>';
if (is_uploaded_file($f)) { echo "uploaded<BR>"; } else { echo "not uploaded<BR>";}
$com = "test - f ".$f." && echo 'F' || echo 'N'";
echo $com.'<BR>';
echo shell_exec($com).'<BR>';
if (move_uploaded_file($f,$uploadfile)) {
echo "File transfer OK<BR>";
} else {
echo "File transfer NOK<BR>";
}
print_r($_FILES);
And here the website output :
Writable
./flag.jpg
/tmp/phpyKvhEz
uploaded
test - f /tmp/phpyKvhEz && echo 'F' || echo 'N'
N
File transfer NOK
Array ( [file] => Array ( [name] => flag.jpg [type] => image/jpeg [tmp_name] => /tmp/phpyKvhEz [error] => 0 [size] => 1660 ) )
So first thing I check if my folder is writable (it's not intended to be '.' but I moved to here because the folder I want wasn't working either (same behavior as '.' through...)) => check
Then I try to shell_exec a file here juste to be sure => check, file is on server
Then I check if the temp file is created on the server :
- check, anyway is_uploaded thinks the file is here
- not check, but a test on the temp file doesn't work (and since the file is not supposed to be removed before the end of the script it should see the file here imho ?)
Then I try to make the move_uploaded_file => not check
And I print the $_FILES who shows nothing suspicious (error = 0, file names matches what I see before).
I can't figure what goes wrong nor where a mistake can come from ><

$uploadfile is undefined in your code. Change it or set it to '.' and it should work.

Related

File upload works on desktop, but not on mobile using camera

I am trying to create an HTML and PHP script to upload images to a webserver from a user's phone. It is working good in that it will prompt the user to either select an image from their gallery, or to capture an image with their camera. When I capture a picture, it successfully fills in the information
"foo.jpg"
but when I pass the data onto my PHP script, it gives me the error
"Warning getimagesize() filename cannot be empty.... Sorry, there was
an error uploading your file."
What confuses me, is that the filename was not empty in my form. Also, when I submit the form using a desktop computer (it just prompts for a file upload), it works perfectly as it should.
HTML:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" capture="camera" accept="image/*" name="imageFileToUpload">
<label for="rma">RMA: </label>
<input type="text" name="rma">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
PHP:
<?php
$rma = $_POST['rma'];
echo "RMA: " . $rma. "<br>";
$target_dir = "uploads/". $rma;
if (file_exists($target_dir)==false)
{
if(mkdir ($target_dir))
{
echo "folder created at: " .$target_dir . "<br>";
}
else
{
echo "failed to create folder " . $target_dir. "<br>";
}
}
$target_file = $target_dir ."/" .basename($_FILES["imageFileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"]))
{
$check = getimagesize($_FILES["imageFileToUpload"]["tmp_name"]);
if($check !== false)
{
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else
{
echo "File is not an image.<br>";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file))
{
echo "Sorry, file already exists.<br>";
$uploadOk = 0;
}
// if everything is ok, try to upload file
else
{
if (move_uploaded_file($_FILES["imageFileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["imageFileToUpload"]["name"]). " has been uploaded.<br>";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
I would like to thank everyone for their kind and patient help so far and I appreciate any answers and guidance.
UPDATE:
I am using an Ipad with Safari as well as an android device running 6.0.1 Marshmallow and the chrome browser. The dump file did show some information.
Here is the echo from the ipad:
RMA: 2468
C:\wamp64\www\upload.php:5:
array (size=5)
'name' => string 'image.jpg' (length=9)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 1
'size' => int 0
folder created at: uploads/2468
( ! ) Warning: getimagesize(): Filename cannot be empty in C:\wamp64\www\upload.php on line 31
Call Stack
# Time Memory Function Location
1 0.0006 376976 {main}( ) ...\upload.php:0
2 0.0011 377176 createImageFile( ) ...\upload.php:20
3 0.0012 377208 getimagesize ( ) ...\upload.php:31
File is not an image.
Sorry, there was an error uploading your file.
Android 6.0.1 chrome:
RMA: 1996
C:\wamp64\www\upload.php:5:
array (size=5)
'name' => string '20160322_125659.jpg' (length=19)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 1
'size' => int 0
folder created at: uploads/1996
( ! ) Warning: getimagesize(): Filename cannot be empty in C:\wamp64\www\upload.php on line 30
Call Stack
# Time Memory Function Location
1 0.0006 377880 {main}( ) ...\upload.php:0
2 0.0012 378096 createImageFile( ) ...\upload.php:20
3 0.0012 378128 getimagesize ( ) ...\upload.php:30
File is not an image.
Sorry, there was an error uploading your file.
Working echo from computer:
RMA: 1234
C:\wamp64\www\upload.php:5:
array (size=5)
'name' => string '58832_300x300.jpg' (length=17)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string 'C:\wamp64\tmp\phpF5F3.tmp' (length=25)
'error' => int 0
'size' => int 3801
The file 58832_300x300.jpg has been uploaded.
New record created successfully
It seems like it never sends the image type or the filesize, only the name when using mobile devices. Any ideas?
It seems to be a CORS problem.
There is an error when you try to upload from an another location.
See log file of your wamp server for the detailled error information...
For more informations of that mechanism, see : CORS wiki

move_uploaded_file() Isn't uploading files

I a php script which is called from a file form and it is supposed to check the form for password, filename, filetype and errors uploading to temp. If it passes all tests it's supposed to upload using move_uploaded_file but this does not work. No errors are outputted but I know it passes all the tests otherwise it would return back to the page.
PHP script:
<?php
$temp = explode(".", $_FILES["file"]["name"]);
if ($_POST["pass"] == "examplePass"){
if($_FILES["file"]["name"] == ""){
header("Location: /upload?i=f");
}
elseif($_FILES["file"]["type"] != "application/x-shockwave-flash"){
header("Location: /upload?i=s");
}
elseif ($_FILES["file"]["error"] > 0){
header("Location: /upload?i=e");
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"], "/swf/". $_FILES["file"]["name"]);
if(file_exists("/swf/" . $_FILES["file"]["name"])){
header("Location: /upload?i=o");
}
else{
print_r($_FILES);
}
}
}
else{
header("Location: /upload?i=p");
}
?>
This outputs:
Array ( [file] => Array ( [name] => launcher.swf [type] => application/x-shockwave-flash [tmp_name] => /tmp/phpBugtQL [error] => 0 [size] => 161303 ) )
I have tried this with multiple swf files and I can remember it used to work.
I have set the whole of my web folder to 0777 and also recursed this into all sub-directories and files.
The directory /swf/ is at root so that is the absolute path.
Thanks in advance, Kyle
You can try using, ../swf/ or full path of the swf folder instead of /swf/
move_uploaded_file($_FILES["file"]["tmp_name"], "../swf/". $_FILES["file"]["name"]);
Reason for swf folder path, make sure you have used the correct path

Uploading XML file and parsing it - without temporary files

With PHP 5 I would like to upload an XML file via a web form and parse it using SimpleXML.
I've tried few SimpleXML examples and they work fine at my CentOS 6 Linux server.
However, I don't have any experience with handling uploaded files in PHP yet.
Should I use the $_FILES and do I always have to use a temporary file or can it be done completely in memory?
From PHP Cookbook I've copied this example:
<html>
<body>
<?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { ?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>"
enctype="multipart/form-data">
<input type="file" name="doc"/>
<input type="submit" value="Send File"/>
</form>
<?php } else {
if (isset($_FILES['doc']) &&
($_FILES['doc']['error'] == UPLOAD_ERR_OK)) {
$oldPath = $_FILES['doc']['tmp_name'];
$newPath = '/tmp/' . basename($_FILES['doc']['name']);
if (move_uploaded_file($oldPath, $newPath)) {
print "File moved from $oldPath to $newPath";
} else {
print "Couldn't move $oldPath to $newPath";
}
} else {
print "No valid file uploaded.";
}
}
?>
</body>
</html>
It works fine and for the print_r statement added by me the following output is printed:
Array
(
[document] => Array
(
[name] => my_file.xml
[type] => text/xml
[tmp_name] => /tmp/phpRD9cYI
[error] => 0
[size] => 1610252
)
)
And I can see the /tmp/my_file.xml file.
My question is though if I can skip the creation of temporary files?
I don't like them because:
They are sometimes security issue
They have to be cleaned up (by a cronjob?)
Their names might collide (probably seldom case unless it's 1)
UPDATE: Also, I don't understand, why can't I read the file at $oldPath? It is not found there and I have to call the move_uploaded_file() and then read the $newPath...
You don't need to save/move the file in a new folder,
if (isset($_FILES['doc']) && ($_FILES['doc']['error'] == UPLOAD_ERR_OK)) {
$xml = simplexml_load_file($_FILES['doc']['tmp_name']);
}
The tempfile generated will be automatically removed when the PHP script finishes. Hope this helps.

Can't move/fine APC Uploaded file

As a bit of a follow up to Javascript form won't submit (to view the code I am using visit that link) I am now encountering a problem that I cannot find the file that has been uploaded.
I have added $files = apc_fetch('files_'.$_POST['APC_UPLOAD_PROGRESS']); to the top of my page and this is the output of print_r($files);
Array
(
[theFile] => Array
(
[name] => tt1.mp4
[type] => video/mp4
[tmp_name] => /tmp/php2BEvy7
[error] => 0
[size] => 1050290
)
)
However when I try to run the following code:
if (file_exists($files['theFile']['tmp_name'])) {
$webinarType = strcmp($files['theFile']['type'], 'video/mp4');
if($webinarType == 0) {
$webinarFile = $fileTitle;
$webinarTempName = $files['theFile']['tmp_name'];
} else {
echo 'Webinar must be .mp4';
}
} else {
echo "No File";
}
I get the No File output.
I have ssh'd into the server and the file is not in /tmp/, /path/to/public_html/tmp/ or path/to/file/tmp/ all of which exist.
I have tried to use move_uploaded_file() but as this is executed on all file inputs I can't get the tmp_name dynamically due to my limited knowledge of javascript.
tl;dr version; Where is my file gone and how can I find it?
NOTE; This form did work before the APC intevention and I am running wordpress in case that affects anything.
Fixed this one on my own as well.
In the progress.php file (found on the other question) I modified the elseif statement with this:
elseif(($s_progressId = $_POST['APC_UPLOAD_PROGRESS']) || ($s_progressId = $_GET['APC_UPLOAD_PROGRESS']))
{
// If the file has finished uploading add content to APC cache
$realpath = realpath($PHP_SELF);
$uploaddir = $realpath . '/tmp/';
foreach ($_FILES as $file) {
if(!empty($file['name'])) {
$uploaded_file = $file['name'];
$moveme = $uploaddir.$uploaded_file;
move_uploaded_file($file['tmp_name'], $moveme);
}
}
apc_store('files_'.$s_progressId, $_FILES);
die();
}
That way I could iterate through the $_FILES array without knowing the name of the input. I noticed that it loops through a couple of times hence the if(!empty()) however in hindsight it's probably best practice anyway.

PHP Wont Extract zip file on windows ER_OPEN

I'm building a module installer for my CMS and i have ran into a problem now im using Windows 7 x64 with XAMPP x32 installed,
For some reason PHP returns the ER_OPEN error code (11) when ever i run my code and i know the directoy is writeable as the file gets move to the parent by php when it's uploaded here is my script
if($_URL['form'] == 'sent'){
$target_path = getcwd()."\\..\\Temp-uplds\\";
$target_path = $target_path. time() . basename( $_FILES['installFile']['name']);
if(move_uploaded_file($_FILES['installFile']['tmp_name'], $target_path)) {
$zip = new ZipArchive;
$status = $zip->open('$target_path');
if ($status === TRUE) {
$zip->extractTo(getcwd()."\\..\\Temp-uplds\\zip\\");
$zip->close();
} else {
print_r(array($status, $zip));
}
} else{
$this->tmp_vars->error = true;
}
}
echo "<pre>error codes ZIPARCHIVE::ER_EXISTS = '".ZIPARCHIVE::ER_EXISTS."'
File already exists.
ZIPARCHIVE::ER_INCONS = '".ZIPARCHIVE::ER_INCONS."'
Zip archive inconsistent.
ZIPARCHIVE::ER_INVAL = '".ZIPARCHIVE::ER_INVAL."'
Invalid argument.
ZIPARCHIVE::ER_MEMORY = '".ZIPARCHIVE::ER_MEMORY."'
Malloc failure.
ZIPARCHIVE::ER_NOENT = '".ZIPARCHIVE::ER_NOENT."'
No such file.
ZIPARCHIVE::ER_NOZIP = '".ZIPARCHIVE::ER_NOZIP."'
Not a zip archive.
ZIPARCHIVE::ER_OPEN = '".ZIPARCHIVE::ER_OPEN."'
Can't open file.
ZIPARCHIVE::ER_READ = '".ZIPARCHIVE::ER_READ."'
Read error.
ZIPARCHIVE::ER_SEEK = '".ZIPARCHIVE::ER_SEEK."' </pre>";
And my Given output is
Array ( [0] => 11 [1] => ZipArchive Object ( [status] => 0 [statusSys] => 0 [numFiles] => 0 [filename] => [comment] => ) )
Any help would be helpfull
You have single quotes around '$target_path'. Variable interpolation only works with double quotes.
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Categories