Jump to content

PHP Newbie Upload Link Scripting/Folder Question


graphxsman

Recommended Posts

Hi,

 

I'm trying to incorporate a very simple php upload file link script into my website, but it doesn't seem to be running correctly. I'm using a very simple html form set up to activate the script. I know I have the correct coding and syntax set up because I'm using an already coded script from a php developer. My inquiry has to do with folder and file placement on the root directory. I have php 5.3 installed on the server. Does the php file and the html file that runs the code have to be in a special folder other than the public_html folder or can it be amongst the other site files? I know there needs to be an "upload" folder to place the uploaded files, but do the php and html files need to be in that folder too? When I try to run the script, all I get is a blank web page, but the url shows the php file in the address.
 
FORM:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" size="30" />
<input type="file" name="myfile" size="30" /><br/>
<input type="submit" value="Upload" />
</form>
 
PHP:
<?php
 
$uploaddir = "uploads/";
$allowed_ext = "pdf, doc, dotx";
$max_size = "20000";
 
$extension = pathinfo($_FILES['file']['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for ($i = 0; $i < count ($allowed_paths); $i++); 
{
if ($allowed_paths[$i] == "$extension");
{
$ok = "1";
}
 
if ($ok == "1") {
if($_FILES['myfile']['size'] > $max_size);
}
echo "File is too big.";
exit;
}
 
if (is_upload_file($_FILES['myfile']['tmp_name']))
{
move_upload_file($_FILES['myfile']['tmp_name'],$uploaddir.'/'.$_FILES['file']['name']);
echo "Your file has been uploaded successfully.";
}
 else {
echo "Incorrect file extension.";
 }
 
?>
 
Thanks!
Link to comment
Share on other sites

Does the php file and the html file that runs the code have to be in a special folder other than the public_html folder or can it be amongst the other site files?

No, the public_html file is fine.

 

 

 

all I get is a blank web page, but the url shows the php file in the address.

This is most probably caused by an error. To see what the error could be either look at your servers error log or enable error reporting. Add these two lines after <?php to enable error reporting

display_errors(1);
error_reporting(E_ALL);
What errors are shown? Edited by Ch0cu3r
Link to comment
Share on other sites

Thanks for tips!

 

It seems to be working now, but there appears to be something wrong with the php code. I keep getting the echo "File is too big." I should only get that IF the file is too big, but no matter how small of a file I choose, it gives that echo.  

 

I'd like simple code that restricts file size and extension mostly.

Link to comment
Share on other sites

Your if statement for checking if the file size is wrong

if($_FILES['myfile']['size'] > $max_size);  // semi-colon should not be there
}  // this should be a {
echo "File is too big.";
exit;
}
To check for valid file extensions put all valid file extensions in array, not a string

$allowed_ext = array('pdf', 'doc', 'dotx');
Then use in_array to check if the uploaded files extensions exists in the $allowed_ext array

$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(in_array($extension, $allowed_ext))
{
      // uploaded file has valid file extension
}
Fixed php code

$uploaddir = "uploads/";
$allowed_ext = array('pdf', 'doc', 'dotx');
$max_size = "20000";

$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // get the file extension
// check if extension is in the allowed extensions array
if(in_array($extension, $allowed_ext))
{
    // uploaded file has valid file extension
    // check file size
    if($_FILES['myfile']['size'] > $max_size)
    {
        echo "File is too big.";
    }
    // file size ok
    else
    {
        // move uploaded to storage location
        if (move_upload_file($_FILES['myfile']['tmp_name'],$uploaddir.'/'.$_FILES['file']['name'])
        {
            echo "Your file has been uploaded successfully.";
        }
        else
        {
            echo "Sorry, something went wrong";
        }
    }
}
// file extension not allowed
else
{
    echo "Invalid file type";
}
Edited by Ch0cu3r
Link to comment
Share on other sites

Thanks so much, Ch0cu3r. It's definitely working now, but for some reason I'm now getting the echo, "Invalid file type" even if I upload the correct file type. I thought perhaps not having all the 'file' s correctly labeled might be doing that, but even after changing them to 'myfile' it still gives me the echo.

 

Here's the code with my tweaks. Hopefully I didn't mess anything up. I did have to tweak some of the syntax because it was saying it was incorrect.

 

<?php
$uploaddir = "uploads/";
$allowed_ext = array('pdf', 'doc', 'dotx', 'rtf', 'txt');
$max_size = "5242880";
 
$extension = pathinfo($_FILES['myfile']['name'], PATHINFO_EXTENSION); // get the file extension changed to myfile
// check if extension is in the allowed extensions array
if(in_array($extension, $allowed_ext))
{
    // uploaded file has valid file extension
    // check file size
    if($_FILES['myfile']['size'] > $max_size)
    {
        echo "File is too big.";
    }
    // file size ok
    else
    {
        // move uploaded to storage location
        if (move_upload_file($_FILES['myfile']['tmp_name'],$uploaddir.'/'.$_FILES['myfile']['name'])) // changed to myfile
        {
            echo "Your file has been uploaded successfully.";
        }
        else
        {
            echo "Sorry, something went wrong.";
        }
    }
}
// file extension not allowed
else
{
    echo "Invalid file type.";
}
 
?>
Link to comment
Share on other sites

when validating user supplied information, you need to provide verbose messages why something the user did didn't work and what if anything he can do to fix it.

 

rather than a generic message - "Invalid file type.", you should output what the type value the user supplied is and what the valid type values are.  this will make your code 'self troubleshooting'. during development, your code will tell you why it didn't work.

Link to comment
Share on other sites

Thanks for that piece of code, mac_gyver. I applied it right away. I'm getting this echo now, though. "The file extension you supplied is: , the allowable types are: pdf, doc, dotx, rtf, txt" I get this echo whether I try to upload a pdf (an allowed ext.) or a png (not allowed ext.). It's fun that it's working, though. :-)

Link to comment
Share on other sites

it's likely that the upload is failing and the $_FILES['myfile']['name'] element is empty.

 

your code needs to test if the upload worked at all before you can access any of the uploaded file information. the ['name'], ['type'], ['size'], and ['tmp_name'] elements of the $_FILES['myfile'][...] array are only 100% valid when the ['error'] element is set and is a zero value. if you use the advanced search on the forum, for the word 'upload' and by me as an author, you will find a number of posts showing/stating how to detect that an upload form has been submitted and how to detect if the upload worked before using any of the uploaded file information.

 

i also notice you have two type='file' fields in your form with the same name. that won't work. only the values from the last field with the same name will be submitted. when uploading multiple files, it's easiest to use an array name for the form field so that you can simply iterate/loop over the data. i'm pretty sure the forum search i suggested above will return results showing how to do this as well.

Link to comment
Share on other sites

Well, if I may indulge anybody's expertise once again I'd be much obliged.

 

I really want to have a multiple file upload, but I just can't seem to get anything to "work."

 

So for now I'm trying to wrap my brain around a simple single file upload.

 

I'm not sure why i'm having such a difficult time with this. Maybe it's a matter of not having my files set up right. So here's what I have to test a working arrangement.

 

I have a html document named "careers.html" that I have put the following form in for the upload link:

 

FORM:

<form action="upload9.php" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" />
  <input type="submit" value="Upload" />
</form>
 
Here is the the php upload doc, "upload9.php", that the "action" is being called to:
 
PHP:
<?php
$allowedExts = array("doc", "pdf", "dotx", "rtf", "txt");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "text/doc")
|| ($_FILES["file"]["type"] == "text/pdf")
|| ($_FILES["file"]["type"] == "text/dotx")
|| ($_FILES["file"]["type"] == "text/rtf")
|| ($_FILES["file"]["type"] == "text/txt"))
&& ($_FILES["file"]["size"] < 5242880)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
 
    if (file_exists("uploads/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file.";
  }
 
?>
 
I have the php, the html and the "uploads" folder in the same directory on my web server. When I run the code above, I get the error message "Invalid File." No matter what file type I link to. Incorrect or correct.
 
I looked at the resources you all sent and I tried a few of them, but I just can't seem to get anything to show up in my "uploads" folder on my server or to get any of the scripts to "work." 
 
I just want to get something to work and then, as I said, I'd like to make the html form and php actually function as a multiple file upload, or really, be able to send the file to an email address without going to the server. But first I've got to get something to work for me. 
 
If anybody can assist me, that would be great. Sorry I'm not grasping this too well, although I am slowly seeing how things work. 
:confused:  
Link to comment
Share on other sites

your code is still not testing if the upload worked before trying to use the uploaded file information.

 

when an upload fails, generally due to the size of the file, the ['type'] element will be empty and for some of the possible reasons an upload can fail, the ['name'] element will be empty. your lumped together conditional logic testing the ['type'] and $extension will be false and your generic "Invalid file." message will be displayed.

 

your current code is testing some of the possible uploaded errors in the ['error'] element AFTER you have tried to test the ['type'] and $extension. your code will never reach that point and report an upload error because if there is a detected error in the ['error'] element, the ['type'] or $extension won't be valid and your first logic test will go to the "Invalid file." message. the code you have now is based on the w3schools site and it is ass-backwards. YOU MUST CORRECT THE LOGIC IN YOUR CODE BEFORE IT WILL TELL YOU WHY IT IS FAILING.

 

so two things, as previously mentioned -

 

1) you must test if the upload worked before you use any of the uploaded file information, since the uploaded file information will not exist to test if the upload didn't work.

 

2) you should output unique and verbose messages for each different thing that can cause your code to fail so that your code is self troubleshooting.

 

to debug what exactly might be happening after you submit your form, you can dump the $_FILES array using the following code, put in before the start of your conditional logic  -

echo "<pre>";
echo "FILES:";
print_r($_FILES);
echo "</pre>";
Edited by mac_gyver
Link to comment
Share on other sites

Thanks so much, mac_gyver. I appreciate your assistance. I'm really new at this php stuff. Scripting languages have been a rough thing for me to grasp. Since I'm new at this, I'm finding some of your instructions assume a bit more knowledge of php than I have. So if you find helping me frustrating, don't feel obligated. I'll get through this in time. I always do. 

 

Like Javascript, I am assuming the code runs in a hierarchical manner from what I grasp in your instructions. So I put the code you sent in the following place:

 

<?php
echo "<pre>";
echo "FILES:";
print_r($_FILES);
echo "</pre>";
// $allowedExts = array("doc", "pdf", "dotx", "rtf", "txt");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "text/doc")
|| ($_FILES["file"]["type"] == "text/pdf")
|| ($_FILES["file"]["type"] == "text/dotx")
|| ($_FILES["file"]["type"] == "text/rtf")
|| ($_FILES["file"]["type"] == "text/txt"))
&& ($_FILES["file"]["size"] < 5242880)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
 
    if (file_exists("uploads/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file.";
  }
 
?>
 
But I got this message:
 
FILES:Array
(
[file] => Array
(
[name] => Week-10_8_13.dotx
[type] => application/vnd.openxmlformats-officedocument.wordprocessingml.template
[tmp_name] => /tmp/php5cWfFQ
[error] => 0
=> 88652
)

)
Invalid file.
 
Correcting the logic in my code is the problem I'm having. I'm not knowledgable enough to know what logic isn't correct or even how to code it. I'm trying to find something on the web and then tweak it to fit my needs.
 
Maybe I should go with a jquery or javascript method instead.
Link to comment
Share on other sites

I don't see the type of that uploaded file

[type] => application/vnd.openxmlformats-officedocument.wordprocessingml.template

in your list of acceptable types:

if ((($_FILES["file"]["type"] == "text/doc")
|| ($_FILES["file"]["type"] == "text/pdf")
|| ($_FILES["file"]["type"] == "text/dotx")
|| ($_FILES["file"]["type"] == "text/rtf")
|| ($_FILES["file"]["type"] == "text/txt"))
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.