12

I have added a bunch of new fields to my checkout form in woocommerce. it reads in the finished php file as such;

    <form name="checkout" method="post" class="checkout woocommerce-checkout processing" action="http://localhost:100/wordpress/checkout/" enctype="multipart/form-data" style="position: relative; zoom: 1;">
        <div id="pagePreview">
            <input type="file" name="CheckoutImageUpload">     
            <div class="BBtextInputFrontend">
                <input class="BBTextBoxFront" placeholder="placeholder">
                <input class="BBInitialValue BBData" type="text" name="BBInitialValue[]">
            </div>
            <div class="BBtextInputFrontend">
                <input class="BBTextBoxFront" placeholder="placeholder">
                <input class="BBInitialValue BBData" type="text" name="BBInitialValue[]">
            </div>
        </div>

        <!-- the rest is the default woocommerce billing inputs -->

        <div class="col2-set" id="customer_details">
            <div class="col-1">
                <div class="woocommerce-billing-fields">
                <h3>Billing Details</h3>

the problem is that the input

<input type="file" name="CheckoutImageUpload">

never returns a value in the $_FILES array. in fact, the $_FILES array always returns an empty array. I can get the other values through $_POST with no issue. but not files. putting the plugin on a fresh install on another separate computer yields the exact same results.

I'm currently using this code to find the values:

function add_image($order_id) {
    //if they DID upload a file...

    if ($_FILES['CheckoutImageUpload']['name']) {
        ?>Y<?php
        die();
    }
    else {
        ?>N<?php
        die();
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'add_image', 100, 1);

can anyone help? I feel like I'm losing my mind

The complete code mentioned I've added below. what you see above is a shortening of it while keeping the important parts.

  <?php
/*
    @package            BBPlugin
    @wordpress_plugin
    Plugin Name:            Brave books book preview plugin
    Plugin URI:             null
    Description:            Allows the user to single out words to be replaced for a preview in a book.
    Author:                 Goodship
    Version:                0.0.2
    Author URI:             www.Goodship.co.za
*/
// If this file is called directly, abort execution.
if ( ! defined( 'WPINC' ) ) {
    die;
}
ini_set('error_reporting', E_ALL);
// This will attach the file needed for the class which defines
// meta boxes, their tabs, views and partial content.
require_once plugin_dir_path( __FILE__ ) . 'admin/class-BBPlugin.php';


/**
    The class that represents the meta box that will display 
    the navigation tabs and each of the fields for the meta box.
 */
require_once plugin_dir_path( __FILE__ ) . 'admin/class-BBPlugin-meta-box.php';


/* 
    Execute the plugin.

    Everything for this particular plugin will be done so from within 
    the Author_Commentary/admin subpackage. This means that there is no reason to setup
    any hooks until we're in the context of the Author_Commentary_Admin class.
    @since 0.0.1
*/


/* 
    This will create an instance of the BBPlugin_Admin class
    from the class file mentioned previously as soon as the plugin is activated,
    After accepting the plugin name and version parameters.
*/


add_shortcode("BB", "BraveBooksShortCode");
function BraveBooksShortCode( $atts, $content = null , $checkout) {
    $inputDiv =  '<div class="BBtextInputFrontend">
                    <input class="BBTextBoxFront" type="text" placeholder="'.$content.'" />
                    <input class="BBInitialValue BBData" type="text" name="BBInitialValue[]" />
                </div>';
    return $inputDiv;
}







function Run_BBPlugin() {
    $BBPlugin = new BBPlugin_Admin('BB-Plugin', '0.0.1');
    $BBPlugin->initialize_hooks();
}

Run_BBPlugin();
wp_register_style( 'postStyles', '/'.'wp-content/plugins/BBPluginv2/admin/assets/css/BBClasses.css' );

wp_enqueue_style('postStyles');

wp_enqueue_script( 'jquery' );

function load_my_script(){
    wp_register_script(
        'functions',
        '/wp-content/plugins/BBPluginv2/admin/assets/js/functions.js' ,
        array( 'jquery' )
    );
    wp_enqueue_script( 'functions' );
}
add_action('wp_enqueue_scripts', 'load_my_script');






function woo_redirect_to_checkout() {
    $checkout_url = WC()->cart->get_checkout_url();
    return $checkout_url;
}
add_filter ('woocommerce_add_to_cart_redirect', 'woo_redirect_to_checkout');

function check_if_cart_has_product( $valid, $product_id, $quantity ) {
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    $woocommerce->cart->add_to_cart($product_id,0);
    return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

function change_add_to_cart_loop( $product ) {
    global $product; // this may not be necessary as it should have pulled the object in already
    return '<a href="' . esc_url( $product->get_permalink( $product->id ) ) . '">READ MORE</a>';
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'change_add_to_cart_loop' );


function woo_custom_cart_button_text() {
    return __( 'Buy this book', 'woocommerce' );
}
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );    // 2.1 +

function wc_remove_all_quantity_fields( $return, $product ) {
    return true;
}
add_filter( 'woocommerce_is_sold_individually', 'wc_remove_all_quantity_fields', 10, 2 );

function wc_add_to_cart_message_filter($message, $product_id = null) {
    $message = sprintf( 'Please remember to enter your details before purchase.');
    return $message;
}
add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );








// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order , $order_id){
    global $woocommerce, $post;?>

    <div class="order_data_column">
        <h4><?php _e( 'Words used' ); ?></h4>
        <?php
        $items = $order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item['product_id'];
            echo '<p>' .json_encode(get_post_meta($product_id, 'BBPlugin-Pages', true) ). '</p>';
            echo '<p>' .json_encode(get_post_meta($post->ID, 'your_key', true) ). '</p>';
        }

        $pageJSONData = json_encode(get_post_meta($product_id, 'BBPlugin-Pages', true));
        $wordsJSONData = json_encode(get_post_meta($post->ID, 'your_key', true));
        ?>
        <script type='text/javascript'>
            var pageArray = <?php echo $pageJSONData ?>;
            var wordsArray = <?php echo $wordsJSONData ?>;
        </script>
        <a href="javascript:restructureInput(pageArray, wordsArray)">Create PDF</a>
    </div>

<?php
}

add_action( 'woocommerce_admin_order_data_after_order_details', 'kia_display_order_data_in_admin' );


/*
** Getting an image to upload
*/
function add_image($order_id, $posted) {
    $sanitized_input_data = array();
    $inputsData = $_POST['BBInitialValue'];
    $filesData = $_FILES['CheckoutImageUpload'];
    $testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
    fwrite ($testLog , "added files: " . $_FILES['CheckoutImageUpload']['name']);



    foreach ( $inputsData as $inputsBoxNumber => $inputBoxData ) {
        $inputArray = explode( "|", $inputBoxData );
        if ( ! empty( $inputBoxData ) ) {

            $BBData = array(
                    'shortcode' => $inputArray[0],
                    'word_used' => $inputArray[1]
            );
            fwrite ($testLog , "found files: " . $inputArray[0]);
            $sanitized_input_data[ $inputsBoxNumber ] = $BBData;
        }
    }
    fclose ($testLog);

    update_post_meta( $order_id, 'your_key', $sanitized_input_data);

    //if they DID upload a file...

    if ($_FILES['CheckoutImageUpload']['name']) {
        //if no errors...
        if (!$_FILES['CheckoutImageUpload']['error'] ) {
            $valid_file = true;
            //now is the time to modify the future file name and validate the file
            $new_file_name = strtolower($_FILES['CheckoutImageUpload']['tmp_name'] ); //rename file
            if ($_FILES['CheckoutImageUpload']['size'] > ( 1024000 ) ){ //can't be larger than 1 MB
                $valid_file = false;
                $message    = 'Oops!  Your file\'s size is to large.';
                echo $message;
                die();
            }

            //if the file has passed the test
            if ( $valid_file ) {
                //move it to where we want it to be
                //copy( $_FILES['CheckoutImageUpload']['tmp_name'], plugin_dir_path( __FILE__ ) . 'admin' );
                $message = 'Congratulations!  Your file was accepted.';
                echo $message;


                $BBdirectory = wp_upload_dir();
                $BBdirectory = $BBdirectory['path'] .'/'. $order_id .'/';
                if (!file_exists($BBdirectory)) {
                    mkdir($BBdirectory, 0777, true);
                    if (move_uploaded_file($_FILES['CheckoutImageUpload']['tmp_name'], $BBdirectory . $_FILES["CheckoutImageUpload"]['name'])) {
                        echo "Uploaded";
                        die();
                    } else {
                        echo "File was not uploaded";
                        die();
                    }
                }
            }
        } //if there is an error...
        else {
            //set that to be the returned message
            $message = 'Ooops!  Your upload triggered the following error:  ' . $_FILES['CheckoutImageUpload']['error'];
            echo $message;
        }
    }
    else {
    }
}


add_action( 'woocommerce_checkout_update_order_meta', 'add_image', 99, 2);
//add_action( 'woocommerce_checkout_update_order_meta', 'add_image');
/*
function platoon_add_order_meta( $order_id, $posted ) {
    $sanitized_input_data = array();
    $inputsData = $_POST['BBInitialValue'];
    foreach ( $inputsData as $inputsBoxNumber => $inputBoxData ) {
        $inputArray = explode( "|", $inputBoxData );
        if ( ! empty( $inputBoxData ) ) {

            $BBData = array(
                    'shortcode' => $inputArray[0],
                    'word_used' => $inputArray[1]
            );

            $sanitized_input_data[ $inputsBoxNumber ] = $BBData;
        }
    }

    update_post_meta( $order_id, 'your_key', $sanitized_input_data);
}
add_action( 'woocommerce_checkout_update_order_meta', 'platoon_add_order_meta', 99, 2 );
*/

function add_checkout_notice() {


    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    $item = end($items)['data']->post->ID;

    $pages = get_post_meta( $item, 'BBPlugin-Pages', true );
    echo '<div id="pagePreview">';
    echo    '<input type="file" name="CheckoutImageUpload" />';

    foreach ( $pages as $pageNumber=>$pageData ) {

        if ($pageData["page_type"] == "text_only"){
            $designedData = $pageData["text"];
            $designedData = do_shortcode ( $designedData, false );
            echo $designedData;
        }
        else if ($pageData["page_type"] == "2up"){
            $designedData = $pageData["text"];
            $designedData = do_shortcode ( $designedData, false );
            echo $designedData;
        }
    }
    echo '</div>';
    ?>
    <script>
        function Test(){
            <?php
/*
                $testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
                fwrite ($testLog , "added files: " . $_FILES['CheckoutImageUpload'] . $_POST['BBInitialValue']);
                fclose ($testLog);
*/
            ?>
        }
    </script>

    <a onclick="Test()" class="btn">Call PHP Function</a>
    <?php
}
add_action( 'woocommerce_checkout_before_customer_details', 'add_checkout_notice');

/*
** end of image upload
*/

?>

I've also included the code below for debugging, and it also returns nothing, so it isn't exclusive to the action.

?>
    <script>
        function Test(){
            <?php
                $testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
                fwrite ($testLog , "added files: " . $_FILES);
                fclose ($testLog);
            ?>
        }
    </script>

    <a onclick="Test()" class="btn">Call PHP Function</a>
    <?php
Captain Dando
  • 497
  • 2
  • 11
  • 30
  • http://php.net/manual/en/function.error-reporting.php – Funk Forty Niner Mar 29 '16 at 14:20
  • 1
    that isn't your full code, obviously as it's missing the closing `` tag, unless it IS missing (?) check for errors – Funk Forty Niner Mar 29 '16 at 14:21
  • it definitely is there, just didn't want to paste all of the other code that comes on the front end, there is a lot of it – Captain Dando Mar 29 '16 at 14:22
  • This is on a local server using Bitnami, I should add. file uploads are allowed in php.ini and the files I've tested have been smaller than the limit – Captain Dando Mar 29 '16 at 14:24
  • @Fred -ii- I used that link you added to get all the errors and I received this error: `[Thu Mar 31 12:23:09.121930 2016] [:error] [pid 11208:tid 1248] [client 127.0.0.1:51335] PHP Notice: Undefined index: CheckoutImageUpload in Z:\\Work\\J00028 - Brave books plugin\\Wordpress stack\\apps\\wordpress\\htdocs\\wp-content\\plugins\\BBPluginv2\\BBPlugin.php on line 290, referer: http://localhost:100/wordpress/product/a-book/` Does this help? – Captain Dando Mar 31 '16 at 10:25
  • you are aware that woo-commerce is using ajax for checkout? I dont see anything that will allow files to be uploaded in the js, but are you sure you want to upload images by ajax = very slow.... – David Apr 03 '16 at 23:47
  • what would be the alternative? – Captain Dando Apr 04 '16 at 12:26
  • try turning off js in your browser and see if the form will progress, your code will prob work then ! – David Apr 04 '16 at 18:46
  • chaeck with `var_dump($_FILES);` either it's working or not – Ahmad Asjad Apr 06 '16 at 16:55
  • FYI, `die()` will write to the output buffer. So having `?>Y – mferly Apr 06 '16 at 16:56
  • @ahmad asjad That returns no values – Captain Dando Apr 07 '16 at 10:31
  • @marcus thank you, I will use that going forward – Captain Dando Apr 07 '16 at 10:31
  • @David it seems that woocommerce uses js in it's checkout process so I can't complete the form without it – Captain Dando Apr 07 '16 at 10:31
  • you will have to remove the onclick event from the submit button to insert your own custom function (formdata is used to send files by ajax) but I did something similar before, to be honest it wasn't worth it, the complete time was horrible. Another option would be to base64 encode the image and store it in a post field, but if the image is large you will have issues with this as well but check my answer here for how to base64 encode http://stackoverflow.com/questions/23323840/ajax-send-save-base64-encoded-image-to-server – David Apr 07 '16 at 11:06
  • Are you sure you enter the desired method after submitting the form? Put an echo as first line and use `die` to see if you get the expected result. If you get the expected result add `print_r($_FILES)`. When no result is returned there must be something wrong with your server configuration. Check in `php.ini` the following options: `file_uploads = On; post_max_size = 100M; upload_max_filesize = 100M`. And of course, check your Apache error log. – GuyT Apr 07 '16 at 11:30
  • Read following post: http://www.trovster.com/blog/2011/07/wordpress-custom-file-upload . Based on that article I suppose you have to add following code `add_action( 'post_edit_form_tag' , 'post_edit_form_tag' ); function post_edit_form_tag( ) { echo ' enctype="multipart/form-data"'; }` – GuyT Apr 07 '16 at 11:35
  • @GuyT its not mentioned in the Q but this is an ajax upload process. Captain Dando i typed out the gist of what you need to do below, I typed it out freehand so there may be a few typos, i dont have time to test. THere may be also js to remove evts so use chrome inspector to ensure the new evt is attached, etc. – David Apr 07 '16 at 16:27
  • @GuyT thank you for adding that, unfortunately it seems that the form already contains `enctype="multipart/form-data"` – Captain Dando Apr 07 '16 at 18:13

5 Answers5

5

"@Fred -ii- I used that link you added to get all the errors and I received this error: [Thu Mar 31 12:23:09.121930 2016] [:error] [pid 11208:tid 1248] [client 127.0.0.1:51335] PHP Notice: Undefined index: CheckoutImageUpload in Z:\Work\J00028 - Brave books plugin\Wordpress stack\apps\wordpress\htdocs\wp-content\plugins\BBPluginv2\BBPlugin.php on line 290, referer: http://localhost:100/wordpress/product/a-book/ Does this help? – Captain Dando"

Your file's name attribute is name="checkoutupload" but you're using $_FILES['CheckoutImageUpload'] throughout your code.

So, to keep you from changing all of the $_FILES['CheckoutImageUpload'] to the named attribute, simply change the file name attribute to name="CheckoutImageUpload".

Also make sure that the folder you are uploading to has the correct path and that it has the proper permissions to write to it.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Hi Fred, sorry I forgot to update the code in my question, it actually is the same. I will update it now – Captain Dando Mar 31 '16 at 12:11
  • @CaptainDando if `name="CheckoutImageUpload "` is your *real* code, there's a space in there. It needs to be removed `name="CheckoutImageUpload"`. – Funk Forty Niner Mar 31 '16 at 12:14
  • @CaptainDando You also have a space in there also `$_FILES['CheckoutImageUpload ']` so `$_FILES['CheckoutImageUpload']` – Funk Forty Niner Mar 31 '16 at 12:15
  • @CaptainDando another thing why is this `echo '';` where it's at now? That's unclear and if you're wanting to upload multiple files from your original form, then you need to treat that other one as an array as you did here, with the brackets `[]`. You probably can't preview multiple files, so try removing the brackets to test. – Funk Forty Niner Mar 31 '16 at 12:17
  • In the future I'd like to upload multiple files, at this stage I kept the [] so that I could iterate through the uploads, but I get the same results with or without it. I've removed the space, it was an error while editing this post, sorry again – Captain Dando Mar 31 '16 at 12:19
  • 1
    @CaptainDando there's still a space `if ($_FILES['CheckoutImageUpload ']['name'])`. Please post actual code. We're getting too many comments here. – Funk Forty Niner Mar 31 '16 at 12:20
  • @CaptainDando then the brackets around the integers `if ( $_FILES['CheckoutImageUpload']['size'] > ( 1024000 ) ){` that should be removed, it's being treated as a function `if ( $_FILES['CheckoutImageUpload']['size'] > 1024000 ){` – Funk Forty Niner Mar 31 '16 at 12:22
  • I've removed them, though the code doesn't get that far. It doesn't get past `if ($_FILES['CheckoutImageUpload']['name'])`, because it can't find that value – Captain Dando Mar 31 '16 at 12:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107857/discussion-between-fred-ii-and-captain-dando). – Funk Forty Niner Mar 31 '16 at 12:27
  • The input field in html has the same extra space at the end. (always check ```if(array_key_exists('myFieldName',$_FILES))){/* check values */}```) – Hafenkranich Apr 04 '16 at 00:17
  • Hi @Hafenkranich, that was corrected earlier, I've also tried different names for the input to no effect – Captain Dando Apr 04 '16 at 15:04
  • @CaptainDando Just a comment in general: I don't want to offend you, but you are making mistakes all over again (typos). At some point people will get frustrated/annoyed and are not willing to help you any more so please be more careful with your future edits. Anyway, did you solve your issues yet? – GuyT Apr 07 '16 at 07:24
  • Hi GuyT, sorry about that. I've been busy the last two days but I have lengthy comments for the users that contributed. I will be adding them in the next few hours – Captain Dando Apr 07 '16 at 10:24
4
  • do check var_dump($_FILES); for debugging
  • check $_FILES['yourFieldName']['error'] for file upload errors. php stores any errors encountered during upload, allocation, etc in ['errors']
  • $_FILES is an array so fwrite ($testLog , "added files: " . $_FILES); wont work var_dump should work best most of the time. (for silent debugging use a recursive foreach loop)
  • should you encounter errors in $_FILES['yourFieldName']['error'], most of the time the filesize is to big (php.ini) or the folder is not writeable

try the following:

function add_image($order_id) {
  //var_dump($_FILES);
  $errors = array();
  if (
    !isset($_FILES['CheckoutImageUpload']['error']) ||
    is_array($_FILES['CheckoutImageUpload']['error'])
  ) {
    $errors[] = 'Invalid file.';
  }

  switch ($_FILES['CheckoutImageUpload']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        $errors[] = 'you sent no file';
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        $errors[] = 'file too big'
    default:
        $errors[] = 'unknown error';
  }

  // check filesize manually
  if ($_FILES['CheckoutImageUpload']['size'] > 50000) { // whatever your php.ini says
    $errors[] = 'file too big';
  }

  return json_encode($errors);
}

Also try small text files for dev purposes. If big files fail increase these php.ini values:

  • max_input_time
  • max_execution_time
  • upload_max_filesize
  • post_max_size
  • session.gc_maxlifetime
Hafenkranich
  • 1,696
  • 18
  • 32
  • Hi Hafenkranich, I have this odd problem with woocommerce where if I try to echo something during `woocommerce_checkout_update_order_meta`, it gets blocked by the error system and I only get the first letter. nontheless, I tried your code and I received the first error; `Invalid file` after uploading a 75kb .jpg file. I know it's that error because I changed the case of the first letter of that error and it came back as what you see in the image in this link: http://i.imgur.com/1rcCgwu.png – Captain Dando Apr 04 '16 at 12:38
  • 1
    instead of echoing the error I instead sent it to a text file and it indeed comes back as 'invalid file' – Captain Dando Apr 04 '16 at 12:44
  • I'm not sure if it's because the php file is told to die(); but I just got this error: `Unable to fix malformed JSON` from `checkout.min.js?ver=2.5.5:1` on my chrome console – Captain Dando Apr 04 '16 at 12:49
  • Also, returning vardump in that file also returns nothing – Captain Dando Apr 04 '16 at 13:13
  • Have you tried uploading a small .txt file. Just to narrow it down. – Hafenkranich Apr 05 '16 at 10:48
  • I changed my solution to return a json including the error strings as it sounds like the file upload is done via a js function -> ajax. That way you can open chrome developer console go to network an watch for the Request for file checkout.min.js. See "preview" to inspect the full error strings. – Hafenkranich Apr 05 '16 at 10:53
  • as you get "invalid file" you know there is some sort of error with the file upload. See the above mentioned output to detect what is wrong in detail. Alternatively uncomment the first if-statement and see what you get next. The switch statement checks more in detail where the problem might be. – Hafenkranich Apr 05 '16 at 10:56
  • Hi @Hafenkranich, sorry for the delay, I haven't been able to comment the last few days, but you seem to be on a good tangent. I'm going to extend the bounty if it runs out. I tried out the txt file though I unfortunately got the same result. I am going to try out the other stuff now – Captain Dando Apr 07 '16 at 10:41
  • Here is another interesting thing, if I try to return that var_dump to the text file as I mentioned earlier, while retaining the console between pages I get this error in the console: `Fixed malformed JSON. Original: array(0) { } {"result":"success","redirect":"http:\/\/localhost\/wordpress\/checkout\/order-received\/18?key=wc_order_5706436166d5f"}` Does this help at all? – Captain Dando Apr 07 '16 at 11:26
  • You can't var_dump to a textfile (at least not directly). var_dump is like echo and prints out everything to the outputstream. this is great for testing. now you know it prints "array(0) { }". 1st Step now is to figure out if thats what you want (dont think so), 2nd fix that problem until you see an output of var_dump you expected. 3rd step is to remove the var_dump statement so your response is a valid JSON again. – Hafenkranich Apr 09 '16 at 18:05
  • Ah ok... later on this should work but for the moment instead of `return json_encode($errors);` try `var_dump($errors); die();`. Now you should see the exact error with your file upload – Hafenkranich Apr 09 '16 at 18:09
  • Hi Hafenkranich, I'm back after sorting out another brief. it seems that wordpress catches whatever I return or var_dump at the 'woocommerce_checkout_update_order_meta' action and puts the first letter of it into an error at the top of the order. in this case, I received the error "SyntaxError: Unexpected token a in JSON at position 0". fwrite was what I was using to circumvent that.. I think of the answers here yours is the most close. if you're ok with it, could I send you my plugins complete code? I'm sure the problem is something small I've overlooked – Captain Dando Apr 19 '16 at 13:05
3

I'd simplify and just test a simple file upload first

Here is a sample. Save it as test_upload.php and access it directly through your web server to test file uploads.

<?php
// test_upload.php
// Tests php file upload capabilities

if($_SERVER['REQUEST_METHOD'] == 'POST') {
        echo "<pre>";
        print_r($_FILES);
        exit();
}

?>

<form enctype="multipart/form-data" method='post' action=''>
        <input type='file' name='file' />
        <input type='submit' value='submit form' />
</form>

If this doesn't work, you need to check your php.ini and also make sure that the configured temporary directory is writable by the web server.

You can find your system's temporary directory by running the following:

php -B 'echo sys_get_temp_dir(); echo "\n"; exit();'
  • Hi @friendly_programmer, running your code yields this result: `Array ( [file] => Array ( [name] => 790306V2Q3.jpg [type] => image/jpeg [tmp_name] => Z:\Work\J00028 - Brave books plugin\bitnami\php\tmp\php2181.tmp [error] => 0 [size] => 58173 ) )` – Captain Dando Apr 07 '16 at 11:19
  • This means it successfully uploaded. and the file is temporarily stored 'tmp_name'. – friendly_programmer Apr 07 '16 at 21:50
  • Following up,continue to simplify. You should replace your form with the form above. Then you can `print_r` or `error_log(print_r($_FILES,1))` in your php code and see if the `$_FILES` object has anything in it. – friendly_programmer Apr 07 '16 at 21:58
  • Thanks @friendly_programmer, I've added that form to my function in the following way: `if($_SERVER['REQUEST_METHOD'] == 'POST') { fwrite ($testLog , 'Post compatible'); fwrite ($testLog , print_r($_FILES)); fwrite ($testLog , sys_get_temp_dir()); }`. Using fwrite I put all this information into a txt file. that text file records that the form used uses post as it's method, `print_r($_FILES)` returns '1', nothing else. I was also able to find my temporary directory, though searching for the file uploaded unfortunately brings up nothing – Captain Dando Apr 08 '16 at 10:32
  • Needs to be `fwrite ($testLog, print_r($_FILES, 1));` – friendly_programmer Apr 08 '16 at 16:24
  • hi @friendly_programmer, I'm sorry for my delay. I used `fwrite ($testLog , "files [1] is " . print_r($_FILES, 1));` and I received `files [1] is Array`, is this correct? – Captain Dando Apr 19 '16 at 13:11
  • Using the php cli: `php > $array = array('something' => 'something');` `php > echo print_r($array, 1); Array ( [something] => something )` If it is empty it looks like this: `php > $array = array();` `php > echo print_r($array,1); Array ( )` – friendly_programmer Apr 21 '16 at 16:13
  • I'm not too sure how to use the console – Captain Dando May 04 '16 at 10:10
1

As this is a ajax method, you need to add a ajax method to upload the files as the settings are slightly different. I think the performance of this will be poor but see what you think!

You need to check a few things in the script 1. I think i have used the correct identifer for the form (classname="checkout") examine your outputted html to ensure this is correct
2. This will only work with 1 file upload on the page, modify jQuery(document) if you need to narrow this down
3. Ajaxurl -- read the notes in the code, i'd recommend you check this first before trying the script

jQuery(form.checkout).on('submit', function(){

    var fd = new FormData();


    //searches the whole document, i am assuming you only need 1 file uploaded
    var file = jQuery(document).find('input[type="file"]');


    var individual_file = file[0].files[0];
    fd.append("imagefile", individual_file);
    fd.append('action', 'upload_image');



    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,  // nb-----------------have you got a variable for ajaxurl? if not insert var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; somewhere in your template...or google the wp way!
        data: fd,
        contentType: false,
        processData: false,
        success: function(response){
            //just spit out the response to the console to catch php errors etc..
            console.log(response);
        }
    });


});

In your functions.php...

function upload_image(){

    echo 'action had been called';

    var_dump($_FILES);
    // work with files!

}


add_action('wp_ajax_upload_image', 'upload_image');
add_action('wp_ajax_nopriv_upload_image', 'upload_image');
David
  • 5,897
  • 3
  • 24
  • 43
0

Did you dump the $_FILES completly? Maybe you have an other field with the same form name. If you would have posted the complet form it would be easier (as already mentioned). Another reason might be, that your php stack doesn't have write permission to the upload folder and then returns nothing. Check your server logs. It might tell you what happened.

Something else I just thought off. Use Crome and check what requests have been fired. But make shure that you hightlited the checkbox in the network section to persist the session. Your Browser might reload the page without you recognizing it. :)

Chris West
  • 741
  • 13
  • 36
  • hmm, I've searched the document, there is another form, but it's information is different. it reads as 'code' – Captain Dando Mar 29 '16 at 14:40
  • how may I see requests through chrome? – Captain Dando Mar 29 '16 at 14:40
  • the response I got under 'form data' in chrome reads as follows: `BBInitialValue[]:Input|asdasd BBInitialValue[]:Derpdydoo|aafsass billing_first_name:Dicks billing_last_name:Mcgee billing_company:woopwoop billing_email:captaindando@gmail.com billing_phone:+27833871309 billing_country:ZA billing_address_1:Lonehill, La Gratitude Circle No 28 Sandton billing_address_2: billing_city:Sandton billing_state:GP billing_postcode:2062 _wp_http_referer:/wordpress/checkout/?wc-ajax=update_order_review` No mention of $_FILES – Captain Dando Mar 29 '16 at 15:19