i try to use the rest api with encrypted data in the url.
For example i create the url with given data like this:
$data = (object) [
'name' => $_POST["name"],
'email' => $_POST["email"],
'telefon' => $_POST["telefon"],
'firma' => $_POST["firma"],
'timestamp' => "123",
];
$json = json_encode($data);
$encrypted = openssl_encrypt($json, $this->cipher, $this->key);
$url_data = urlencode($encrypted);
$url = site_url() . '/wp-json/ebooks/' . $url_data;
My register_rest_route
looks like this:
register_rest_route(
'ebooks', '/(?P<data>.*)', array(
'methods' => 'GET',
'callback' => array($this, 'optin'),
'permission_callback' => '__return_true',
));
Example of generated url:
http://127.0.0.1//wp-json/ebooks/NgG90Q7hogoX05oildW45kQA2ykAzYBISpkl128IkfeLqqhG3dsbMsPVLCCx9AgvCkOtEM7iOwBlxjY5nidoKiGBKbU3TYYiiKbS85pA9SDrS0wtDA%2FAmHN4CfxpGONm
If i open that url i get a 404 error. I think the %
in the url is the problem. If i replace the %
with another digit or character than all works fine!
Why is the %
a problem and how can i solve it?
Edit:
My optin
function.
public function optin($data) {
$dec_url = urldecode($data['data']);
$decrypted = openssl_decrypt($dec_url, $this->cipher, $this->key);
$json = json_decode($decrypted);
print_r($json);
return 0;
}
My Answer:
The issue with using % in the URL is that it is a reserved character in URLs and is used for encoding special characters. When you use % in the URL, it is interpreted as an encoded character and can cause issues with routing.
To solve this issue, you can try using base64 encoding instead of urlencode for your encrypted data. Base64 encoding will not use % in the encoded string and should work fine in the URL.
Here is an example of how you can encode and decode using base64:
Encoding:
php
$encrypted = openssl_encrypt($json, $this->cipher, $this->key);
$encoded = base64_encode($encrypted);
$url_data = urlencode($encoded);
Decoding:
php
$decoded = base64_decode(urldecode($data['data']));
$decrypted = openssl_decrypt($decoded, $this->cipher, $this->key);
By using base64 encoding, you should be able to avoid the issue with % in the URL and successfully pass encrypted data through the WordPress REST API.
Rate this post
4 of 5 based on 5103 votesComments