For example I have a website that points to a page like this:
http://www.mysite.com/folder/file
How can I get determine /folder so that I can go further an quote an if statement like
if /folder then echo something
Why do I need this?
I am trying to tell facebook which image to pick from a page. Actually I have a pretty simple page structure and the image that facebook should take is always at first but somehow it does choose another one from time to time. I guess because the other images are loaded faster. And the old way to rel="img_src" doesn't seem to work anymore as that I could just add it to the wanted image.
So well of course I use the open graph protocol to tell facebook which Image it should use.
I am working with a cms were I can output the path of the image depending on the id the image has. I have two different id's for the different kind of pages living in two different folders.
This leads to:
if index --> echo meta og for index img
else if /folderone (with id1) --> echo meta og for id1
else if /foldertwo (with id2) --> echo meta og for id2
This is why I need to know the foldername.
Now with the answer I have following setup, just that you know:
<?php $folder = dirname($_SERVER['SCRIPT_NAME']); ?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/") echo "<meta property='og:image' content='http://www.mysite.com/img/img.jpg'/>" ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderOne") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id1}'/> " ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderTwo") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id2}'/> " ;?>
parse_url &
explode
$path = parse_url($url, PHP_URL_PATH);
gives you
/folder/file
then you can explode() to separate the path values and check the first one to see if it is 'folder'
Example here: http://tehplayground.com/#7TIKAwp6J
Example code:
$url = "http://www.mysite.com/folder/file";
$path = parse_url($url, PHP_URL_PATH);
$arr = explode("/",$path);
echo $arr[1]; // leading slash makes [0] ""
outputs
folder
$script = $_SERVER['SCRIPT_NAME'];
echo dirname($script);
Possibly use "get current working directory" function getcwd()?
Explode it by directory separator.
Then grab the last element like this:
$var = getcwd();
$var = explode('\\', $var); // your OS might use '/' instead
$var = end($var);
I suppose this assumes you're not using some kind of MVC framework that uses routing.
I hope that helps!
I think this is nicer than exploding the string:
function getCurrentDirectory(){
$curDirPath = getcwd();
return substr($curDirPath, strrpos($curDirPath, '/') + 1);
}
getcwd() gives you the current directory's path, and then you can truncate it starting right after the last occurrence of the / in its file path.
$dir_list = explode('/', dirname($_SERVER['SCRIPT_FILENAME']));
$this_folder = $dir_list[count($dir_list)-1];
...
if ($this_folder) == "folderOne") echo "...."
...
if(dirname('yoursite/folder')){
Related
I would like to obtain on my localhost (somehow dynamically) the following URLs:
localhost/demo1/
localhost/demo2/
localhost/demo3/
...
and so on (more than 30).
I have an index.php file which I would like to use as a template for each of the above paths.
When I access localhost/demoX/ I would like to load the index.php template only with some few changes inside, based on the demoX name.
Can you tell me how to obtain this structure?
Thanks
Use PHP
1) Parse site URL (hint for url "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']) to get variable you need (I think you will use RegEx for that)
2) $template = require_once('index.php');
3) Process all variables used in index.php
4) echo $template; exit();
NOT TESTED PSEUDO CODE
$url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$part = preg_match("/demo(\d+)/", $url)[0];
$partName = "File name is demo-{$part}";
$template = require_once('index.php');
echo $template;
exit();
[index.php]
<?php
echo $partName;
Still learning php as I go so this might just be something I haven't gotten to yet but it's the next roadblock in building my personal site. I have a basic understanding of includes such as linking:
<a href="art.php?id=image id&name=This is my title&menu=side-menu-portfolio">
to pull my includes but I've come to a small problem in that my generic art-gallery page needs to switch between a 'portfolio' header and an 'artwork' header. So I figured I could either build "art-gallery.php" AND "port-gallery.php" and go back and relink everything or just make it so that when you call the link like the above code I just specify which header goes with it. Unfortunately this would also require going back and changing every link. But I noticed that I did state:
...&menu=side-menu-portfolio...
and the pages are already calling side-menu-artwork or side-menu-portfolio so if I could just call in menu and cast aside the 'side-menu-" portion then it would just use artwork or portfolio and call the right header. Unfortunately this is where my limited knowledge of php and syntax come in. I have tried to produce the following code based on my php and js understanding:
<?php include("headlines/headline-" . $_GET[menu - "side-menu-" ] . ".php"); ?>
but I don't know if my syntax is just wrong or if what I'm trying to do is impossible to begin with. Note that when I try this I get
Function Include error of "Warning: include(headlines/headline-.php)"
so it looks like everything else is reading correctly, I just don't know if or how I can extract the word I want from the rest of the menu name.
Should be, Assumed your included file name is headline-side-menu-portfolio.php
<?php
$filename = str_replace("side-menu-", "", $_GET['menu']); // headline-portfolio
include("headlines/headline-" . $filename . ".php"); // headline-portfolio.php
?>
Something like this :
<?php include("headlines/headline-" . $_GET["menu"].".php"); ?>
<!--gives include("headlines/headline-side-menu-portfolio.php")-->
where
$_GET["menu"] = 'side-menu-portfolio'
Try this:
<?php include("headlines/headline-" . $_GET['menu'] . ".php"); ?>
Your code is wrong.
Instead of
<?php include("headlines/headline-" . $_GET[menu - "side-menu-" ] . ".php"); ?>
try
<?php include("headlines/headline-" . $_GET['menu'] . ".php"); ?>
You should check if the file exists before you try including it.
if (file_exists($filesrc)) { ... }
Better yet don't let the user change the menu through a $_GET variable. Instead link to a specific page or pass a variable then decide what menu to get. Like
switch ($_GET['menu']) {
case 'side-menu':
include("headlines/headline-side-menu.php");
break;
}
Just use
$_GET['menu']
, the "side-menu-" part is already in the content of your variable passed as param.
You propably want to do an if .... else so to include one header or another based on the $_GET variable menu.
So something like this will do this:
if($_GET['menu'] == 'side-menu-portfolio') {
include 'headliens/side-menu-portfolio.php';
} elseif($_GET['menu'] == 'side-menu-other') {
include 'headliens/side-menu-other.php';
}
okay....your are almost there....just quotes missing from include syntax...it should be
include("headlines/headline-.php"); /* notice the quotes*/
so it should be
<?php include("headlines/headline-" .$_GET['menu'].".php"); ?>
where $_GET['menu'] should be in the url, like:
art.php?id=image id&name=This-is-my-title&menu=side-menu-portfolio
so what's happening her ??
Upon execution of the line :
<?php include("headlines/headline-" .$_GET['menu'].".php"); ?>
$_GET is fetched from the url and replaced in the header tag, so now the header tag becomes :
<?php include("headlines/headline-"."side-menu-portfolio".".php"); ?> => <?php include("headlines/headline-side-menu-portfolio.php"); ?>
Also. may i suggest that for :
<a href="art.php?id=image id&name=This is my title&menu=side-menu-portfolio">
don't use space in the url, either replace it by - or _
I have a piece of php that if a specified folder has a file in, it will display the filename, date created and present a download button, if the folder is empty it will show nothing. This works very well but if I have more than one file in the folder it bunches all the filenames together - what I want is the separate information displayed for every file.
To help you understand the problem here is an image showing the problem and the code. I got very far on my own but its way above my head, I just cant see a simple way to correct the problem. The code may look very awkward and odd as I'm totally new at this but it looks visually right on the browser. I would really appreciate any help thank you.
Here is an image of the problem: http://i46.tinypic.com/m79cvs.png
<?php if (!empty($thelist)) { ?>
<p class="style12"><u>Fix</u></p>
<p class="style12"><?=$thelist?><?php echo " - " ?> <?php $filename = '../../customers/client1/client1.fix.exe';
if (file_exists($filename)) {
echo "" . date ("m/d/Y", filemtime($filename));
}
?> <?php echo " - <a href='download.php?f=client1/client1.fix.exe'><b>Download</b></a> <a href='download.php?f=client1/client1.fix.exe'>
<img src='../css/images/dlico.png' alt='download' width='35' height='32' align='absmiddle' /></a>" ?>
</p>
<?php } ?>
The list ($thelist) contains your files, yes?
You are not working on the $thelist, but on the $filename which is a hardcoded string.
Why? Currently you are outputting <?=$thelist?> and it looks like concatenated string from filenames. I would suggest that $thelist should be something like an array of your files. Then you could iterate over the files and output html dynamically for each entry.
<?php
// define your directory here
$directory = xy;
// fetches all executable files in that directory and loop over each
foreach(glob($directory.'/*.exe') as $file) {
// output each name and mtime
echo $file . '-' . date ("m/d/Y", filemtime($file));
// or you might also build links dynamically
// $directory needs to be added here
echo ''.$file.' - Size: '.filesize($file).'';
}
?>
I am a total PHP novice and am trying to write what I think is a pretty simple script. This is the code I have so far:
HTML / PHP
<?php
$hits = file_get_contents('hits.txt');
++$hits;
file_put_contents('hits.txt', $hits);
echo $hits;
$url = $_GET['w'];
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>
The result is a page with an iframe and a hit counter.
The problem with this script is that if the variable $url changes, the hit counter does not. My goal would be that if I visited http://www.website.com/index.php?w=blue.html I would get a different counter than if I visited http://www.website.com/index.php?w=yellow.html.
EDIT: I should add that this script is designed to accept any URL. I realize this complicates things significantly. My ultimate goal would be that if the counter didn't already exist for that particular URL, it would be generated on the fly.
Your current code saves the hit points for every page to the same file as a simple string.
You have a number of options. Here's one that would work if you prefer to stick with text files instead of databases.
You could take the URL in, hash it, and save the counter for that page in a hash-named text file.
Something like
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
and then later you could echo out the hits under that or pull the hits in on another script and echo like that.
If you need it to create new ones on the fly, you could add something like
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}
NOTE
This could end up creating a ton of tiny text files, though. So be aware. If you are worried about that, you would really need to look into a database or read in a text file line by line to find the same hash.
TO IMPLEMENT
Replace the top part of your code within the <?php ?> with the following:
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}else{
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
}
This will take the page name in, hash it, check to see if /hit_counters/THEHASH.txt exists, and create it if not or add +1 to it otherwise. A hash is sort of like encryption, but not really. It will change your $_get['w'] into a longer random-looking string.
You're writing the same hits.txt file regardless of what $_GET['w'] is set to. Try putting the hits.txt file in a folder like this:
<?php
$url = $_GET['w'];
$dir = str_replace(".html", "", $url);
$hits = file_get_contents($dir.'/hits.txt');
++$hits;
file_put_contents($dir.'/hits.txt', $hits);
echo $hits;
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>
Having an issue here where the
$_SERVER['REQUEST_URI']
is spitting out:
/dev/nava2/store/index.php?route=product/product&product_id=48
the actual URL is /dev/nava2/store/index.php?route=product/product&product_id=48
obviously, the difference being the & on the top vs. the & on the bottom
full code looks like this:
$currentpage = $_SERVER['REQUEST_URI'];
$classic = "/dev/nava2/store/index.php?route=product/product&product_id=48";
if ($currentpage == $classic)
{ $classicclass = "current";
}
else { echo "";}
Any suggestions?
& is the html entity corresponding to &. You can obtain to original string back with html_entity_decode :
$original = html_entity_decode($_SERVER['REQUEST_URI']);
You can use html_entity_decode() to get the actual url but the top one should work. I dont think you need to change anything. You could also use str_replace or preg_replace if you really need to change some parts of your uri.
echo html_entity_decode($_SERVER['REQUEST_URI']);