Jump to content

Recommended Posts

Hi, I am trying to create an if/else statement. I need to execute a piece of javascript code if the IP address is not a particular IP.  I am totally new to PHP, so I'm clueless as to what to do.

 

Here is the code I am trying to get working...

 

=========================

 

<?php

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {

      $ip=$_SERVER['HTTP_CLIENT_IP'];

    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

    } else {

      $ip=$_SERVER['REMOTE_ADDR'];

} endifelse; ?>

 

<?php

if ($ip == "255.255.255.255") {

echo "Your IP Is Blocked!";

} else {

<script type="text/javascript">

<!--

my javascript code

-->

</script>

 

} endifelse; ?>

 

=========================

 

As you can see, I tried pasting the JS code into the else clause (in red), but of course it didn't work.

 

Can someone help?

 

Thanks!

 

 

Link to comment
https://forums.phpfreaks.com/topic/170142-solved-php-ifelse-question/
Share on other sites

You have to close the PHP tags to do what you want. Also, you don't need to write "endifelse;" if you have opening and closing brackets.

 

<?php
if ($ip == "255.255.255.255") {
echo "Your IP Is Blocked!";
} else {
?>

<script type="text/javascript">
<!--
my javascript code
-->
</script>
<?php
}  ?>

 

hope that helps!

You have to echo the javascript code as you would echo normal text. PHP is server side and is parsed 100% before the page is sent to the users browser. JS on the other hand is client side code which will be used after the user has received the page from the server. So something like this..

 

if ($ip == "255.255.255.255")
{
   echo 'Your ip is blocked';
}
else
{
echo '<script type="text/javascript">
<!--
my javascript code
-->
</script>';
}

You have to close the PHP tags to do what you want. Also, you don't need to write "endifelse;" if you have opening and closing brackets.

 

<?php
if ($ip == "255.255.255.255") {
echo "Your IP Is Blocked!";
} else {
?>

<script type="text/javascript">
<!--
my javascript code
-->
</script>
<?php
}  ?>

 

hope that helps!

 

 

That did the trick... Thanks!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.