I need some help I have written the following preg_replace. The idea of the script is to get the language name from the domain name:
If I have a
http://www.domainname.com/nl/this/is/a/test/index.asp
I would like to strip the (nl) part from the domain name. The nl is a variable for languages so it could be:
http://www.domainname.com/nl/this/is/a/test/index.asp
http://www.domainname.com/fr/this/is/a/test/index.asp
http://www.domainname.com/de/this/is/a/test/index.asp
The above domains represents language directories...
<?php
$sitename = "http://" .$_SERVER["SERVER_NAME"];
$pagename = $_SERVER["PHP_SELF"]."this/is/a/test";
$language = "\/..\/";
$language1 = preg_replace("/$language/", "$1", "$pagename");
?>
I am only using the script where I know there will be a language directory.
The script above also removes the this/a/test/ the (is) from the url. (which tells me the script is greedy.
What would be the best method to grab the language from the url?
Can someone please provide me with some guidence.
Thanks
This is the script I came up using the advice below:
<?php
$mainurl = "http://" .$_SERVER["SERVER_NAME"];
$fullpagename = $_SERVER["PHP_SELF"];
$mainlanguage = preg_replace('%^/(\w+?)/.*$%', '$1', $_SERVER["REQUEST_URI"]);
$strippedpagename = preg_replace("/$mainlanguage\//", '$1', $_SERVER["REQUEST_URI"]);
?>
<?php echo "Full URL: ".$mainurl ?><br>
<?php echo "Full Page Name: ".$fullpagename ?><br>
<?php echo "Language: ".$mainlanguage ?><br>
<?php echo "Page Name No Language: ".$strippedpagename ?><br>
Exactly what I needed, or is there a more elegant way?
Maybe something like this:
$language = preg_replace('%^/(\w+?)/.*$%', '$1', $_SERVER["REQUEST_URI"])
Maybe more simple:
$language = reset( explode('/', substr($_SERVER["REQUEST_URI"],1) ) );
No need of regexp here.
Related
I've got a question, I'm using this code:
<?php
$actual_link = $_SERVER['REQUEST_URI']
?>
This shows me the current link e.g.: www.domain.com/en/page1.
But it should output only domain and tld: www.domain.com/
Thanks
With $_SERVER['SERVER_NAME'] you will get the domain.
With $_SERVER['REQUEST_URI'] you will get the folder tree structure on the point where you are.
Example URL: 127.0.0.1/PHP_learning/jumpletter/
So in your case you write:
<?php
$actual_link = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
Now you can cut your URL with the PHP substr() Function.
Here is an example:
<?php
$actual_link = substr($actual_link, 0, 15);
?>
Your new $actual_link = 127.0.0.1/PHP_l
So all in one here is your finished code:
<?php
$actual_link = $_SERVER['SERVER_NAME'].substr($_SERVER['REQUEST_URI'], 0, 3);
?>
In your examples is the finished resault: domain.com/en
Should be worke fine. Enjoy ;)
I am new to PHP, still learning, but I need help with this:
If I define a constant like this:
<?php
$area = "New York";
?>
Then I will create a file New-York.php.
I would like to use the constant "New York" inside this line:
<?php include $_SERVER["DOCUMENT_ROOT"] . "/includes/New-York.php"; ?>
I will have a lot of different cities and I would like to avoid having to change the includes link for every page, but rather only define the constant $area.
Am I making sense and can that be done?
Thanking you all in advance.
You could use str_replace() to transform the space " " to "-". Then, concatenate into your include path:
<?php
$area = "New York";
?>
<?php include $_SERVER["DOCUMENT_ROOT"] . "/includes/".str_replace(' ','-',$area).".php"; ?>
I have a string stored in a variable in my php code, something like this:
<?php
$string = "
<?php $var = 'John'; ?>
<p>My name is <?php echo $var; ?></p>
";
?>
Then, when using the $string variable somewhere else, I want the code inside to be run properly as it should. The PHP code should run properly, also the HTML code should run properly. So, when echoing the $string, I will get My name is John wrapped in a <p> tag.
You don't want to do this. If you still insist, you should check eval aka evil function. First thing to know, you must not pass opening <?php tag in string, second you need to use single quotes for php script You want to evaluate (variables in single quotes are not evaluated), so your script should look something like:
<?php
$string = '
<?php $var = "John"; ?>
<p>My name is <?php echo $var; ?></p>
';
// Replace first opening <?php in string
$string = preg_replace('/<\?php/', '', $string, 1);
eval($string);
However, this is considered very high security risk.
So if I'm right, you have the $var = 'John'; stored in a different place.
Like this:
<?php $var = 'John'; ?>
And then on a different place, you want to create a variable named $String ?
I assume that you mean this, so I would suggest using the following:
<?php
$String = "<p>My name is ".$var." </p>";
echo $String;
?>
You should define $var outside the $string variable, like this
<?php
$var="John";
$string = "<p>My name is $var</p>";
?>
Or you can use . to concatenate the string
<?php
$var="John";
$string = "<p>My name is ".$var."</p>";
?>
Both codes will return the same string, so now when doing
<?php
echo $string;
?>
You will get <p>My name is John</p>
The title says it all: I want the page to determine the title, but the title is being set before the page is being read (I think). Is there a way to accomplish this, or am I doomed to include the header on each individual page?
Here's what I have:
php.ini:
auto_prepend_file = "header.php"
header.php:
<?php
if (isset($title) == false) {
$title = "foobar";
}
$title = "My Site : " . $title;
?>
<title><?php echo($title) ?></title>
index.php
<?php
$title = "Home"; // ideally this would make the title "My Site : Home"
?>
Instead of using auto_prepend_file, I would just use:
include 'header.php';
An important reason why I wouldn't use auto_prepend_file is, if you move to another server, you'll have to remember to edit the php.ini. If you just include the file, you can move your code to any server.
Also, just like Fred-ii- said, I wouldn't use parenthesis. Also, you are missing a semi-colon after the echo.
To take that a step further, I would create a file called something like $config.php or $vars.php. Include that before everything and have it define all your global variables and constants.
I would check this out: http://php.about.com/od/tutorials/ht/template_site.htm
This is not an ideal answer, but I could use CGI variables to get the name of the page, then turn that into a title.
function get_title($page){
$title = str_replace("/", "", $page);
$title = str_replace("_", " ", $title);
$title = str_replace(".php", "", $title);
$title = ucfirst($title);
if($title = "Index"){
$title = "Home";
} elseif ($title == "") {
$title = 'Foobar';
}
return $title;
}
$title = get_title($_SERVER["PHP_SELF"]);
$title = 'My Site: ' . $title;
As a follow-up to my original comment, I'm posting this as an answer because while it doesn't specifically solve the problem, it addresses the underlying cause.
Disclaimer: The code below has many problems, especially security, it's not meant to be copied directly but only explains the concept.
What you need to do is have a container file that includes your headers and whatever else, and each PHP file is included from there. For example, name your container index.php, and have the following in it:
<?php
include 'header.php';
if ($_GET['page'])
include $_GET['page'].'.php';
include 'footer.php';
?>
Then each PHP page you have will be wrapped in the index.php file, and you can add whatever you want in the header file which will be included in all of your files. That way you don't have to include anything in the individual page files.
The client will access your pages with a query string, such as: index.php?page=test
Again, for security reasons you will still want to include basic checks in each individual file, but technically this can be avoided in you plan for this. You definitely won't need to include huge headers in each file, like MySQL connections etc. Also for security you should have stringent checks on your $_GET variables to make sure that only the pages you want can be included.
I'd define a writeTitle (or similar) function in the header.php file which you're auto_prepending:
header.php
<?php
function writeTitle($title = 'foobar') {
$title = "My Site : " . $title;
return '<title>' . $title . </title>';
}
And then you can just call the function from your page scripts instead of setting a variable:
index.php
<?php
echo writeTitle('Home');
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')){