I'm using a GET variable and people get to it by the following URL:
page?siteID=1
and I check to make sure that siteID is an integer, but PHP is saying it is a string.
How can I convert it to a integer? I noticed that intval() would convert 0x1A to 26, which I don't want to happen.
If you don't want to convert the variable, but simply check if it represents a number, you can also use the is_numeric function. Either that, or you can use the conversion methods as described in other answers, whichever suits your particular need best.
EDIT: based on James Socol's comment, it may also be worth looking at the ctype_digit function. For your particular application (it looks like you want to check for some page ID number), this might be better suited than the is_numeric function.
Just as a side note, so that you know why this is happening, here's what's going on.
When a web browser sends a GET request, it's all text. The URL `http://example.com/page?siteID=1' is actually sent as a single string; in the HTTP request it will be this line:
GET /page?siteID=1 HTTP/1.0
(The "http://example.com" part was used by the web browser to figure out which server to talk to, and what network protocol to use.)
PHP gets hold of that and does a whole bunch of work for you to parse it. It splits it into three pieces based on those spaces (method "GET", URI "/page?siteID=1" and protocol "HTTP/1.1"), and further parses the URI into a path ("/page") and query parameters ("siteID=1"), which it further parses into name/value pairs. And even that whole GET line quoted above was only part of the full text stream delivered to the HTTP server as a request.
So you're seeing the the result of a whole lot of work to convert a longish sequence of characters into a lot of different pieces.
If you're really curious, you can use tools such as Wireshark or the Firefox Live HTTP Headers plugin to see the details of what text strings are actually passing over the network. It's worth learning, if you're a web developer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With