Advertisement
MarcHumer

CORS-Plugin for Wordpress (german)

Mar 2nd, 2025
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.87 KB | Source Code | 0 0
  1. <?php
  2. /*
  3. Plugin Name: MH CORS
  4. Plugin URI: https://humer-it.com/download/plugins/mh/cors
  5. Description: CORS-Settings für die Webseite ohne .htaccess
  6. Version: 25.03
  7. Author: Marc Humer
  8. Author URI: https://humer-it.com
  9. Network: false
  10. */
  11. if (!defined('ABSPATH')) {
  12.     exit;
  13. }
  14.  
  15. function custom_cors_get_defaults() {
  16.     return [
  17.         'origin'             => get_site_url(),
  18.         'methods'           => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Methoden als Array
  19.         'headers'           => 'Content-Type, Authorization',
  20.         'credentials'       => 'false',
  21.         'expose_headers'     => '',
  22.         'max_age'           => '86400',
  23.         'request_method'     => '',
  24.         'request_headers'   => '',
  25.         'timing_allow_origin' => '*'
  26.     ];
  27. }
  28.  
  29. function custom_cors_get_settings() {
  30.     $settings = get_option('custom_cors_settings', []);
  31.     // Stelle sicher, dass 'methods' ein Array ist
  32.     if (!is_array($settings['methods'])) {
  33.         $settings['methods'] = explode(', ', $settings['methods']);
  34.     }
  35.     return wp_parse_args($settings, custom_cors_get_defaults());
  36. }
  37.  
  38. function custom_add_cors_headers() {
  39.     $options = custom_cors_get_settings();
  40.     header("Access-Control-Allow-Origin: ".         $options['origin']);
  41.     header("Access-Control-Allow-Methods: ".        implode(', ', $options['methods']) );
  42.     header("Access-Control-Allow-Headers: ".        $options['headers']);
  43.     header("Access-Control-Expose-Headers: ".       $options['expose_headers']);
  44.     header("Access-Control-Max-Age: ".                  $options['max_age']);
  45.     header("Access-Control-Allow-Credentials: ".($options['credentials'] === 'true' ? 'true' : 'false') );
  46.     if (!empty($options['request_method'])) {               header("Access-Control-Request-Method: ".$options['request_method']);}
  47.     if (!empty($options['request_headers'])) {          header("Access-Control-Request-Headers: ".$options['request_headers']);}
  48.     if (!empty($options['timing_allow_origin'])) {  header("Timing-Allow-Origin: ".$options['timing_allow_origin']);}
  49.     if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){  http_response_code(204); exit;}
  50. }
  51.  
  52. // Hooks für REST-API & normale Seitenaufrufe
  53. add_action('rest_api_init', function() {
  54.     add_filter('rest_pre_serve_request', function($value) {
  55.         custom_add_cors_headers();
  56.         return $value;
  57.     });
  58. });
  59. add_action('send_headers', 'custom_add_cors_headers');
  60.  
  61. // Admin-Menüpunkt hinzufügen
  62. function custom_cors_settings_page() {
  63.     add_menu_page(
  64.         'CORS Einstellungen',
  65.         'CORS Einstellungen',
  66.         'manage_options',
  67.         'custom-cors-settings',
  68.         'custom_cors_settings_page_html',
  69.         'dashicons-admin-network',
  70.         100
  71.     );
  72. }
  73. add_action('admin_menu', 'custom_cors_settings_page');
  74.  
  75.  
  76. function custom_cors_settings_page_html() {
  77.     if (!current_user_can('manage_options')) {return;}
  78.  
  79.     if ($_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('custom_cors_settings_save')) {
  80.         $methods = isset($_POST['custom_cors_methods']) ? $_POST['custom_cors_methods'] : [];
  81.         if (is_array($methods)) {
  82.             $methods = array_map('sanitize_text_field', $methods);
  83.         }
  84.  
  85.         update_option('custom_cors_settings', [
  86.             'origin'             => sanitize_text_field($_POST['custom_cors_origin']),
  87.             'methods'           => $methods, // Speichere die Methoden als Array
  88.             'headers'           => sanitize_text_field($_POST['custom_cors_headers']),
  89.             'expose_headers'     => sanitize_text_field($_POST['custom_cors_expose_headers']),
  90.             'max_age'           => sanitize_text_field($_POST['custom_cors_max_age']),
  91.             'credentials'       => $_POST['custom_cors_credentials'],
  92.             'request_method'     => sanitize_text_field($_POST['custom_cors_request_method']),
  93.             'request_headers'   => sanitize_text_field($_POST['custom_cors_request_headers']),
  94.             'timing_allow_origin' => sanitize_text_field($_POST['custom_cors_timing_allow_origin'])
  95.         ]);
  96.         echo '<div class="updated"><p>Einstellungen gespeichert!</p></div>';
  97.     }
  98.  
  99.     $options = custom_cors_get_settings();
  100.     $methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'];
  101.  
  102.     ?>
  103. <style>
  104.     .cors-info {
  105.         border: 1px solid #ccc;
  106.         padding: 10px;
  107.         margin-top: 5px;
  108.         background-color: #f9f9f9;
  109.         border-radius: 5px;
  110.     }
  111.    
  112. </style>
  113.  
  114.     <div class="wrap">
  115.         <h1>CORS Einstellungen</h1>
  116.         <form method="post">
  117.             <?php wp_nonce_field('custom_cors_settings_save'); ?>
  118.  
  119. <h2>Wichtige CORS-Header</h2>
  120. <table class="form-table">
  121.     <tr>
  122.         <th>Access-Control-Allow-Origin</th>
  123.         <td>
  124.             <input type="text" name="custom_cors_origin" value="<?php echo esc_attr($options['origin']); ?>" class="regular-text">
  125.             <p class="description">
  126.                 Gibt an, welche Domains auf die Ressourcen zugreifen dürfen.  
  127.                 <strong>*</strong> erlaubt alle, aber das ist aus Sicherheitsgründen oft nicht ratsam.
  128.             </p>
  129.         </td>
  130.     </tr>
  131.     <tr>
  132.         <th>Timing-Allow-Origin</th>
  133.         <td>
  134.             <input type="text" name="custom_cors_timing_allow_origin" value="<?php echo esc_attr($options['timing_allow_origin']); ?>" class="regular-text">
  135.             <p class="description">
  136.                 Ähnlich wie `Access-Control-Allow-Origin`, aber für Timing-Daten.  
  137.                 <br>Falls aktiviert, können Webseiten Performance-Messungen über die Netzwerkzeit (z. B. Ladezeiten) durchführen.
  138.             </p>
  139.         </td>
  140.     </tr>
  141.     <tr>
  142.         <th>Access-Control-Allow-Methods</th>
  143.         <td>
  144.             <?php
  145.             $http_methods = [
  146.                 "GET" => "Liest Daten vom Server",
  147.                 "POST" => "Sendet neue Daten an den Server",
  148.                 "PUT" => "Aktualisiert eine Ressource",
  149.                 "PATCH" => "Teilweises Update einer Ressource *",
  150.                 "DELETE" => "Löscht eine Ressource",
  151.                 "OPTIONS" => "Prüft, welche Methoden erlaubt sind"
  152.             ];
  153.             foreach ($http_methods as $method => $description) : ?>
  154.                 <label>
  155.                     <input type="checkbox" name="custom_cors_methods[]" value="<?php echo $method; ?>" <?php echo in_array($method, $options['methods']) ? 'checked' : ''; ?> >  
  156.                     <?php echo $method; ?> - <small><?php echo $description; ?></small>
  157.                 </label><br>
  158.             <?php endforeach; ?>
  159.             <p class="description">Wählen Sie die erlaubten HTTP-Methoden aus.</p>
  160.             <p class="description">
  161. * 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, &hellip;)
  162. <br>PATCH kann nur die E-Mail änern, ohne die anderen Felder zu senden.</p>
  163.         </td>
  164.     </tr>
  165.     <tr>
  166.         <th>Access-Control-Allow-Headers</th>
  167.         <td>
  168.             <input type="text" name="custom_cors_headers" value="<?php echo esc_attr($options['headers']); ?>" class="regular-text">
  169.             <p class="description">Liste der erlaubten Header, z. B. `Content-Type, Authorization`.</p>
  170.  
  171.         </td>
  172.     </tr>
  173.     <tr>
  174.         <th>Access-Control-Allow-Credentials</th>
  175.         <td>
  176.             <select name="custom_cors_credentials">
  177.                 <option value="true" <?php selected($options['credentials'], 'true'); ?> >true</option>
  178.                 <option value="false" <?php selected($options['credentials'], 'false'); ?> >false</option>
  179.             </select>
  180.             <p class="description">Erlaubt Cookies und Authentifizierungsinformationen (`true` oder `false`).</p>
  181.         </td>
  182.     </tr>
  183.     <tr>
  184.         <th>Access-Control-Expose-Headers</th>
  185.         <td>
  186.             <input type="text" name="custom_cors_expose_headers" value="<?php echo esc_attr($options['expose_headers']); ?>" class="regular-text">
  187.             <p class="description">
  188.                 Definiert, welche Header für <B>JavaScript</B> auf der Client-Seite sichtbar sind / übergeben werden.  
  189.             </p>
  190.  
  191.  
  192. <div style="display:inline-block;">
  193.  
  194.     <div id="corsInfo" class="cors-info">
  195. <p><strong>Die folgenden Header sind Standard und müssen - und sollten - NICHT nochmals explizit eingetragen werden.</strong>
  196. <br><code>Cache-Control</code>, <code>Content-Language</code>, <code>Content-Type</code>, <code>Expires</code>, <code>Last-Modified</code>, <code>Pragma</code>
  197. <br>JavaScript kann immer auf auf die folgenden Header zugreifen (sofern nicht serverseitig unterbunden):
  198.  
  199. </p>        <hr>
  200.  
  201.         <strong>Weitere mögliche Header (werden häufig bei API-Zugriffen verwendet und müssen explizit freigegeben werden)</strong>
  202.         <ul>
  203.             <li><code>Authorization</code> → Falls Tokens oder Authentifizierung über den Header laufen</li>
  204.             <li><code>X-Request-ID</code> → Falls eine eindeutige Anfragennummer mitgeliefert wird</li>
  205.             <li><code>X-RateLimit-Limit</code>, <code>X-RateLimit-Remaining</code> → Falls deine API Ratelimits nutzt</li>
  206.             <li><code>Location</code> → Falls Weiterleitungen (Redirects) von der API gesteuert werden</li>
  207.             <li><code>Link</code> → Falls du paginierte API-Ergebnisse hast</li>
  208.             <li><code>ETag</code> → Falls du Caching-Mechanismen nutzen willst</li>
  209.             <li><code>X-Custom-Header</code> → Beispiel für eigene, benutzerdefinierte Header</li>
  210.         </ul>
  211.     </div>
  212. </div>
  213.  
  214.  
  215.         </td>
  216.     </tr>
  217.     <tr>
  218.         <th>Access-Control-Max-Age</th>
  219.         <td>
  220.             <input type="number" name="custom_cors_max_age" value="<?php echo esc_attr($options['max_age']); ?>" class="small-text">
  221.             <p class="description">
  222.                 Gibt an, wie lange die Preflight-Request-Ergebnisse gecached werden dürfen (in Sekunden).  
  223.                 <br>Ein hoher Wert reduziert unnötige Preflight-Anfragen.
  224.             </p>
  225.         </td>
  226.     </tr>
  227. </table>
  228.  
  229. <hr>
  230.  
  231. <h2>Selten verwendete CORS-Header</h2>
  232. <table class="form-table">
  233.     <tr>
  234.         <th>Access-Control-Request-Method</th>
  235.         <td>
  236.             <input type="text" name="custom_cors_request_method" value="<?php echo esc_attr($options['request_method']); ?>" class="regular-text">
  237.             <p class="description">
  238.                 Dieser Header wird in Preflight-Anfragen verwendet, um anzugeben, welche Methode die tatsächliche Anfrage nutzen möchte.  
  239.                 <br>Falls Ihr Server `PUT` oder `DELETE` Anfragen erlaubt, sollte dieser Header geprüft werden.
  240.             </p>
  241.         </td>
  242.     </tr>
  243.     <tr>
  244.         <th>Access-Control-Request-Headers</th>
  245.         <td>
  246.             <input type="text" name="custom_cors_request_headers" value="<?php echo esc_attr($options['request_headers']); ?>" class="regular-text">
  247.             <p class="description">
  248.                 Header, die vom Client bei einem Preflight-Request gesendet werden.  
  249.                 Beispiel: `Authorization, Content-Type`
  250.             </p>
  251.         </td>
  252.     </tr>
  253. </table>
  254.  
  255.  
  256.             <?php submit_button('Speichern'); ?>
  257.         </form>
  258.     </div>
  259.     <?php
  260. }
  261.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement