Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Dec 2006
    Location
    Philippines
    Posts
    23
    Thanks
    1
    Thanked 0 Times in 0 Posts

    upload file using plain javascript but undefine variable in PHP

    hi,the codes below were just a short version of the actual script..anyway i am uploading a file, as much as possible, using plain javascript

    but encounterred a hitch when values won't reach to PHP file . Here are my codes..

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
       <title>Uploading File</title>
       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      
       <script type="text/javascript">
       <!--
       
             function start()  {
    	      		  		 
              myForm=document.createElement("form"); 
              myForm.action="uploader.php"; 
              myForm.method="post"; 
              myForm.enctype="multipart/form-data"; 
              document.body.appendChild(myForm); 
                                                                           
              hidden1=document.createElement("input"); 
              hidden1.type="hidden"; 
              hidden1.name= "MAX_FILE_SIZE"; 
              hidden1.value= 2000000; 
              myForm.appendChild(hidden1); 
                                                           
               //for the browse button  
              button1 = document.createElement("input"); 
              button1.type="file"; 
              button1.name="upload"; 
              button1.value=""; 
              button1.style.position="absolute"; 
              button1.style.top = 20;
              button1.style.height = 30;
              myForm.appendChild(button1); 
                                           
              //for submit button 
              button2 = document.createElement("input"); 
              button2.type="submit"; 
              button2.value="Submit"; 
              button2.style.position="absolute"; 
              button2.style.top = 20;
              button2.style.left = 250;
              button2.style.height = 30;
              button2.style.width = 80;
              button2.onclick="form.submit()";
              myForm.appendChild(button2); 
                                           
              hidden2=document.createElement("input"); 
              hidden2.type="hidden"; 
              hidden2.name="submitted"; 
              hidden2.value="TRUE"; 
              myForm.appendChild(hidden2); 	
    					 	  
             } // end of function start().
       
        // -->
        </script>
    </head>
    <body onLoad="start()"> 
    </body>
    </html>
    and the PHP file or handler (uploader.php)

    PHP Code:
    echo '<pre>POST: 'print_r($_POST); echo "</pre>\n"
    echo 
    '<pre>FILES: 'print_r($_FILES); echo "</pre>\n"
    echo 
    "<hr />\n";
    die();
    //this is just a trap to check wether superglobal variable $_FILES do contains
    //values...beyond this point are PHP codes that actually do the uploading.. 
    unfortunately, the result was..

    Code:
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [upload] => D:\My Folder\Temp\bytes conversion table.xls
        [submitted] => TRUE
    )
    
    FILES: Array
    (
    )
    i guessed my javacript code just lack something?..

  • #2
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    joboy:

    Several things were missing from your post, namely: "please" and "thank you."

    Several things in the code were incorrect, but one was fatal. You must use .encoding to set the form MIME type, not .enctype.

    Unless you are going to be using several of these forms, you shouldn't need a hidden input for the max size value, since size checking is done server-side.

    When responding, please address me by my name.

    This works for me on IIS:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Upload a File</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    	
    	function init(){
    
    		var nBody = document.getElementsByTagName('body')[0];
    		var nForm = document.createElement('form');
    		nForm.encoding = "multipart/form-data";
    		nForm.method = "post";
    		nForm.action = "uploader.php";
    		var nFieldSet = document.createElement('fieldset');
    		nForm.appendChild(nFieldSet);
    		var nLegendTxt = document.createTextNode('File Upload');
    		var nLegend = document.createElement('legend')
    		nLegend.appendChild(nLegendTxt);
    		nFieldSet.appendChild(nLegend);
    		var nLabel = document.createElement('label');
    		nLabel.appendChild(document.createTextNode('File: '));
    		nFieldSet.appendChild(nLabel);
    		var nUpload = document.createElement('input');
    		nUpload.type = "file";
    		nUpload.name = "userUpload";
    		nUpload.className = "fileUpload";
    		nFieldSet.appendChild(nUpload);
    		var nSubmit = document.createElement('input');
    		nSubmit.type = "submit";
    		nSubmit.value = "Submit";
    		nSubmit.className = "submitBtn";
    		nFieldSet.appendChild(nSubmit);
    		nBody.appendChild(nForm);
    	}
    
    	onload=init;	
    
    </script>
    <style type="text/css">
    
    	 body {background-color:#eae3c6;margin-top:60px}
    	 form {width:300px;margin:auto}
    	 fieldset {width:300px;background-color:#f0fff0;border:1px solid #87ceeb}
    	 legend {font-family:times;font-size:14pt;color:#00008b;background-color:#87ceeb;padding-left:3px;padding-right:3px;margin-bottom:5px}
    	 label {font-family:times;font-size:12pt;color:#00008b;padding-left:15px}
    	.fileUpload {font-family:tahoma;font-size:10pt;margin-left:10px}
    	.submitBtn {font-family:tahoma;font-size:10pt;display:block;margin-left:auto;margin-right:auto;margin-top:5px;margin-bottom:5px}
    	
    </style>
    </head>
    	<body>
    		
    	</body>
    </html>
    uploader.php
    Code:
    <?php 
    	//print_r($_FILES);
    	$tmp_name = $_FILES["userUpload"]["tmp_name"];
           	$name = $_FILES["userUpload"]["name"];
    	move_uploaded_file($tmp_name, "images/$name");
    	echo "<h3>The " . $name . " file has been uploaded</h3>";
    ?>
    Last edited by Ancora; 12-19-2006 at 07:45 PM.

  • #3
    New Coder
    Join Date
    Dec 2006
    Location
    Philippines
    Posts
    23
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Ancora, thank you for the reply...and also for reminding me on the essence of being polite. anyway, your codes are truly convincing but in my case i use Apache 2.x i hope web server has nothing to do with the probs and the result i got is a bit different from what we are expecting. upon clicking the submit button, this is what the pop-up window told me..

    Code:
    Do you want to open or save this file?
    
    Name: uploader.php
    Type: unknown file...
    From: blah blah..
    i think, instead of executing the PHP file it's another way around. regarding the enctype and the hidden inputs.. it is better for me to show you the complete codes of the PHP file as well as the "plain" HTML version so you will have a better idea on what i am trying to do. Please see the addtional codes bellow..

    Code:
    <html>
    <head>
    <title>Uploading File - HTML</title>
    </head>
    <body>
    <form enctype="multipart/form-data" action="uploader.php" method="post">
    	<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
    	<p><b>File:</b> <input type="file" name="upload" /></p>
    	<input type="submit" name="submit" value="Submit" />
    	<input type="hidden" name="submitted" value="TRUE" />
    </form>
    </body>
    i am trying to covert the above code into plain javascript (the reason i got hidden input.) and here my complete PHP file that could handle MS Office document and several image files...

    PHP Code:

    <?php
    echo '<pre>POST: 'print_r($_POST); echo "</pre>\n"
    echo 
    '<pre>FILES: 'print_r($_FILES); echo "</pre>\n"
    echo 
    "<hr />\n";
    die();

    // Check if the form has been submitted.
    if (isset($_POST['submitted'])) {
        
        
    // Check for an uploaded file.
            
    if (isset($_FILES['upload'])) {    
                    
            
    // Validate the type. Should be jpeg, jpg, gir or document files.
            
    $allow_pic = array ('image/gif''image/jpeg''image/jpg''image/pjpeg');
            
    $allow_doc = array ('application/msword''application/vnd.ms-excel''application/vnd.ms-powerpoint''application/pdf');
            if (
    in_array($_FILES['upload']['type'], $allow_doc) || in_array($_FILES['upload']['type'], $allow_pic)) {
                
                
    //extract the file extension, to be use in renaming uploaded file.
                
    $filename $_FILES['upload']['name'];
                
    $file_low strtolower($filename); 
                
    $extns split("[/\\.]"$file_low);
                
    $n count($extns)-1
                
    $extns $extns[$n]; 
            
                require_once(
    'class_dcfa.php');
                
    database::connect_db();
                
    $result publication::save_pub($empty_id=''$author$date$title$filename);     
                
    $upload_id mysql_insert_id();
                
    $new_name $upload_id "." $extns;
                
    publication::update_pub($upload_id,$new_name);
                
                if (
    $result) {
                    
    // Move the file over with new filename.
                    
    if (move_uploaded_file($_FILES['upload']['tmp_name'], "../../documents/$new_name")) {
                    
    //if (move_uploaded_file($_FILES['upload']['tmp_name'], "../../documents/{$_FILES['upload']['name']}")) {
                        
    ?>
                        <script type="text/javascript">
                        alert("The file has been uploaded.")
                        window.close();
                        </script>
                        <?php
                        
    exit;
                        
    //echo '<p>The file has been uploaded!</p>';
                
                    
    } else { // Couldn't move the file over.
                        
    publication::del($upload_id);
                        
    ?>
                        <script type="text/javascript">
                        alert("Sorry, the file could not be uploaded because a system error occured.")
                        window.close();
                        </script>
                        <?php
                        
    exit;
                        

                    } 
    // End of move... IF.
               
    // End of IF ($result....
            
            
    } else { // Invalid type or Size too large.
                
    ?>
                <script type="text/javascript">
                alert("Please upload a MS Word, MS PowerPoint, MS Excel, PDF File, or Image file (gif, jpeg, jpg, pjpeg) smaller than 2MB.")
                //alert("File format is not supported.")
                window.close();
                </script>
                <?php
                
    exit;
                
    //unlink ($_FILES['upload']['tmp_name']); // Delete the file.
            
    }

        } else { 
    // No file uploaded.
            
    ?>
            <script type="text/javascript">
            alert("Please upload a MS Word, MS PowerPoint, MS Excel, PDF File, or Image file (gif, jpeg, jpg, pjpeg) smaller than 2MB.")
            window.close();
            </script>
            <?php
            
    exit;
            
    //echo '<p><font color="red">Please upload a MS Word, MS PowerPoint, MS Excel, PDF File or Image file (gif, jpeg, jpg, pjpeg) smaller than 2MB.</font></p>';
        
    }
                
    // End of the submitted conditional.
    ?>
    the plain HTML and PHP tandem gaves me the result i am expecting, such as
    (take note of the die() command)..

    Code:
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submit] => Submit
        [submitted] => TRUE
    )
    
    FILES: Array
    (
        [upload] => Array
            (
                [name] => bytes conversion table.xls
                [type] => application/vnd.ms-excel
                [tmp_name] => H:\Temp\phpE5.tmp
                [error] => 0
                [size] => 13824
            )
    
    )
    for now, please try only MS documents or PDF file, because for an image file it still lead to an error.
    thanks in advance!

  • #4
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    joboy:

    First, did you test the code I posted? I don't think you did. Test it AS IS. Copy the first part and save it as an .html document. Copy the second part and save it as uploader.php

    Second, it may be because of a language difference, but I have no idea what you mean by "plain" HTML, or "plain" JavaScript. For "plain" JavaScript do you mean that you want to completely create the form using ONLY JavaScript? That's what my code does.

    The code I posted WORKS. It uploads the selected file. No popup opens.

    I keep reading your response, but I have no idea what the problem is. At first I thought that you were unable to upload a file, and that was because you were using .enctype and not .encoding. The file will not be uploaded unless you use .encoding.

    My code will produce a result similar to this:

    Code:
    FILES: Array
    (
        [upload] => Array
            (
                [name] => bytes conversion table.xls
                [type] => application/vnd.ms-excel
                [tmp_name] => H:\Temp\phpE5.tmp
                [error] => 0
                [size] => 13824
            )
    I will test all of your code, the PHP and the "plain" HTML form. I will let you know the results.

    Won't you also do the same? Test my code AS IS.
    )

  • #5
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    joboy:

    I tested this html:
    Code:
    <html>
    <head>
    <title>Uploading File - HTML</title>
    </head>
    <body>
    <form enctype="multipart/form-data" action="uploader.php" method="post">
    	<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
    	<p><b>File:</b> <input type="file" name="upload" /></p>
    	<input type="submit" name="submit" value="Submit" />
    	<input type="hidden" name="submitted" value="TRUE" />
    </form>
    </body>
    with this php:
    Code:
    <?php 
    echo '<pre>POST: '; print_r($_POST); echo "</pre>\n"; 
    echo '<pre>FILES: '; print_r($_FILES); echo "</pre>\n"; 
    echo "<hr />\n";
    ?>
    and obtained these results:
    Code:
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [upload] => Array
            (
                [name] => fog.jpg
                [type] => image/pjpeg
                [tmp_name] => C:\PHP\uploadtemp\php2.tmp
                [error] => 0
                [size] => 764
            )
    
    )
    
    ---------------------------------------
    
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [upload] => Array
            (
                [name] => WSJ.wps
                [type] => application/octet-stream
                [tmp_name] => C:\PHP\uploadtemp\php3.tmp
                [error] => 0
                [size] => 14848
            )
    
    )
    
    -------------------------------------
    
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [upload] => Array
            (
                [name] => Lakewood Exemption.pdf
                [type] => application/pdf
                [tmp_name] => C:\PHP\uploadtemp\php4.tmp
                [error] => 0
                [size] => 96555
            )
    
    )
    Then, I modified the code I originally posted, to include the two hidden fields. This is the modified code:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Upload a File</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    	
    	function init(){
    
    		var nBody = document.getElementsByTagName('body')[0];
    		var nForm = document.createElement('form');
    		nForm.encoding = "multipart/form-data";
    		nForm.method = "post";
    		nForm.action = "uploader.php";
    		var nFieldSet = document.createElement('fieldset');
    		nForm.appendChild(nFieldSet);
    		var nLegendTxt = document.createTextNode('File Upload');
    		var nLegend = document.createElement('legend')
    		nLegend.appendChild(nLegendTxt);
    		nFieldSet.appendChild(nLegend);
    		var nLabel = document.createElement('label');
    		nLabel.appendChild(document.createTextNode('File: '));
    		nFieldSet.appendChild(nLabel);
    		var nUpload = document.createElement('input');
    		nUpload.type = "file";
    		nUpload.name = "upload";
    		nUpload.className = "fileUpload";
    		nFieldSet.appendChild(nUpload);
    		var maxSize = document.createElement('input');
    		maxSize.type = "hidden";
    		maxSize.name="MAX_FILE_SIZE"
    		maxSize.value = "2000000";
    		nFieldSet.appendChild(maxSize);
    		var nSubmitted = document.createElement('input');
    		nSubmitted.type = "hidden";
    		nSubmitted.name = "submitted";
    		nSubmitted.value = "TRUE";
    		nFieldSet.appendChild(nSubmitted);
    		var nSubmit = document.createElement('input');
    		nSubmit.type = "submit";
    		nSubmit.name = "submit";
    		nSubmit.value = "Submit";
    		nSubmit.className = "submitBtn";
    		nFieldSet.appendChild(nSubmit);
    		nBody.appendChild(nForm);
    	}
    
    	onload=init;	
    
    </script>
    <style type="text/css">
    
    	 body {background-color:#eae3c6;margin-top:60px}
    	 form {width:300px;margin:auto}
    	 fieldset {width:300px;background-color:#f0fff0;border:1px solid #87ceeb}
    	 legend {font-family:times;font-size:14pt;color:#00008b;background-color:#87ceeb;padding-left:3px;padding-right:3px;margin-bottom:5px}
    	 label {font-family:times;font-size:12pt;color:#00008b;padding-left:15px}
    	.fileUpload {font-family:tahoma;font-size:10pt;margin-left:10px}
    	.submitBtn {font-family:tahoma;font-size:10pt;display:block;margin-left:auto;margin-right:auto;margin-top:5px;margin-bottom:5px}
    	
    </style>
    </head>
    	<body>
    		
    	</body>
    </html>
    I tested the above code with the same php code, uploader.php, above, and obtained the following results:

    Code:
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [userUpload] => Array
            (
                [name] => 56.jpg
                [type] => image/pjpeg
                [tmp_name] => C:\PHP\uploadtemp\phpC.tmp
                [error] => 0
                [size] => 35790
            )
    
    )
    
    ----------------------------------
    
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [userUpload] => Array
            (
                [name] => MJH Summary.wps
                [type] => application/octet-stream
                [tmp_name] => C:\PHP\uploadtemp\phpD.tmp
                [error] => 0
                [size] => 15360
            )
    
    )
    
    --------------------------------------
    
    POST: Array
    (
        [MAX_FILE_SIZE] => 2000000
        [submitted] => TRUE
        [submit] => Submit
    )
    
    FILES: Array
    (
        [userUpload] => Array
            (
                [name] => formulary_open.pdf
                [type] => application/pdf
                [tmp_name] => C:\PHP\uploadtemp\phpE.tmp
                [error] => 0
                [size] => 410192
            )
    
    )
    So, you see, I had no trouble, using my code, uploading any type of file. Beyond this, I have no idea what the problem could be.

    Test the code I posted AS IS. That's WHY I posted it.
    Last edited by Ancora; 12-20-2006 at 02:08 PM.

  • #6
    New Coder
    Join Date
    Dec 2006
    Location
    Philippines
    Posts
    23
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Ancora:

    i believe in all what you have said that everything is working fine while running the codes i posted and as well as your "enhanced" codes, and i would like to point out that i really run your code AS IS i.e. paste the javacript(first part) code on .html document and the second on .php file, i am very sure of that..but i guessed i am experiencing a bit weird on my PC because i made a desperate attempt, just recently, to replace the "trap"..see code below:

    PHP Code:
    <?php 
    echo '<pre>POST: 'print_r($_POST); echo "</pre>\n";  
    echo 
    '<pre>FILES: 'print_r($_FILES); echo "</pre>\n";  
    echo 
    "<hr />\n"
    die(); 
    ?>
    with just a simple statement, like this:

    PHP Code:
    echo "Hello world..";
    die(); 
    and the browser displays only a white blank page. at this point, i think as far as the thread that i posted is concern, it's already solved! and i deeply appreciated your solutions(modified code). thank you and merry x'mas..wish you all the luck this coming new year!

  • #7
    New Coder
    Join Date
    Dec 2006
    Location
    Philippines
    Posts
    23
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Ancora:

    correction to latest reply i made, i mean that it is only your modified code that works..excluding the original script i posted, of course that's the reason i posted it up.

  • #8
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    joboy:

    You're welcome, and Merry Chirstmas.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •