PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] Is file_put_contents a reliable way to check value of some variables?

 February 05, 2022     file-put-contents, php, woocommerce, wordpress     No comments   

Issue

My website is built with wordpress+woocommerce.

For learning purpose, I am trying to check an order's detail once it is completed using file_put_contents. Here is the code:

add_action( 'woocommerce_order_status_completed', 'change_role_on_first_purchase' );

function change_role_on_first_purchase( $order_id ) {
  $order = new WC_Order( $order_id );
  // $user = new WP_user($order->user_id);
  file_put_contents('order.json',json_encode($order));
  file_put_contents('userid.json',json_encode($order->user_id));
  }
}

While the second file_put_contents does write the correct user ID into userid.json, order.json's content is just {}. Obviously $order is not empty, then why file_put_contents is outputting an empty json object?


Solution

Short Answer

Before you can json_encode($order), you need to get the order's data as a plain unprotected array:

$order = new WC_Order( $order_id );
$order_data = $order->get_data(); // ADD THIS
file_put_contents('order.json',json_encode($order_data));

Long Answer Read: json_encode empty with no error TLDR: Basically, json_encode works best when an object has public properties. WC_Order doesn't have any, so it results in an empty object and that's why they created the get_data() method (to expose the data as a plain "unprotected" associative array) (perfect food for json_encode).



Answered By - Fritz Bester
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing