Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
質問
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();
}
?>
解決
Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
他のヒント
<?php
if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
// Do something
} else {
// Do something else
}
?>
This post has PHP code for simple startsWidth() and endsWith() functions in PHP that you could use. Your code would end up looking like:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}
But one thing you might want to do in addition to that is convert $host to lowercase so the case of the URL wouldn't matter. EDIT: That would end up looking like this:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))
you can use strpos
$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo'))
{
// Do something
echo "in Demo";
}
else
{
// Do something
echo "not in Demo";
}
$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }