how can I dected if URL has variable?

Hello guys,

I have this code in my php file:

	$parc = $_GET['cod']; 	

Open in new window

the cod is a variable that comes from my URL, like:

but, sometimes the link doesn't have the variable, then I am getting an error:

Undefined index: cod

is there any way to prevent if URL came with variable or not?

Who is Participating?

Improve company productivity with a Business Account.Sign Up

Ray PaseurConnect With a Mentor Commented:
$cod = !empty($_GET['cod']) ? $_GET['cod'] : FALSE;
if ($cod) { /* YOU HAVE A VARIABLE IN THE URL */}

Open in new window

If you're new to PHP and want to learn the language, this article can help you get started.  Just skip over the parts you already know from other programming languages or computer science courses.
ste5anSenior DeveloperCommented:
When it is a mandatory parameter, then use a redirect. Depending on your stack, this should be placed at the web server level, if possible.
hidrauAuthor Commented:
Hello Ray,

I had found something like this:

if isset($_GET['cod']) {
		$parc = 'VD001'
	} else {
		$parc = $_GET['cod']

Open in new window

What do you think about?

Thanks for the link
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Ray PaseurConnect With a Mentor Commented:
That looks a little bit backwards to me.  As I understand the intended logic, the external variable should be the controlling factor, otherwise a default value will be used.

The Ternary operator is useful for things like this.  This page is long, but it's required reading for anyone who writes PHP code.

Here is how I might write the expressions
$parc = !empty($_GET['cod']) ? $_GET['cod'] : 'VD001';

Open in new window

Here is the narrative:
1. Inspect $__GET['cod'] with the empty() function.  If that returns FALSE, there is information in $_GET['cod']
2. When empty() returns FALSE, !empty() [said "not-empty"] returns TRUE
3. With !empty() === TRUE, assign the value in $_GET['cod'] to $parc
4. With !empty() === FALSE, assign the literal string 'VD001' to $parc
ste5anSenior DeveloperCommented:
First of all: do you have a working backup? Do you have a test system?

Cause you currently allow SQL injection...

hidrauAuthor Commented:
Thanks a lot
Ray PaseurCommented:
Thanks for the points.  I think ste5an may have a good point about the risks of SQL injection.  This article shows some ways of preventing it.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.