Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: MH CORS
- Plugin URI: https://humer-it.com/download/plugins/mh/cors
- Description: CORS-Settings für die Webseite ohne .htaccess
- Version: 25.03
- Author: Marc Humer
- Author URI: https://humer-it.com
- Network: false
- */
- if (!defined('ABSPATH')) {
- exit;
- }
- function custom_cors_get_defaults() {
- return [
- 'origin' => get_site_url(),
- 'methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Methoden als Array
- 'headers' => 'Content-Type, Authorization',
- 'credentials' => 'false',
- 'expose_headers' => '',
- 'max_age' => '86400',
- 'request_method' => '',
- 'request_headers' => '',
- 'timing_allow_origin' => '*'
- ];
- }
- function custom_cors_get_settings() {
- $settings = get_option('custom_cors_settings', []);
- // Stelle sicher, dass 'methods' ein Array ist
- if (!is_array($settings['methods'])) {
- $settings['methods'] = explode(', ', $settings['methods']);
- }
- return wp_parse_args($settings, custom_cors_get_defaults());
- }
- function custom_add_cors_headers() {
- $options = custom_cors_get_settings();
- header("Access-Control-Allow-Origin: ". $options['origin']);
- header("Access-Control-Allow-Methods: ". implode(', ', $options['methods']) );
- header("Access-Control-Allow-Headers: ". $options['headers']);
- header("Access-Control-Expose-Headers: ". $options['expose_headers']);
- header("Access-Control-Max-Age: ". $options['max_age']);
- header("Access-Control-Allow-Credentials: ".($options['credentials'] === 'true' ? 'true' : 'false') );
- if (!empty($options['request_method'])) { header("Access-Control-Request-Method: ".$options['request_method']);}
- if (!empty($options['request_headers'])) { header("Access-Control-Request-Headers: ".$options['request_headers']);}
- if (!empty($options['timing_allow_origin'])) { header("Timing-Allow-Origin: ".$options['timing_allow_origin']);}
- if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){ http_response_code(204); exit;}
- }
- // Hooks für REST-API & normale Seitenaufrufe
- add_action('rest_api_init', function() {
- add_filter('rest_pre_serve_request', function($value) {
- custom_add_cors_headers();
- return $value;
- });
- });
- add_action('send_headers', 'custom_add_cors_headers');
- // Admin-Menüpunkt hinzufügen
- function custom_cors_settings_page() {
- add_menu_page(
- 'CORS Einstellungen',
- 'CORS Einstellungen',
- 'manage_options',
- 'custom-cors-settings',
- 'custom_cors_settings_page_html',
- 'dashicons-admin-network',
- 100
- );
- }
- add_action('admin_menu', 'custom_cors_settings_page');
- function custom_cors_settings_page_html() {
- if (!current_user_can('manage_options')) {return;}
- if ($_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('custom_cors_settings_save')) {
- $methods = isset($_POST['custom_cors_methods']) ? $_POST['custom_cors_methods'] : [];
- if (is_array($methods)) {
- $methods = array_map('sanitize_text_field', $methods);
- }
- update_option('custom_cors_settings', [
- 'origin' => sanitize_text_field($_POST['custom_cors_origin']),
- 'methods' => $methods, // Speichere die Methoden als Array
- 'headers' => sanitize_text_field($_POST['custom_cors_headers']),
- 'expose_headers' => sanitize_text_field($_POST['custom_cors_expose_headers']),
- 'max_age' => sanitize_text_field($_POST['custom_cors_max_age']),
- 'credentials' => $_POST['custom_cors_credentials'],
- 'request_method' => sanitize_text_field($_POST['custom_cors_request_method']),
- 'request_headers' => sanitize_text_field($_POST['custom_cors_request_headers']),
- 'timing_allow_origin' => sanitize_text_field($_POST['custom_cors_timing_allow_origin'])
- ]);
- echo '<div class="updated"><p>Einstellungen gespeichert!</p></div>';
- }
- $options = custom_cors_get_settings();
- $methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'];
- ?>
- <style>
- .cors-info {
- border: 1px solid #ccc;
- padding: 10px;
- margin-top: 5px;
- background-color: #f9f9f9;
- border-radius: 5px;
- }
- </style>
- <div class="wrap">
- <h1>CORS Einstellungen</h1>
- <form method="post">
- <?php wp_nonce_field('custom_cors_settings_save'); ?>
- <h2>Wichtige CORS-Header</h2>
- <table class="form-table">
- <tr>
- <th>Access-Control-Allow-Origin</th>
- <td>
- <input type="text" name="custom_cors_origin" value="<?php echo esc_attr($options['origin']); ?>" class="regular-text">
- <p class="description">
- Gibt an, welche Domains auf die Ressourcen zugreifen dürfen.
- <strong>*</strong> erlaubt alle, aber das ist aus Sicherheitsgründen oft nicht ratsam.
- </p>
- </td>
- </tr>
- <tr>
- <th>Timing-Allow-Origin</th>
- <td>
- <input type="text" name="custom_cors_timing_allow_origin" value="<?php echo esc_attr($options['timing_allow_origin']); ?>" class="regular-text">
- <p class="description">
- Ähnlich wie `Access-Control-Allow-Origin`, aber für Timing-Daten.
- <br>Falls aktiviert, können Webseiten Performance-Messungen über die Netzwerkzeit (z. B. Ladezeiten) durchführen.
- </p>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Allow-Methods</th>
- <td>
- <?php
- $http_methods = [
- "GET" => "Liest Daten vom Server",
- "POST" => "Sendet neue Daten an den Server",
- "PUT" => "Aktualisiert eine Ressource",
- "PATCH" => "Teilweises Update einer Ressource *",
- "DELETE" => "Löscht eine Ressource",
- "OPTIONS" => "Prüft, welche Methoden erlaubt sind"
- ];
- foreach ($http_methods as $method => $description) : ?>
- <label>
- <input type="checkbox" name="custom_cors_methods[]" value="<?php echo $method; ?>" <?php echo in_array($method, $options['methods']) ? 'checked' : ''; ?> >
- <?php echo $method; ?> - <small><?php echo $description; ?></small>
- </label><br>
- <?php endforeach; ?>
- <p class="description">Wählen Sie die erlaubten HTTP-Methoden aus.</p>
- <p class="description">
- * PATCH wird <U>nicht</U> von jedem Server unterstützt; im Zweifel PUT wählen.<br>Fallbeispiel API: bei PUT werden z.B. beim Ändern der E-Mail auch alle anderen Daten mitgesendet (z. B. Name, Adresse, …)
- <br>PATCH kann nur die E-Mail änern, ohne die anderen Felder zu senden.</p>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Allow-Headers</th>
- <td>
- <input type="text" name="custom_cors_headers" value="<?php echo esc_attr($options['headers']); ?>" class="regular-text">
- <p class="description">Liste der erlaubten Header, z. B. `Content-Type, Authorization`.</p>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Allow-Credentials</th>
- <td>
- <select name="custom_cors_credentials">
- <option value="true" <?php selected($options['credentials'], 'true'); ?> >true</option>
- <option value="false" <?php selected($options['credentials'], 'false'); ?> >false</option>
- </select>
- <p class="description">Erlaubt Cookies und Authentifizierungsinformationen (`true` oder `false`).</p>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Expose-Headers</th>
- <td>
- <input type="text" name="custom_cors_expose_headers" value="<?php echo esc_attr($options['expose_headers']); ?>" class="regular-text">
- <p class="description">
- Definiert, welche Header für <B>JavaScript</B> auf der Client-Seite sichtbar sind / übergeben werden.
- </p>
- <div style="display:inline-block;">
- <div id="corsInfo" class="cors-info">
- <p><strong>Die folgenden Header sind Standard und müssen - und sollten - NICHT nochmals explizit eingetragen werden.</strong>
- <br><code>Cache-Control</code>, <code>Content-Language</code>, <code>Content-Type</code>, <code>Expires</code>, <code>Last-Modified</code>, <code>Pragma</code>
- <br>JavaScript kann immer auf auf die folgenden Header zugreifen (sofern nicht serverseitig unterbunden):
- </p> <hr>
- <strong>Weitere mögliche Header (werden häufig bei API-Zugriffen verwendet und müssen explizit freigegeben werden)</strong>
- <ul>
- <li><code>Authorization</code> → Falls Tokens oder Authentifizierung über den Header laufen</li>
- <li><code>X-Request-ID</code> → Falls eine eindeutige Anfragennummer mitgeliefert wird</li>
- <li><code>X-RateLimit-Limit</code>, <code>X-RateLimit-Remaining</code> → Falls deine API Ratelimits nutzt</li>
- <li><code>Location</code> → Falls Weiterleitungen (Redirects) von der API gesteuert werden</li>
- <li><code>Link</code> → Falls du paginierte API-Ergebnisse hast</li>
- <li><code>ETag</code> → Falls du Caching-Mechanismen nutzen willst</li>
- <li><code>X-Custom-Header</code> → Beispiel für eigene, benutzerdefinierte Header</li>
- </ul>
- </div>
- </div>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Max-Age</th>
- <td>
- <input type="number" name="custom_cors_max_age" value="<?php echo esc_attr($options['max_age']); ?>" class="small-text">
- <p class="description">
- Gibt an, wie lange die Preflight-Request-Ergebnisse gecached werden dürfen (in Sekunden).
- <br>Ein hoher Wert reduziert unnötige Preflight-Anfragen.
- </p>
- </td>
- </tr>
- </table>
- <hr>
- <h2>Selten verwendete CORS-Header</h2>
- <table class="form-table">
- <tr>
- <th>Access-Control-Request-Method</th>
- <td>
- <input type="text" name="custom_cors_request_method" value="<?php echo esc_attr($options['request_method']); ?>" class="regular-text">
- <p class="description">
- Dieser Header wird in Preflight-Anfragen verwendet, um anzugeben, welche Methode die tatsächliche Anfrage nutzen möchte.
- <br>Falls Ihr Server `PUT` oder `DELETE` Anfragen erlaubt, sollte dieser Header geprüft werden.
- </p>
- </td>
- </tr>
- <tr>
- <th>Access-Control-Request-Headers</th>
- <td>
- <input type="text" name="custom_cors_request_headers" value="<?php echo esc_attr($options['request_headers']); ?>" class="regular-text">
- <p class="description">
- Header, die vom Client bei einem Preflight-Request gesendet werden.
- Beispiel: `Authorization, Content-Type`
- </p>
- </td>
- </tr>
- </table>
- <?php submit_button('Speichern'); ?>
- </form>
- </div>
- <?php
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement