Im working on a simple script to include a "Add to calendar" button.
Im using the idea and ICS.php file from https://gist.github.com/jakebellacera/635416 that is a old post.
Im getting the file to download through a function using add_action( 'template_redirect', 'cl_download_ics' ); [The theme is Avada]. But what is happening now is that the download invite is including the themes template file to the file that I don't want and even after removing the template code that was added extra the file still does not want to add the event to the iCalendar.
Here is the code I have so var.
include_once (plugin_dir_path(__DIR__).'cl-add-to-calendar/ics.php');
function cl_download_ics(){
if (isset( $_GET['ics'])) {
$query_data_get = $_POST;
//$query_data = $query_data_get['calendar_data'];
$dtstart = date_create($query_data_get['date_start']);
$dtstart = date_format($dtstart,"Y/m/d H:i:s");
$dtend = date_create($query_data_get['date_end']);
$dtend = date_format($dtend,"Y/m/d H:i:s");
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=Invite.ics');
$ics = new ICS(array(
'location' => $query_data_get['location'],
'description' => $query_data_get['description'],
'dtstart' => $dtstart,
'dtend' => $dtend,
'summary' => $query_data_get['summary'],
'url' => $query_data_get['url']
));
echo $ics->to_string();
}
}
add_action( 'template_redirect', 'cl_download_ics' );
function calendar_btn_ad($atts){
// Shortcode atts with examples
// dtsrart --- 2017-1-16 9:00AM
// dtend --- 2017-1-16 9:00AM
// location --- 123 Fake St, New York, NY
// description --- This is my description
// summary --- This is my summary
// url --- http://example.com
$form_input_fields = array();
if (! empty($atts['dtsrart'])) {
$form_input_fields[] = '<input type="hidden" name="date_start" value="'.$atts['dtsrart'].'">';
};
if (! empty($atts['dtend'])) {
$form_input_fields[] = '<input type="hidden" name="date_end" value="'.$atts['dtend'].'">';
};
if (! empty($atts['location'])) {
$form_input_fields[] = '<input type="hidden" name="location" value="'.$atts['location'].'">';
};
if (! empty($atts['description'])) {
$form_input_fields[] = '<input type="hidden" name="description" value="'.$atts['description'].'">';
};
if (! empty($atts['summary'])) {
$form_input_fields[] = '<input type="hidden" name="summary" value="'.$atts['summary'].'">';
};
if (! empty($atts['url'])) {
$form_input_fields[] = '<input type="hidden" name="url" value="'.$atts['url'].'">';
};
$download_link = WP_PLUGIN_URL.'/cl-add-to-calendar/download-ics.php';
ob_start();
?>
<form action="?ics=true" method="post">
<?php foreach ($form_input_fields as $input_field): ?>
<?php echo $input_field; ?>
<?php endforeach; ?>
<input type="submit" id="cl-add-calendar-submit" value="Add to Calendar">
</form>
<div id="cl-btn-ajax-result">
</div>
<?php
$output = ob_get_clean();
return $output;
}
add_shortcode('cl_calendar_btn', 'calendar_btn_ad');
It is a feed, so add the feed using wordpress add_feed and your function. see
https://developer.wordpress.org/reference/functions/add_feed/.
function add_custom_feed() {
add_feed( 'ics', 'cl_download_ics' );
}
add_action( 'init', 'add_custom_feed' );
function cl_download_ics() {
header('Content-Type: text/calendar; charset=utf-8');
etc.....
}
I'm using custom post types for the event and adding the ics feed when I register the post type. Adding the feed needs to be done with an early wordpress action. Don't use theme actions.
Related
EDITED
Problem - A null value is written to the JSON file after the function runs.
Expectation - Capture data entered into HTML form, append it to an existing JSON file.
Some of the Stack resources I've used:
How do I extract data from JSON with PHP?
How to loop through JSON array using PHP
how to write a json file as a datasource in php?
How to Append JSON File in PHP?
How to add to json array in .json file with php
How can I write data in local JSON file using jQuery?
My JSON file looks like this:
{
"records": [
{"Date":"05/04/2016","Miles":168081,"Gallons":11.003,"Cost":28.60,"MPG":24.1,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"07:04"},
{"Date":"04/18/2016","Miles":167815,"Gallons":10.897,"Cost":27.23,"MPG":25.7,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"15:46"}
],
"error" : false,
"status" : 200
}
EDITED - My PHP script looks like this (update implements Chay's code):
<?php
function runMyFunction() {
// #####
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file2.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file2.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
$formattedData = json_encode($formattedData);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = json_encode($data);
}
//Set a parent key
$records['records'] = $formattedData;
//Overwites everything
/* $handle = fopen($filename,'a+');
fwrite($handle,$records);
fclose($handle); */
file_put_contents($filename,$records, FILE_APPEND | LOCK_EX);
print_r($formattedData);
echo 'OK: ' . '<BR>' . $records . '<BR>';
}
// #####
}//end runMyFunction
/*
if (isset($_GET['hello'])) {
runMyFunction();
} */
if(isset($_POST['mpg_date'],$_POST['mpg_date'],$_POST['mpg_miles'],$_POST['mpg_gallons'],$_POST['mpg_cost'],$_POST['mpg_mpg'],$_POST['mpg_street'],$_POST["mpg_city"],$_POST['mpg_state'],$_POST['mpg_zip'],$_POST['mpg_time'])) {
runMyFunction($_POST);
}
?>
An excerpt of the HTML form looks like this:
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_miles" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<a href='_process.php?hello=true'>Run PHP Function</a>
</div>
</form>
I'm sure that your submission doesn't POST something since you're using anchor (without any javascript) to submit. In the other word, notice I change it to <button>.
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_num" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<button type="submit" role="button">Run PHP Function</button>
</div>
</form>
If you also noticed I also changed the second input name above to mpg_num. And this should be your backend looks.
...
...
if(isset($_POST['mpg_date'], $_POST['mpg_num'])) {
runMyFunction($_POST);
}
Updated
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = $data;
}
//Set a parent key
$records['records'] = $formattedData;
$records['error'] = false;
$records['status'] = 200;
$records = json_encode($records);
//Overwites everything
$handle = fopen($filename,'w+');
fwrite($handle,$records);
fclose($handle);
print_r($records);
}
I hope this won't consume your environment RAM alot :)
This:
<a href='_process.php?hello=true'>Run PHP Function</a>
will actually submit your form. When you just link to the script that way rather than submitting the form, none of the $_POST values will be set.
It looks like your form just needs a submit button. You can put '_process.php?hello=true' into the form action if you want the if (isset($_GET['hello'])) { check to work.
In other words:
<form action="_process.php?hello=true" method="POST" role="form">
<!-- All your inputs, etc. ...-->
<input type="submit" value="Run PHP Function">
</form>
In order to append the new data to your existing JSON, you'll need to change the order that things happen in your function. The else part should be like this:
// First get the existing JSON from the file and decode it
$str_data = file_get_contents("mpg-data-file.json"); // Get the JSON string
$data = json_decode($str_data,true);// json_decode expects the JSON data, not a file name
// Then create a new data array from the $_POST data and add it to the 'records' key
$new_data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
$data['records'][] = $new_data;
// Then re-encode the JSON and write it to the file
$formattedData = json_encode($data);//format the data
$handle = fopen($filename,'w+');//open or create the file
fwrite($handle,$formattedData);//write the data into the file
fclose($handle);//close the file
print_r($data);
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 'READ MORE';
}
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>
Create PDF
</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
"#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.
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
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();'
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');
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.
:)
I have a WP plugin that sends a link to an email to download a file in hidden location. User selects a file, then a token containing the file ID etc. is written to a database, and a link is sent. Upon clicking the link (ex. mysite.com/thank-you/?id=asd687asd68as7d6a8sdd7sd768as7d6, the "thank you" page makes a request to a php function to donload the file.
There's also a dummy "download engine" page with a shortcode [download_page] that initiates the download.
Weird thing is that while this setup works just fine at test environment, and has worked for over a year at production site, it suddenly stopped working:
call for DownloadFile() returns 0KB and correct headers at test site, and initiates the download, but
returns full HTML file and, of course, no download.
I cannot spot any changes in configuration (both sites run WP 4.2.7). Only difference seems to be the WooCommerce plugin, and Google Analytics snippet included in production site.And that test site runs PHP 5.3 while productiopn site runs 5.6.
I'd be very grateful if somebody had an insight of what's happening.. Why are headers ignored? (There's no "Headers already sent" error.) Why is full HTML of the dummy "download engine" page displayed?
BTW it's an out-of-the-box theme, but I cannot spot no faults in it. But still, maybe.. Where I'm to look for a culprit lines? What could force a page to show full HTML instead of headers sent by php?
Relevant code is such:
(download manager.php):
<?php
/*
Plugin Name: Hidden Download Manager
Description: Bla bla
*/
include_once('add_meta_boxes.php');
include_once('mfdm_frontend_functions.php');
add_action( 'init', 'program_register' );
add_shortcode( 'download_page', 'downloadFile' );
?>
(thank_you.tpl.php)
<?php
/**
Template Name: Thank You
*/
$HOST = get_option('mfdm_dbhost');
$USER = get_option('mfdm_dbuser');
$PWORD = get_option('mfdm_dbpwd');
$DB = get_option('mfdm_dbname');
$connect_db = mysqli_connect($HOST,$USER,$PWORD,$DB) or die("Some error occurred during connection " . mysqli_error($connect_db));
if(get_magic_quotes_gpc()) {
$id = stripslashes($_GET['id']);
} else {
$id = $_GET['id'];
}
$result = $connect_db->query("SELECT * FROM 3_downloadkey WHERE uniqueid = '$id'");
$row = resultToArray($result);
$redirect = '';
if (!$row) {
// redirect to 'invalid' page
$redirect = get_option('mfdm_link_invalid_page');
wp_redirect($redirect);
exit;
}
get_header();
$plugindir = plugin_dir_url(0).'mouseful_download/';
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'processLink_request', $plugindir . 'mf_downloads.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script('processLink_request', 'ProcessLink', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'postCommentNonce' => wp_create_nonce( 'ProcessLink-post-comment-nonce' ),
'downloadHiddenPage' => get_option('mfdm_download_hidden_page')
)
);
?>
<link rel="stylesheet" type="text/css" media="all" href="<?=$plugindir;?>mf_downloads.css">
<body onLoad="setTimeout('downloadLink()', 1000)"></body>
<div class="contents about">
<div class="row">
<div class="col banner">
<p><?php the_title(); ?></p>
</div>
</div>
<div class="row2"><div class="col">
<?php
while ( have_posts() ) : the_post();
the_content();
endwhile;
?>
</div></div></div>
<?php
get_footer();
?>
(mfdm_frontend_functions.php):
<?php
add_action( 'wp_ajax_nopriv_downloadLink-submit', 'downloadFile' );
add_action( 'wp_ajax_downloadLink-submit', 'downloadFile' );
function downloadFile() {
$HOST = get_option('mfdm_dbhost');
$USER = get_option('mfdm_dbuser');
$PWORD = get_option('mfdm_dbpwd');
$DB = get_option('mfdm_dbname');
$id = $_POST['app'];
$connect_db = mysqli_connect($HOST,$USER,$PWORD,$DB);
$result = $connect_db->query("SELECT * FROM 3_downloadkey WHERE uniqueid = '$id'");
$row = resultToArray($result);
$app_ID = $row[0]['app_ID'];
ob_start();
// get app name
$base_dir = get_option('mfdm_applications_folder');
define('BASE_DIR',$base_dir);
$fname = get_post_meta($app_ID, 'meta_source', true);
$app_download_name = get_post_meta($app_ID, 'meta_program_name', true);
$file_path = '';
$file_path = find_file1(BASE_DIR, $fname, $file_path);
if (!is_file($file_path)) {
die("File does not exist. Make sure you specified correct file name.");
}
$fsize = filesize($file_path);
$fext = strtolower(substr(strrchr($fname,"."),1));
$mime_types = array(
'msi' => 'application/x-ole-storage',
'zip' => 'application/zip',
'exe' => 'application/x-msdownload',
'sh' => 'application/x-sh',
'iso' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'pdf' => 'application/pdf',
);
$mm_type = $mime_types[$fext];
if ($fd = fopen ($file_path, "r")) {
$fsize = filesize($file_path);
$path_parts = pathinfo($file_path);
$ext = strtolower($path_parts["extension"]);
header("Content-type: $mm_type");
header("Content-Disposition: attachment; filename=\"".$app_download_name."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(ob_POST_level() > 0) {
#ob_end_clean();
}
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
}
?>
(mf_downloads.js):
function downloadLink() {
var id = window.location.search.replace("?", "").split("&")[0];
id = id.split("=")[1];
var url = ProcessLink.downloadHiddenPage;
var form = jQuery('<form action="' + url + '" method="post">' + '<input type="text" name="app" value="' + id + '" hidden="hidden"/>' + '</form>');
jQuery('body').append(form);
form.submit();
}
Your 'downloadFile' function in 'mfdm_frontend_functions.php' should end with wp_die() in order to return a proper response.
wp_die(); // this is required to terminate immediately and return a proper response
Upload a user-defined php.ini to your webroot containing the following line:
default_charset = ""
there is a button on my settings that once clicked it will prompt to download a csv file. Here is the code.
<?php
/** Step 2 (from text above). */
add_action( 'admin_menu', 'my_plugin_menu' );
/** Step 1. */
function my_plugin_menu() {
add_options_page( 'Members Log Data',
'Members Log',
'manage_options',
'sj-member-option',
'members_option' );
}
/** Step 3. */
function members_option() {
if ( !current_user_can( 'manage_options' ) )
{
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
$name = "member-log-".date('Y-m-d');
$list[] = array('username','no of favorites');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $name);
$op = fopen('php://output','w');
foreach($list as $row)
{
fputcsv($op,$row);
}
fclose($op);
/*
echo '<div class="wrap">';
echo '<p>Here is where the form would go if I actually had options.</p>';
echo '</div>';
*/
}
I am getting can not modify session header.
I would like to ask how to do this in WP as I am familiar outside of it.
You're trying to send a header command too late, hence the error. Use the hook load-(your_page) for this kind of output.
function my_plugin_menu() {
$page = add_options_page( 'Members Log Data',
'Members Log',
'manage_options',
'sj-member-option',
'members_option' );
add_action( "load-$page", 'do_export' );
}
In the members_option function callback add a <form> with a submit button and in the new do_export function you'll put the export actions. Something like bellow, note that I'm not checking for the nonce, but for security best practices you should do it instead of checking for $_POST['submit'].
function members_option() {
if ( !current_user_can( 'manage_options' ) )
{
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
?>
<form method='post' >
<p class="submit">
<?php wp_nonce_field('my-import'); ?>
<input type='submit' name='submit' value='Restore'/>
</p>
</form>
<?php
}
function do_export() {
if( isset( $_POST['submit'] ) && 'Restore' == $_POST['submit'] )
{
$name = "member-log-".date('Y-m-d');
$list[] = array('username','no of favorites');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $name);
$op = fopen('php://output','w');
foreach($list as $row)
{
fputcsv($op,$row);
}
fclose($op);
}
}
In my tests, the export result was an HTML file with the full contents of the page plus the 'username','no of favorites' that you defined, but this is a matter for another question/research.
I'm in the process of creating a prototype e-commerce website, I'm having problems saving the visitor name to my flat file database "purchases".
<body>
<h1>Confirm Selection</h1>
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
</table>
The confirm file above creates a variable called $visitor which is whatever the user entered as his/her name in the previous form, I then want to take this variable and once the user has confirmed their selection pass it to the "write.php" file to be processed and written to the purchases file.
Part of my "write.php" file is below.
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$now = date(' d/m/y H:i:s ');
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("can't open file\n");
$content = $now . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot Write ($myFile)\n</p>";
exit;
} else {
echo "<p>Transaction Completed!</p>";
fclose($fh);
}
}
}
}
?>
If purchase page submit goes to write.php, a hidden variable might work:
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
<input type="hidden" name="visitor" value="<?=$visitor?>"/> <!-- added line to send visitor -->
</table>
so in your write.php:
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$visitor = $_REQUEST['visitor']; // added line, now you have visitor
$now = date(' d/m/y H:i:s ');
PS: you might need htmlentities function since the user can enter funny characters for visitor:
<input type="hidden" name="visitor" value="<?=htmlentities($visitor)?>">