Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Last active April 10, 2023 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmu83/0b3c402e2893bd7910fe9ed3d08e7f77 to your computer and use it in GitHub Desktop.
Save ahmu83/0b3c402e2893bd7910fe9ed3d08e7f77 to your computer and use it in GitHub Desktop.
<?php
/**
* This function should be only used in AJAX templates & AJAX callbacks.
*
*
* Use cases of this function are when you need to get a URL param inside a
* PHP template rendered through AJAX or an AJAX callback that needs access
* to the parent URL param (From where the ajax call was made). i.e,
* calling ajax.php from http://exmple.com/my-page/?param1=v111&param2=v222.
* A header of URLPARAMS needsto be added to the request headers. i.e, using
* jQuery.ajax add it by doing $.ajaxSetup({headers: {'URLPARAMS': window.location.search}}).
* You can modify it to use HTTP_REFERER param. But some browsers block this for security reasons.
* This will fallback to current URL params if the request header is not present.
*
* The URL params are sanitized to 3 level in depth.
* i.e, aaa[q][]=111&aaa[q][]=99&bbb[]=444&bbb[aaa]=555&bbb[aaa][][]=555
*
* @param string Name of the param to get
* @return mixed
*/
function parent_url_param($name = false) {
// $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : get_current_url();
$referer = isset($_SERVER['HTTP_URLPARAMS']) ? $_SERVER['HTTP_URLPARAMS'] : get_current_url();
$url_params_str = parse_url($referer, PHP_URL_QUERY);
parse_str($url_params_str, $url_params);
$sanitize_fn = function($value) {
// return is_array($value) ? null : sanitize_text_field($value); // If using WordPress
return is_array($value) ? null : preg_replace('/[^-a-zA-Z0-9_]/', '', $value);
};
$url_params_sanitized = array();
foreach ($url_params as $key => $value) {
$url_params_sanitized[$key] = $sanitize_fn($value);
if ( is_null($sanitize_fn($value)) ) {
foreach ($value as $key2 => $value2) {
$url_params_sanitized[$key][$key2] = $sanitize_fn($value2);
if ( is_null($sanitize_fn($value2)) ) {
foreach ($value2 as $key3 => $value3) {
$url_params_sanitized[$key][$key2][$key3] = $sanitize_fn($value3);
if ( is_null($sanitize_fn($value3)) ) {
foreach ($value3 as $key4 => $value4) {
$url_params_sanitized[$key][$key2][$key3][$key4] = $sanitize_fn($value4);
}
}
}
}
}
}
}
if ( $name ) {
return isset($url_params_sanitized[$name]) ? $url_params_sanitized[$name] : null;
}
return $url_params_sanitized;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment