I have the following url where var_a should always be a number. Also I don´t know how many var_a will be:
http://localhost/url.php?var_a[]=298&var_a[]=299
How to prevent getting an error if the user writes special characters in the url?
I have done this:
$data = preg_replace('/[^0-9\']/', '',$_GET['var_a']);
$data = str_replace("'", '', $data);
print_r ($data);// Array ( [0] => 298 [1] => 299 )
//This is ok, all number were printed
But I still get an error with the special characters like # % &
e.g.
http://localhost/url.php?var_a[]=298&var_a[]=#299
print_r ($data);// Array ( [0] => 298 [1] => )
//299 was not printed!
How can I fix this?
As far as I can tell, you can't fix it if the users are entering the values directly in the URL. The reason being is that these characters have special meanings in URLS: # represents data fragment, % represents unicode values, and & represents a new variable . The two options you can do are to use if it is coming from a form is to use $_POST values, or use urlencode before submitting the values. Pound sign (#) not working in PHP has more information on using urlencode .