How to use multiple $_GET in PHP through a URL

Asked

Viewed 365 times

2

Through a URL, I want to display a set of information in the HTML of the page, however, there are values I want to repeat in certain URL’s and others not.

Example:

http://wwww.example.com/example.php?c=resultado1

<?php echo "<div class='campo1'>" . $_GET['c'] . "</div>" ;?>  

I want to repeat the $_GET['c'] in the URL, and automatically generate a new DIV with the new value passed by the URL

http://wwww.example.com/example.php?c=resultado1&c2=resultado2

What I’m not getting is to hit PHP in HTML. I tried to duplicate the function echo above, but if I don’t enter her GET value in the URL, the DIV is displayed anyway (blank), something I don’t want to happen. How should I proceed?

3 answers

2

Just make a condition with the use of the function isset that checks that the variable is defined and is not null.

if(isset($_GET['c']))
    echo "<div class='campo1'>" . $_GET['c'] . "</div>" ;

2

You must do the following:

<?php 
    echo isset($_GET['c']) ? "<div class='campo1'>" . $_GET['c'] . "</div>" : ""; 
?> 

or

<?php 
    if(isset($_GET['c'])){
       echo  "<div class='campo1'>" . $_GET['c'] . "</div>"; 
    }
?> 
  • Recalling that the isset does not validate if the variable is empty, only if it exists. So if the parameter via $_GET comes and is empty, isset returns true.

1

There is also a way to hide div by CSS when it is empty.

Just use

<style>
#campo1:empty{
  display:none;
}
</style>

I would just like to draw attention to the care that should be taken when displaying content coming from user data.

Because the code below leaves your code vulnerable to xss injections (cross-site scripting):

<?php 
    echo isset($_GET['c']) ? "<div class='campo1'>" . $_GET['c'] . "</div>" : ""; 
?> 

If this really goes into production (and it’s not just a test, for study purposes), I recommend that you do it as follows

<?php 
  echo isset($_GET['c']) ? "<div class='campo1'>" . htmlentities($_GET['c']) . "</div>" : ""; 
?>

because this way you can prevent someone from entering a javascript in the url and codes in your page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.