How to write the following in PHP:
IF current page's name is pagex.php
THEN please load these additional CSS rules:
#DIVS { color:#FFF }
IF current page's name is anotherpage.php
THEN please load following CSS rules:
#DIVS { color: #000 }
like this:
<?php
if (basename(__FILE__) == 'pagex.php') {
echo '#DIVS { color:#FFF }';
} else if (basename(__FILE__) == 'anotherpage.php') {
echo '#DIVS { color:#000 }';
}
?>
PHP has some "magic constants" that you can inspect to get this information. Take a look at the ` __FILE__ constant.
The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, FILE always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
So you can take this __FILE__ variable and execute the basename() function on it to get the file name. The basename() function returns the trailing name component of a path. Then you simply do a switch case to match the desired value -
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '<link .... src="some_stylesheet_file.css" />';
break;
case 'anotherpage.php':
echo '<link .... src="another_stylesheet_file.css" />';
break;
}
Your additional CSS rules can sit within those separate files.
Alternatively, if you don't want to split your css into multiple files, you can echo those specific rules into your page's head element like this -
echo '<style type="text/css">';
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '#DIVS { color:#FFF }';
break;
case 'anotherpage.php':
echo '#DIVS { color: #000 }';
break;
}
echo '</style>';
References -
basename()
php magic constants
You can just add in HTML head part one PHP if...else to load additional stylesheet according to page name.
<head>
<?php
if (basename(__FILE__) == 'one.php')
echo '<link .... src="style1.css" />';
elseif (basename(__FILE__) == 'two.php')
echo '<link ..... src="style2.css" />';
?>
</head>
you can use is_page() function of wordpress in a customize manner as it is working on regular php.code is:
<?php
$baseurl = 'http://www.example.com'; //set the base url of the site
$mypage1 = $baseurl."/pagex.php"; //add the rest of the url
$mypage2 = $baseurl."/anotherpage.php"; //add the rest of the url
$currentPage = $baseurl.$_SERVER['REQUEST_URI'];// this gets the current page url
if($currentPage==$mypage1) {
//do something with you style or whatever..
}
else if($currentPage==$mypage2)
{
//do something with you style or whatever..
}
?>
you have to change it according to your needs. i think it will help you.
happy coding!
Related
Im setting up a xampp php website with auto creating css for site (If site named xyz.php/html is created, then a css is created too). Unfortunatelly css doesn't want to include in website using php echo's and html tags. No error.
In style.php:
$arr = explode("/",$_SERVER['PHP_SELF']);
$style = "";
foreach ($arr as $key){
if(strpos($key, ".php")){
$style = str_replace(".php", "style.css", $key);
}
}
if($fp = fopen($_SERVER['DOCUMENT_ROOT']."/TestPHP/".$addr,"wb+")){
fwrite($fp,"body{background-color:#666;}");
fclose($fp);
}
echo $addr = "lib/require/styles/".$style;
echo '<link href="'.$addr.'" rel="stylesheet">';
In index.php:
require_once 'lib/require/php/styles.php';
That's because the only HTML (as i can see in your code) doesn't have anything else than the style, no head, no body... Why don't you directly paste the HTML inside the file instead of making PHP echo it?
I would like to make navbar, in which background colour of one element would change if user would be on that subpage.
Code for checking if url contains chosen string:
<?php
$url = $_SERVER['REQUEST_URI'];
//echo ($url);
if (strpos($url, 'index.php') == true) {
//echo 'Current page contains index.php';
$atm = "#2275A8";
} else {
$atm = "#00427A";
}
?>
This is part from same file saved as .php file
<?php
header("Content-type: text/css");
?>
.ico1 {
background: <?php echo $atm; ?>;
}
If i put my "ckecking part" od code on index, it is working nicely; returning true or false, but for some reason it's not passing parameter into style file.
So now i put "checking part" into style file but, no mater on which subpage i am, its returning same result (always true even if 'index' is not part of url).
Any idea on how to deal with this? :)
Define classes with style you want in style.css file and change the class of element you want to change style of dynamically in php file like in the example below.
style.css
.ico1 {
background: color1;
}
.ico2 {
background: color2;
}
index.php (or the file containing navbar you want to change)
<?php
$url = $_SERVER['REQUEST_URI'];
if (strpos($url, 'index.php') == true) {
//echo 'Current page contains index.php';
$atm = "ico1";
} else {
$atm = "ico2";
}
?>
...
<div class="<?php echo $atm;?>"> // navbar
Why don't you have the two css classes and make a conditional in the element you want the class be applied:
CSS
.ico1-0 {
background: #2275A8;
}
.ico1-1 {
background: #00427A;
}
PHP
[...]
<div class="<?php echo (strpos($url, 'index.php') === true) ? 'ico1-0' : 'ico1-1'; ?>"></div>
[...]
strpos will never return true. Either it will return false or it return integer. So try like below.
if (strpos($url, 'index.php') !== false)
within my page.tpl.php I have the following code which makes some trouble in the backend. Therefore I want to solve it the better way, with preprocess functions.
if (!path_is_admin(current_path())) {
$pathArray = explode('/', current_path());
if (!empty($pathArray)) {
$path_to_node = url("node/".$pathArray[1]);
$img = '<img src="'.$theme_path.'/images/default.png" alt="Default" />';
if (!empty($path_to_node)) {
$menuChildArray = explode('/', $path_to_node);
if (!empty($menuChildArray[2])) {
$menuParent = $menuChildArray[2];
switch($menuParent) {
case "one":
$img = '<img src="'.$theme_path.'/images/one.png" alt="Pic tne!" />';
break;
case "two":
default:
$img = '<img src="'.$theme_path.'/images/two.png" alt="Pic two!" />';
break;
}
}
print $img;
}
}
}
But how can I realize this? To try it, I did the following:
I added a template.php to the Theme folder and added:
function set2015_preprocess_page(&$variables) {
$variables['set2015_pics'] = 'test';
}
Within page.tpl.php I then did:
<?php
print $set2015_pics;
But nothing is getting printed... What am I doing wrong here?
Thank you!
Presuming that set2015 is the name of your theme everything looks good so clearing cache with drush or at config/development/performance should make the variable show up. If set2015 is not the name of your theme then rename the function set2015_preprocess_page to YOURTHEME_preprocess_page
Debug it. Add some echo "I'm here"; above first if, then bellow it, then after second if and so on...to see what is executed and what's not. Try localizing the problem.
i have a large number of files with several id's in each file. For example file1.php contains a number of paragraphs, each paragraph has a unique id. (id="1",id="2",id="3" etc...) I would like the ability to create a link to a page (page A.php) and pass the location of one of these id's in the url of the link to display in a php include on page A.php The result that i'm looking for is to have the entire file (file1.php) show up inside of page A.php with the specific id that is passed in the url being highlighted. Is this possible? or do I need to use Java Script and an iframe?
Here is what I ended up with:
The url: http://mydomain/thispage.php?xul=http://mydomain.com/folder1/folder2/file.php&id=Abc150:176
The code:
Stylesheet .vrsehilite{styling}
<script type="text/javascript">var x = <?php echo json_encode($_GET["id"]); ?>;</script>
<?php
$invdmn = "<h2>Error: Invalid Domain</h2>";
$filnf = "<h2>Error: File Not Found</h2>";
$pthinv = "<h2>Error: The Path is invalid</h2>";
$idinv = "<h2>Error: The ID is invalid</h2>";
$oops = "<br/><h2>Oops! Something went wrong.<br/><br/>Please click the back button or use the menu to go to a new page.</h2>";
$testdomain = substr_compare ($_GET['xul'],"http://mydomain.com",0,20,FALSE); //make sure the domain name is correct
if ($testdomain == 0) {
$flurl = $_GET['xul'];
} else {
echo $invdmn . " " . $oops;
}
$flurl_headers = #get_headers ($flurl);
if ($flurl_headers[0] == 'HTTP/1.1 404 Not Found') {
echo $filnf . " " . $oops; //Make sure the file exist
} else {
$surl = str_replace (".com/",".com/s/",$flurl);
} //add some characters to url at point to explode
list($url1, $path) = explode ("/s/",$surl); //explode into array of 2 [0]url to domain [1] path
$testpath = substr_compare ($path,"file1/file2/",0,10,FALSE); //make sure the path is correct
if ($testpath == "0") {
$aid = preg_match ("/^[A-Z][a-z]{2}(?:[1-9][0-9]?|1[0-4][0-9]|150):(?:[1-9][0-9]?|1[0-6][0-9]|17[0-6])$/", $_GET['id']);
} else { //make sure the id is valid
echo $pthinv . " " . $oops;
}
if ($aid == 1) {
include($path);
echo "<script type='text/javascript'>";
echo "document.getElementById(x).className = 'vrsehilite';";
echo "document.getElementById(x).scrollIntoView();";
echo "window.scrollBy(0,-100);";
echo "</script>";
} else {
echo $idinv . " " . $oops;
}
?>
Never ever include arbitrary files submitted by the user. Instead, you should only include files from a pre-defined set of your choice. Perhaps something like this:
PHP
$files = array ('file1.php', 'file2.php', 'view.php', 'edit.php');
$id = (int)$_GET['id'];
if (isset ($files[$id])) {
include $files[$id];
} else {
/* Error */
}
Or you could use a regular expression to accept only certain filenames, in this case 1 or more lower case letters followed by 0 or more digits.
$m = array ();
if ( preg_match ('#^http://domain.example/folder1/folder2/([a-z]+[0-9]*\\.php)$#', $m)
&& file_exists ($m[1])) {
include $m[1];
} else {
/* Page not found */
}
You may want to check the return value of include. You may also want to move the folders into the subpattern (...) or use regular expressions for the folder names.
If all you need is to highlight a certain paragraph in a page, you should add a URL fragment that poins to the paragraph's id, and add CSS to style it. Eg:
URL
http://domain.example?id=1#p1
HTML
<p id=p1>This is the target paragraph.
CSS
p:target { /* Style the targeted <p> element */ }
I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).