To make `no-variable` if-clause in PHP - php

How can you make the if -clause which do this and this if
there is no variable in the URL by PHP?
there is no variable which has value in the URL by PHP?
Examples of the URLs which should be true for the if -clause for #1:
www.example.com/index.php
example.com/index.php
example.com/index.php?
Examples of the URLs which should be true for the if -clause for #2:
example.com/index.php?successful_registration
example.com/index.php?successful_login
The following is my unsuccessful if -clause for $1
if (isset($_REQUEST[''])) {
// do this
}

if ( 0 == count( $_GET ) )
{
// do this
}
or
if ( empty( array_keys( $_GET ) ) )
{
// do this
}
or
if ( '' == $_SERVER['QUERY_STRING'] )
{
// do this
}

You'd want to check $_GET and $_SERVER["query_string"].
If the query string is empty, you've got just the base url. If the query string is not empty, but one of the $_GET variables is empty, you've got an invalid domain.

If statements are not loops. You might call it an condition though.
if(isset($_REQUEST['successful_registration'])) {
//do this
}elseif(isset($_REQUEST['successful_login'])) {
//do this
}else{
//do this
}

Related

php in_array giving odd result

I've read all the other articles on in_array, and still don't understand why mine is givng odd results. I'm inheriting this code from someone else, and don't fully understand why they did certain things. When a user logs in, data is grabbed from a db, one of the fields being their "level". 1 is an admin, 2 a regular user, etc. Once the data is grabbed from the db, we put the user level (stored as a:1:{i:0;s:1:"2") into an array:
$user_level = unserialize($this->result['user_level']);
$_SESSION['unt']['user_level'] = $user_level;
Later we check to see if this is an admin:
error_log(print_r($_SESSION['abc']['user_level'])); //this is always "1"
if (in_array('1', $_SESSION['abc']['user_level'])) { //should be yes, correct?
Yet somehow the if statement never evaluates as true, even though the SESSION variable is 1. What am I missing?
$_SESSION['abc']['user_level'] doesn't appear to be an array. Looks like you want one of the following.
If gettype($_SESSION['abc']['user_level']) is 'integer':
if ($_SESSION['abc']['user_level']) === 1) {
If gettype($_SESSION['abc']['user_level']) is 'string':
if ($_SESSION['abc']['user_level']) === '1') {
If gettype($_SESSION['abc']['user_level']) is 'string' and its value actually contains the quotes:
if ($_SESSION['abc']['user_level']) === '"1"') {
If it was an array the output would have this structure, not just "1":
Array
(
[0] => 1
)
Even though I noticed closing bracket } missing from your input string I just assumed that you probably might have missed while copy-pasting .
a:1:{i:0;s:1:"2"
So in_array is not the problem but your input string is the problem .With display_errors setting Off you would not see any error when you try to unserialize it .
You could use the below function to check if the input is a valid string to unserialize :
// Copied from http://www.php.net/manual/en/function.unserialize.php
function is_serialized( $str )
{
return( $str == serialize( false ) || #unserialize( $str ) !== false );
}
Then something along these lines :
$inputString = 'a:1:{i:0;s:1:"2";}'; // Is valid and is holding one array of info
// $inputString = 'a:1:{i:0;s:1:"2"'; // Invalid as is missing a closing baracket }
if( ! is_serialized( $inputString ) )
{
echo 'Is not serialized';
}
else
{
$user_level = unserialize( $inputString );
$_SESSION['unt']['user_level'] = $user_level; // Is an array
// Note the second argument as was already pointed by #AsksAnyway
error_log( print_r( $_SESSION['unt']['user_level'] , true ) );
var_dump( in_array( '1' ,$_SESSION['unt']['user_level']) );
var_dump( in_array( '2' ,$_SESSION['unt']['user_level']) );
}

In PHP, how do I substitute a string variable before it's evaluated?

Is it possible to expand/substitute a variable before PHP tries to evaluate its truth value?
I'm trying to code a single Wordpress template that will execute different queries depending on which page we're on. If we're on the homepage, the query should look like this:
while ( $postlist->have_posts() ) : $postlist->the_post();
// code...
If we're not on the homepage, the query should look like this:
while ( have_posts() ): the_post();
// code...
So I thought I would try this:
$query_prefix = ( is_front_page() ) ? '$postlist->' : '';
$query_condition = $query_prefix.'have_posts()';
$query_do = $query_prefix.'the_post()';
while ( $query_condition ): $query_do;
// code...
The problem is, this is creating an infinite loop, because $query_condition is a string and evaluates to TRUE. It seems like PHP never 'reads' the content of the variable. I need my variable to expand itself literally, and only then offer itself for evaluation. Can anyone please tell me how how to do this?
Any of these answers work, but to provide another alternative:
if(is_front_page()) {
$callable_condition = array($postlist,'have_posts');
$callable_do = array($postlist,'the_post');
} else {
$callable_condition = 'have_posts';
$callable_do = 'the_post';
}
while(call_user_func($callable_condition)) : call_user_func($callable_do);
Also, if you are inside an object, you can use array($this,'method') to call a method of your object.
One way to handle this would to use a logical or statement in your while condition to loop based on different objects depending on the result of is_front_page(), and then an if statement to control the call to the_post() as well.
// loop while the front page and $postlist OR not the front page and not $postlist
while ( (is_front_page() && $postlist->have_posts() ) || ( !is_front_page() && have_posts() ) ):
// use $postlist if on the front page
if ( is_front_page() && !empty($postlist) ){
$postlist->the_post();
} else {
the_post();
}
// the rest of your code
endwhile;
May be such example could possible help you. This is about using variables of variables:
class A {
public function foo(){
echo "foo" ;
}
}
$a = new A() ;
$obj = 'a' ;
$method = "foo" ;
${$obj}->$method() ; //Will echo "foo"
I've always used the_title for determining the page.
$isHomePage = false;
if(the_title( '', '', FALSE ) == "Home")
{
$isHomePage = true;
}
Then i use $isHomePage as a flag for anything else I need later in the page. This can be changed to look for any page you want to single out. It can get hairy if you have long page names though, so there is that.

PHP test for empty and/or null and/or unset array

I want to keep this short. I don't know if I have the terminology correct, but I got this example from the Codeigniter handbook Vol.1.
if (count($args) > 1 || is_array($args[0]))
I've run into this problem numerous times. Depending on the datatype different tests are more appropriate. Some tests will just fail in unexpected ways.
How does one determine the most appropriate, and possibly, the most concise test?
Just to be clear I'm looking for the most effective way to test if an object/variable is ready to use, regardless of the datatype, if that's possible.
Also I don't want the solution to apply merely to lists like in the example. It should be widely applicable.
Just use empty
if(!empty($args)){
echo 'Array is set, not empty and not null';
}
use empty() bool empty ( mixed $var )
http://www.php.net/manual/en/function.empty.php
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
I've been using the following function for a while.
You can add your own test for all possible variable types.
function is_valid_var($var)
{
if ( isset( $var ) ) {
// string
if ( is_string( $var ) && strlen( $var ) == 0 ) return false;
// array
elseif ( is_array( $var ) && count( $var ) == 0 ) return false;
// unknown
else return true;
}
return false;
}

"if else statement" when no $_REQUEST exist

I am making a simple if and else statement to get value from a requested link my code is
if($_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
and suppose the link is www.example.com/profile.php?f_id=3
now its simple as if the f_id is empty or with value either of the above if and else statement would run. but what is a user is just playing around with link and he removes the whole ?f_id=3 with link left to be opened with www.example.com/profile.php then how to detect that f_id dosen't exist and in that case redirect to a error page ?
if ( isset( $_REQUEST['f_id'] ) ) {
if($_REQUEST['f_id']=='') {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}
} else {
REDIRECT TO ERROR PAGE
}
UPDATE Since your URLS-s look like www.example.com/profile.php?f_id=3 you should use $_GET instead of $_REQUEST
you can use the isset() php function to test that:
if(!isset($_REQUEST) || $_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
Late answer, but here's an "elegant" solution that I always use. I start with this code for all the variables I'm interested in and go from there. There are a number of other things you can do with the extracted variables as well shown in the PHP EXTRACT documentation.
// Set the variables that I'm allowing in the script (and optionally their defaults)
$f_id = null // Default if not supplied, will be null if not in querystring
//$f_id = 0 // Default if not supplied, will be false if not in querystring
//$f_id = 'NotFound' // Default if not supplied, will be 'NotFound' if not in querystring
// Choose where the variable is coming from
extract($_REQUEST, EXTR_IF_EXISTS); // Data from GET or POST
//extract($_GET, EXTR_IF_EXISTS); // Data must be in GET
//extract($_POST, EXTR_IF_EXISTS); // Data must be in POST
if(!$f_id) {
die("f_id not supplied...do redirect here");
}
You could use empty to combine the 2x isset into 1 statement (unless you actually have a friend_id of 0 which would result in empty being true)
if(empty($_REQUEST['f_id'])) {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}

Php pages dependent on query string but what if there's no parameter?

I am creating pages that are dependent on a query in the url (eg europe.php?country=france). I am aware that it will be useful to re-write theses as europe.php/france with htaccess for SEO etc but what if that page is accessed without the query string?
I am using php to $_GET the query, so if I access the page without the query I get 'var=;' ie, it is empty (and retrieves an error). I'm trying to use an if statement to check if the $_GET retrieves nothing but am unsure if this is the right thing to do.
So: how do I check for an un-retrieved var so I can set a default?
Or: am I going about this the wrong way?
If you know the index into $_GET, use isset():
$country = 'default';
if( isset( $_GET['country'])) {
$country = $_GET['country'];
}
This will only test if the country parameter was passed, but it could have been set to an empty string. If this is invalid input, you can combine the check using empty():
$country = 'default';
if( isset( $_GET['country']) && !empty( $_GET['country'])) {
$country = $_GET['country'];
}
You can condense this into one line and save the result to a variable $country using the ternary operator, like so:
$country = (isset( $_GET['country']) && !empty( $_GET['country'])) ? $_GET['country'] : 'default';
Finally, you can check if you got absolutely no $_GET parameters by calling count() on $_GET:
if( count( $_GET) == 0) {
die( "No parameters - Invalid input!");
}
since isset() really tests for "NOT NULL", you should use empty() to test if an empty string was given:
if (empty($_GET['country'])) {
$_GET['country'] = "default";
}
that is, unless you expect 0 to be a valid input, in that case, you'd have to check with isset and make sure the string has at least one character:
if (!isset($_GET['country']) || !strlen($_GET['country'])) {
$_GET['country'] = "default";
}
which can be optimized into
if (!isset($_GET['country']) || !isset($_GET['country'][0])) {
$_GET['country'] = "default";
}
try using something like this:
$var = ( isset($_GET['var']) ? $_GET['var'] : 'default value' )
Try doing this
if(isset($_GET['your_variable'])) {
$variable = $_GET['your_variable'];
} else {
$variable = "not set";
}
That will set the variable if it is set in your URL - or it can set your variable to some other value if it is not set in the URL
Running a check at the start of the page to see if var is set is fine to do. If it's empty, you can redirect using something like:
header("HTTP/1.0 404 Not Found");
header('Location:YOUR PAGE NOT FOUND PAGE');
exit();
On a side note, if you're using data from $_GET, you need to make sure that this data is validated & cleaned to prevent against all sorts of security intrusions, such as XSS and, if you use a database, MYSQL injection. Running a test at the start of the page to check if it's empty can be just the start - you can also make sure that the data is something you'd expect (say, check it's alphanumeric). After, with $_GET data, anyone could fill the URL bar with whatever they like and potentially damage your website.
Hope this has helped!

Categories