Last active
January 31, 2024 01:39
-
-
Save jasperf/effa823eee44bbfa56c1b579b75b66e1 to your computer and use it in GitHub Desktop.
Basic WordPress Plugin to run scripts on server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Custom Script Runner | |
Description: Allows users to run a custom PHP script. | |
Version: 1.0 | |
Author: Your Name | |
*/ | |
// Define the page where the script can be run | |
function custom_script_runner_menu() { | |
add_menu_page('Script Runner', 'Script Runner', 'manage_options', 'custom-script-runner', 'custom_script_runner_page'); | |
} | |
add_action('admin_menu', 'custom_script_runner_menu'); | |
// Create the page content | |
function custom_script_runner_page() { | |
?> | |
<div class="wrap"> | |
<h1>Custom Script Runner</h1> | |
<?php | |
// Create and output a nonce field | |
$nonce = wp_create_nonce('run_custom_script_nonce'); | |
echo '<button id="run-script-btn" class="button button-primary" data-nonce="' . esc_attr($nonce) . '">Run Script</button>'; | |
?> | |
</div> | |
<script> | |
document.getElementById('run-script-btn').addEventListener('click', function() { | |
// Get the nonce value | |
var nonce = this.getAttribute('data-nonce'); | |
// Perform an AJAX request to run the script with nonce | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', ajaxurl, true); | |
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); | |
xhr.send('action=run_custom_script&nonce=' + nonce); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4 && xhr.status === 200) { | |
// Handle the response, if needed | |
console.log(xhr.responseText); | |
} | |
}; | |
}); | |
</script> | |
<?php | |
} | |
// Define the AJAX action to run the script | |
function run_custom_script() { | |
// Verify nonce | |
$nonce = $_POST['nonce']; | |
if (!wp_verify_nonce($nonce, 'run_custom_script_nonce')) { | |
die('Invalid nonce'); | |
} | |
// Perform necessary checks for security, such as user capabilities | |
// Path to the PHP script (adjust the path accordingly) | |
$script_path = plugin_dir_path(__FILE__) . 'custom-script.php'; | |
// Sanitize the script path (optional, but recommended) | |
$script_path = sanitize_file_name($script_path); | |
// Check if the file exists before including | |
if (file_exists($script_path)) { | |
include $script_path; | |
echo 'Script executed successfully.'; | |
} else { | |
echo 'Script file not found.'; | |
} | |
wp_die(); // Always include this line to terminate the script properly | |
} | |
add_action('wp_ajax_run_custom_script', 'run_custom_script'); | |
?> |
Author
jasperf
commented
Jan 31, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment