You can use parse_url
to check $_SERVER['REQUEST_URI']
Note 1: error:
"Uncaught ReferenceError: $ is not defined at (index): 36 (anonymous) @ (index): 36"
Indicates that jQuery was not loaded on your page, you need to put it before the script you want to run, something like:
<html>
<head>
<script src="pasta/jquery.js"></script>
<script src="pasta/fancybox.js"></script>
</head>
<body>
...
<?php if (<condição>): ?>
<script type="text/javascript">
$(document).ready(function() {
$.fancybox.open({
src : '/assets/images/banner-aviso.png',
type : 'image'
});
});
</script>
<a class="hidden-link pop-up" href="/assets/images/banner-aviso.png"> </a>
<?php endif; ?>
...
</body>
</html>
Note 2: REQUEST_URI
must have the apostrophes (single quotes), because if you do $_SERVER[REQUEST_URI]
PHP will first look for a constant called REQUEST_URI
, which does not exist, then it will issue a notice like this:
Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI'
The
assumed 'REQUEST_URI'
indicates that PHP does not find the constant cast for string, however note that although
$_SERVER[REQUEST_URI]
works, but maybe some additional script generates the constant
REQUEST_URI
with some \ value , then this will fail for sure.
Note also that strpos()
can return 0
or false
, in case of the @DVD script, not even if you are accessing a page with the similar name foobarhome.php
strpos
will also enter in IF
, then the ideal to avoid problems is to use parse_url
or else use preg_match
, follow examples:
Using parse_url
The parse_url($url, PHP_URL_PATH)
will only extract the path
, if it is in the home the value /home
<?php if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === '/home'): ?>
<script type="text/javascript">
$(document).ready(function() {
$.fancybox.open({
src : '/assets/images/banner-aviso.png',
type : 'image'
});
});
</script>
<a class="hidden-link pop-up" href="/assets/images/banner-aviso.png"> </a>
<?php endif; ?>
If the home you refer to is index.php, then do so:
<?php if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === '/'): ?>
...
If it is a range of pages, you can use an array:
Note: ltrim
takes the start bar
<?php
$pathAtual = ltrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$permitidos = array( 'home', 'contato', 'admin/foo' ); //Adicione as páginas permitidas aqui
?>
<?php if (in_array($pathAtual, $permitidos)): ?>
...
With preg_match (regex)
In this case I've used regex (regular expressions), with it you can create a range of pages within the regex, for example this regex will check if it is the home or index #/(index|home)$#
, example:
<?php if (preg_match('#/(index|home)$#', $_SERVER['REQUEST_URI'])): ?>
<script type="text/javascript">
$(document).ready(function() {
$.fancybox.open({
src : '/assets/images/banner-aviso.png',
type : 'image'
});
});
</script>
<a class="hidden-link pop-up" href="/assets/images/banner-aviso.png"> </a>
<?php endif; ?>