【问题标题】:$_FILES empty at checkout$_FILES 结帐时为空
【发布时间】:2016-03-29 14:18:07
【问题描述】:

我在 woocommerce 的结帐表单中添加了一堆新字段。它会像这样读取完成的 php 文件;

    <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>

问题在于输入

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

从不返回 $_FILES 数组中的值。事实上,$_FILES 数组总是返回一个空数组。我可以通过$_POST 毫无问题地获取其他值。但不是文件。将插件重新安装到另一台单独的计算机上会产生完全相同的结果。

我目前正在使用此代码来查找值:

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);

谁能帮忙?感觉自己快要崩溃了

我在下面添加的完整代码。您在上面看到的是在保留重要部分的同时缩短了它。

  <?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
*/

?>

我还包含了下面的代码用于调试,它也没有返回任何内容,因此它不是操作所独有的。

?>
    <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

【问题讨论】:

  • 这不是您的完整代码,显然它缺少结束 &lt;/form&gt; 标记,除非它缺少 (?) 检查错误
  • 它肯定在那里,只是不想粘贴所有其他前端的代码,它有很多
  • 这是在使用 Bitnami 的本地服务器上,我应该补充一下。 php.ini中允许文件上传,我测试过的文件都小于限制
  • @Fred -ii- 我使用您添加的链接来获取所有错误并收到此错误:[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/ 这有帮助吗?

标签: php wordpress woocommerce


【解决方案1】:

"@Fred -ii- 我使用你添加的链接来获取所有错误,我收到了这个错误:[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 上线290,referer:http://localhost:100/wordpress/product/a-book/ 这有帮助吗?——Dando 船长”

您的文件的名称属性是 name="checkoutupload",但您在整个代码中使用的是 $_FILES['CheckoutImageUpload']

因此,为了避免将所有 $_FILES['CheckoutImageUpload'] 更改为命名属性,只需将文件名属性更改为 name="CheckoutImageUpload"

还要确保您要上传到的文件夹具有正确的路径,并且具有适当的写入权限。

【讨论】:

  • 嗨 Fred,对不起,我忘了更新问题中的代码,实际上是一样的。我马上更新
  • @CaptainDando 如果name="CheckoutImageUpload " 是您的真实 代码,则其中有一个空格。需要删除name="CheckoutImageUpload"
  • @CaptainDando 你也有一个空间还有$_FILES['CheckoutImageUpload ']所以$_FILES['CheckoutImageUpload']
  • @CaptainDando 另一件事,为什么echo '&lt;input type="file" id="CheckoutImageUpload" name="CheckoutImageUpload[]" /&gt;'; 现在在哪里?这还不清楚,如果您想从原始表单上传多个文件,那么您需要像在此处所做的那样将另一个文件视为一个数组,并带有括号 []。您可能无法预览多个文件,因此请尝试删除括号进行测试。
  • @CaptainDando 还有空间if ($_FILES['CheckoutImageUpload ']['name'])。请发布实际代码。我们这里的 cmets 太多了。
【解决方案2】:
  • 检查var_dump($_FILES); 进行调试
  • 检查$_FILES['yourFieldName']['error'] 是否有文件上传错误。 php 将上传、分配等过程中遇到的任何错误存储在 ['errors']
  • $_FILES 是一个数组,所以fwrite ($testLog , "added files: " . $_FILES); 不会工作 var_dump 应该在大多数情况下工作得最好。 (对于静默调试,请使用递归 foreach 循环)
  • 如果您在$_FILES['yourFieldName']['error'] 中遇到错误,大多数情况下文件过大(php.ini)或文件夹不可写

尝试以下方法:

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);
}

还可以尝试用于开发目的的小文本文件。如果大文件失败增加这些 php.ini 值:

  • max_input_time
  • max_execution_time
  • upload_max_filesize
  • post_max_size
  • session.gc_maxlifetime

【讨论】:

  • 嗨 Hafenkranich,我在 woocommerce 中遇到了一个奇怪的问题,如果我在 woocommerce_checkout_update_order_meta 期间尝试回显某些内容,它会被错误系统阻止,我只能收到第一个字母。尽管如此,我尝试了您的代码,但收到了第一个错误; Invalid file 上传 75kb .jpg 文件后。我知道是那个错误,因为我更改了该错误的第一个字母的大小写,它返回了您在此链接中的图片中看到的内容:i.imgur.com/1rcCgwu.png
  • 我没有回显错误,而是将其发送到文本文件,它确实以“无效文件”的形式返回
  • 我不确定是不是因为php文件被告知要死();但我刚刚收到这个错误:Unable to fix malformed JSON from checkout.min.js?ver=2.5.5:1 on my chrome console
  • 另外,在该文件中返回 vardump 也不会返回任何内容
  • 您是否尝试过上传一个小的 .txt 文件。只是为了缩小范围。
【解决方案3】:

我会简化并首先测试一个简单的文件上传

这是一个示例。将其保存为test_upload.php 并通过您的网络服务器直接访问它以测试文件上传。

<?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>

如果这不起作用,您需要检查您的 php.ini 并确保配置的临时目录可被 Web 服务器写入。

您可以通过运行以下命令找到系统的临时目录:

php -B 'echo sys_get_temp_dir(); echo "\n"; exit();'

【讨论】:

  • 嗨@friendly_programmer,运行您的代码会产生以下结果:Array ( [file] =&gt; Array ( [name] =&gt; 790306V2Q3.jpg [type] =&gt; image/jpeg [tmp_name] =&gt; Z:\Work\J00028 - Brave books plugin\bitnami\php\tmp\php2181.tmp [error] =&gt; 0 [size] =&gt; 58173 ) )
  • 表示上传成功。并且该文件临时存储为“tmp_name”。
  • 后续,继续简化。您应该用上面的表格替换您的表格。然后你可以在你的php代码中print_r或者error_log(print_r($_FILES,1))看看$_FILES对象里面有没有东西。
  • 感谢@friendly_programmer,我已通过以下方式将该表单添加到我的函数中:if($_SERVER['REQUEST_METHOD'] == 'POST') { fwrite ($testLog , 'Post compatible'); fwrite ($testLog , print_r($_FILES)); fwrite ($testLog , sys_get_temp_dir()); }。使用 fwrite 我将所有这些信息放入一个 txt 文件中。该文本文件记录所使用的表单使用 post 作为其方法,print_r($_FILES) 返回“1”,仅此而已。我也能找到我的临时目录,但不幸的是搜索上传的文件什么也找不到
  • 需要fwrite ($testLog, print_r($_FILES, 1));
【解决方案4】:

由于这是一个ajax方法,您需要添加一个ajax方法来上传文件,因为设置略有不同。我认为这样的表现会很差,但看看你的想法!

您需要检查脚本中的一些内容 1. 我想我已经为表单 (classname="checkout") 使用了正确的标识符检查您输出的 html 以确保这是正确的
2. 这仅适用于页面上的 1 个文件上传,如果您需要缩小范围,请修改 jQuery(document)
3. Ajaxurl -- 阅读代码中的注释,我建议你在尝试脚本之前先检查一下

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);
        }
    });


});

在你的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');

【讨论】:

  • 这看起来很有希望,我会尝试一下并回复你
  • 你找到解决办法了吗?
【解决方案5】:

您是否完全转储了 $_FILES? 也许您有另一个具有相同表单名称的字段。 如果您发布了完整的表格,那会更容易(如前所述)。 另一个原因可能是,您的 php 堆栈没有上传文件夹的写入权限,然后什么也不返回。 检查您的服务器日志。 它可能会告诉你发生了什么。

我刚刚想到的其他事情。 使用 Crome 并检查哪些请求已被触发。 但是请确保您在网络部分中选中了复选框以保持会话。 您的浏览器可能会在您不认识的情况下重新加载页面。 :)

【讨论】:

  • hmm,我查了文档,还有另外一个表格,但是信息不一样。它读作'code'
  • 如何通过 chrome 查看请求?
  • 我在 chrome 中的“表单数据”下得到的响应如下: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没有提及 $_FILES
猜你喜欢
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2014-08-23
  • 1970-01-01
相关资源
最近更新 更多