This question already has answers here:
Checking if a variable is an integer in PHP
(14 answers)
Closed 7 years ago.
I am doing a pagination script and I want to give users the ability to control how many results are shown in one page. I am doing this through the use of a GET variable, like this: example.org/articles.php?count=10. Only problem is that the GET variable must be an integer or the code spits out random errors, some of which contains information that the user should not be seeing.
Here is my code:
// Checks if there is a GET variable (this part works fine)
if (isset($_GET["count"])) {
if (!empty($_GET["count"])) {
$page_rows = $_GET["count"];
} else {
$page_rows = $page_rows_default;
}
} else {
$page_rows = $page_rows_default;
}
// checks if the GET variable is an interger
// if not, the offending value is replaced with 0
// (it doesn't work)
if(is_int($page_rows) == false) {
$page_rows = 0;
}
From my experimentation my code can tolerate zeros and negative integers, but fails hard when given something like ?count=asdf. I mostly do not want the user to be able to crash the script by injecting random text into the GET variables. How do I get the script to automatically detect non-integer values so that they can be dealt with instead of simply halting the code?
You can use is_numeric().
For reference http://php.net/manual/en/function.is-numeric.php
is_numeric() can done the trick for you
if(is_numeric($page_rows))
{
//your condition
}
else
{
//another condition
}
Related
This question already has answers here:
How to verify if $_GET exists?
(7 answers)
Closed 5 years ago.
Like the title says, how do I determine which GET value has been passed on within the url?
Take http://www.example.com/view.php?id=20as an example. The current GET value is 'id', with a value of 20. This works great, but if someone plays around and changes the GET value to something other than 'id', I get a lot of PHP errors on the page.
So my goal is to check wether the passed GET value is incorrect, so I can redirect them to another page. How would I go about doing that?
You should validate the URL parameters. In your case, it has to be id and that has to be numeric:
if (isset($_GET['id']) && is_numeric($_GET['id']))
As an advance check, you can validate whether id is integer or not:
if((int)$_GET['id'] == $_GET['id']){
return TRUE;
} else {
return FALSE; // It's a number, but not an integer
}
This question already has answers here:
PHP check if url parameter exists
(6 answers)
PHP to check if a URL contains a query string
(4 answers)
Closed 5 years ago.
I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
localhost/myforum/threads.php?categoryid=1
I want it so that when the url is:
localhost/myforum/threads.php
it is to redirect to an error page, and that this piece of code is usable all around the website
The most reliable way is to check if the URL contains a question mark:
if (false !== strpos($_SERVER['REQUEST_URI'], '?')) {
// There is a query string (including cases when it's empty)
}
Try:
$gets = parse_url($url));
if($gets['query'] == "")
{
echo "No GET variables";
}
Just:
if (empty(array_diff($_GET, ['']))) {
header("Location: /path/to/error.php");
}
EDIT: Updated to remove empty values
You can use is_set to check if the parameter exists like this,
isset($_GET)
This question already has answers here:
Is there a "nullsafe operator" in PHP?
(3 answers)
Closed 2 years ago.
Is there a way to "safely" chain methods in PHP and simply return null if some previous method returns null? Otherwise, an error would be thrown: trying to get property on non-object;
For example, the following code checks whether a customer's phone number has changed using a QuickBooks SDK. I don't have control over these methods.
$customer->getPrimaryPhone() will always return an object since the form wouldn't have been submitted otherwise, but $old->getPrimaryPhone() may return null if no phone number existed previously.
The following is required to get the phone number:
$old->getPrimaryPhone()->getFreeFormNumber()
If getPrimaryPhone() returns null, then an error would be thrown.
My question is: How would I avoid code repition in the following case?
if (!empty($old->getPrimaryPhone())) {
if ($customer->getPrimaryPhone()->getFreeFormNumber() !== $old->getPrimaryPhone()->getFreeFormNumber()) {
// Repetive code here
}
} else {
// Repetive code here
}
I'd be inclined to implement an equals method on your PhoneNumber class (or whatever it's called). For example
public function equals(PhoneNumber $otherNumber) {
return $otherNumber !== null && $this->getFreeFormNumber() === $otherNumber->getFreeFormNumber();
}
Then you can simply use
if (!$customer->getPrimaryPhone()->equals($old->getPrimaryPhone())
If you've got other logic that needs to be applied (as indicated in your comment about arrays), you can easily implement that in the equals method.
This question already has answers here:
Weird PHP error: 'Can't use function return value in write context'
(12 answers)
Closed 9 years ago.
This code:
if(!empty(trim($_POST['post']))){ }
return this error:
Fatal error: Can't use function return value in write context in ...
How can I resolve and avoid to do 2 checks ( trim and then empty ) ?
I want to check if POST is not only a blank space.
you cant use functions inside isset , empty statements. just assign the result of trim to a variable.
$r = trim($_POST['blop']);
if(!empty($r))....
edit: Prior to PHP 5.5
if (trim($_POST['post'])) {
Is functionally equivalent to what you appear to be trying to do. There's no need to call !empty
if (trim($_POST['post']) !== "") {
// this is the same
}
In the documentation it actually explains this problem specifically, then gives you an alternate solution. You can use
trim($name) == false.
In PHP, functions isset() and empty() are ment to test variables.
That means this
if(empty("someText")) { ... }
or this
if(isset(somefunction(args))) { ... }
doesn't make any sence, since result of a function is always defined, e.t.c.
These functions serve to tell wether a variable is defined or not, so argument must me a variable, or array with index, then it checks the index (works on objects too), like
if(!empty($_POST["mydata"])) {
//do something
} else {
echo "Wrong input";
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
echo inside if loop
I trying to code a trading system and i have a list of entry and exit strategies. To lessen the number of lines in the code I planned to put all my strategies into an array for each entry and exit. My array is like this
$enter_strats = array(
array('name'=>"macd",'strat'=>"/$divergence[/$key]>0.1;"),
);
I am including the conditional statements inside the array as above.
while I am looping thru everyday prices, I have to check for each entry strategy if they they are true. My if statement is like this
foreach($divergence as $key=>$value)
{
if($trade ==0)
{
foreach($enter_strats as $k =>$v)
{
$strat = $v['strat'];
$strat = str_replace("#","$",$strat);
eval("\$strat = \"$strat\";");
if ($strat)
{
$trade =1;
$book->save($key,$close[$key],$v['name']);
}
}
}
}
The problem since it is a string its always if is always evaluating it to true. I tried to put one more eval inside if but its of no use.
Please help to solve this problem, its is very essential. Thanks a lot.
That's because you're trying to lessen the number of lines in the code.
Arrays intended to keep data, not code.
As soon as you understand it, your code will be okay.
'strat' should contain only data. An operator and a number for instance.
keeping variable name in the string makes no sense.
especially if you have this variable already.
You have already have $divergence[$key] in your code.
So, 'strat' should be just array('>',0.1)