php: if current url contains "/demo" do something

13,662

Solution 1

Just use,

if(basename($_SERVER['REQUEST_URI']) == 'demo'){
    // Do something
}

Solution 2

<?php
    if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
        // Do something
    } else {
        // Do something else
    }
?>
Share:
13,662
agis
Author by

agis

Updated on June 04, 2022

Comments

  • agis
    agis almost 2 years

    I want to check if my current URL contains "/demo" at the end of the url, for example mysite.com/test/somelink/demo to do something. Here is my attempt :

    $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    if($host == 'mysite.com/test/somelink/demo') 
     {
    // Do something
    }
    else
    {
    // Do something
    }
    

    This seems to work fine, but the problem is that /somelink needs to by dynamic.

    Any suggestion on how can I do this ?

    Thank you !

    Edit:

    <?php
    /* An abstract class for providing form types */
    abstract class ECF_Field_Type {
        private static $types = array();
        protected $name;
    
        /* Constructor */
        public function __construct() {
            self::register_type( $this->name, $this );
        }
    
    if(basename($_SERVER['REQUEST_URI']) == 'stats'){
    echo "Hello World";
    }
    
        /* Display form field */
    
        public abstract function form_field( $name, $field );
    
        /* Display the field's content */
        public function display_field( $id, $name, $value ) {
            return "<span class='ecf-field ecf-field-$id'>"
                . "<strong class='ecf-question'>$name:</strong>"
                . " <span class='ecf-answer'>$value</span></span>\n";
        }
    
    
        /* Display field plain text suitable for email display */
        public function display_plaintext_field( $name, $value ) {
            return "$name: $value";
        }
    
        /* Get the description */
        abstract public function get_description();
    }
    ?>
    
  • agis
    agis over 10 years
    Just tried but I'm getting a weird syntax error : Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in
  • agis
    agis over 10 years
    Just tried it and Im getting a weird syntax error: Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in
  • agis
    agis over 10 years
    Yes, I think is something wrong with my code but I don't understand why, I've edited my question with what I've tried please take a look...
  • Rikesh
    Rikesh over 10 years
    So now what is the issue ?
  • agis
    agis over 10 years
    Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in
  • agis
    agis over 10 years
    And if put it outside the abstract class ECF_Field_Type { is working fine
  • agis
    agis over 10 years
    I think I will ask another question for this issue because is not related with what I was asking for. Thank you !