To begin, I'm sorry if the title is misleading. I find it hard to put it into words.
My question is regarding websites that have a lot of pages that are structurally identical, but the content is different.
Take Facebook as an example. Every person's profile is a "/profile.php" of some sort, but depending on whose profile you're viewing, the content is different.
It seems to me like there is one single .php-file for a profile, which loads content based on a profile ID in the database.
So, the question:
Certain types of CMS, like Drupal, do this. You create a node, and it has some content. You create another node of the same type, with different content, but it certainly doesn't create a brand new .php-file on your server for every single node, right? What's the process here? Can I program this using PHP?
I'm very much a beginner at PHP, but I'd very much like to learn how to achieve this practically.
Also, before any sarcastic "just use Drupal" comments arise, keep in mind that I do use that already, but again, I want to see if I can learn how to do this myself.
You can do this either on the server side using PHP or client side using JavaScript:
Server side using PHP:
If you navigate to a url like this: http://example.com/p.php/someParameter, it will actually go to p.php, but the entire uri is available at $_SERVER['REQUEST_URI'], so you can strip ot the someParameter part and serve content dynamically. This would look something like:
<?php
$title = '';
$content = '';
$uri = $_SERVER['REQUEST_URI'];
$slash = strrpos($uri, '/');
$parameter = substr($uri, $slash + 1, strlen($uri) - $slash);
// Update the title and content based on the parameter
?><html>
<body>
<h1><?php echo $title; ?></h1>
<div><?php echo $content; ?></div>
</body>
</html>
Client side using JavaScript
If you are happy to have the # in your path, there are various JS libraries that can make this quite easy as well. I use Knockout and Sammy.js. For a tutorial on how to do that, check out the knockout tutorial.
Related
I'm new to PHP and want to apply a specific class to the title of my page depending on what part of the site the viewer is browsing.
For instance, I want to apply the class "blog" to the if the viewer is at domain.com/blog OR domain.com/blog/post-1 so on and so forth BUT apply the class "pics" if they're viewing domain.com/pics or domain.com/pics/gallery-1 etc etc.
I found something that could be modified to serve my needs using javascript here
but I figured seeing as I'm using PHP already, it'd make more sense to keep this sort of thing server side.
As I say, I'm new to PHP. I've experimented with some regular expressions, but to no avail.
EDIT: Sorry not to be more specific in my first post, I am using wordpress as my CMS - this is my first stackoverflow post, I trust you can forgive me :)
<?php
if (substr($_SERVER['REQUEST_URI'], 0,5)=='/pics') {
$h1class='someclass';
}
The it depends on how you're putting the class in the tag, might be like this
?><h1 class="<?php echo $h1class; ?>">...
Rather than putting a class in based on the page, I would suggest having seperate CSS files for home.css, blog.css, whateverelse.css. Of course, these would be in addition to some sort of default.css or site.css or whatever that would contain the styles used across the site.
You can then build a function/method to create the CSS calls in the HTML header. I usually have a "Page" object that builds the actual HTML page, and a "get_css" method that spits out the CSS calls.
It's hard to get more specific without knowing how you currently build pages.
Here is the solution I ended up crafting. Credit to #m.buettner for pointing me towards explode().
<h1 id="title-text" class="
<?php #returns the category as a class
$url = array();
$url = explode('/', get_permalink());
echo $url[3];
?>
mono in-case-404">
SITE
</h1>
We have a school project with HTML/PHP, and we need to create a web page. The problem is there can only be a index (or a main page), the rest of them are small portions of code in other .html documents.
I need to find a way to create a function (I think...) so when I click on one of the links, this will change the <body id>, the <title>, and will load a different content in a <div> (the small portion of code).
Resuming: there are 5 categories, when clicked, each one of them should change the <body id> attribute, the <title>, and load a different .html page in the <div>. I'm sorry if some of you find this offensively lame, but I really need some help with this.
Until now, this is what i have:
<?php
$id0="" . $id1; //default
$id1="home";
$id2="iso";
$id3="lm";
$id4="par";
$id5="itasir";
$id6="fh";
?>
<body id="<?php echo $id0; ?>">
Where $id1-6 should be the categories, and the id0 would be the counter or a pointer of the page that should be loaded. Ex. When I click on the "Par" link, $id0 would change to "" . $id4; and the body would load the id0 which contains id4 now... i think... That should be it.
Thanks...
A few things to read – learning is awesome, but of course just being given the code sucks.
<?php
$id0="" . $id1; //default
$id1="home";
$id2="iso";
$id3="lm";
$id4="par";
$id5="itasir";
$id6="fh";
?>
Would make much more sense as:
<?php
$id = array();
$id[0]="" . $id[1];
$id[1]="home";
$id[2]="iso";
$id[3]="lm";
$id[4]="par";
$id[5]="itasir";
$id[6]="fh";
?>
That way you can easily use numbers to get the one you need.
You are probably going to use variables in the URL using $_GET.
If the URL is http://www.example.com/index.php?page=1, then $_GET['page'] would be equal to 1.
That lets you write some PHP that does different things based on the URL.
You will then likely use file_get_contents (http://php.net/manual/en/function.file-get-contents.php) to load in the contents of the right file.
Easy!
We have a couple of pages that require special care, jquery-ui will be called from external scripts which are going to "somehow" be added to the head section of an article.
I've attempted with jumi, however it isn't the best choice(including a js in stead of php would render it in html body), the only way I could add a javascript file was by including a php file which would echo a , but as one would imagine, this isn't elegant nor efficient in terms of performance.
Another attempt was, in stead of echoing a script, I've tried using:
<?php
$document = &JFactory::getDocument();
$document->addScript( "path/to/jsfile.js" );
?>
but it didn't work as I've expected, it seems that joomla creates the head section before this php script has the chance of being executed.
I've also gave easy header a go, however, it seems that it will include the files in all articles, which I do not wish since it will have a pretty big impact in terms of bandwidth and possible javascript issues down the road.
I'm farily new to joomla so anything that would provide some flexibility is good as an answer.
If something isn't unclear, please ask, I will try to answer the best I can.
Please note that I'm using joomla 1.7 and php5.
Jumi uses the onAfterRender event (looking at the 2.0.6 plugin) - by this time I think the <head> tag has already been written out, in-fact the whole document is already rendered.
You could try getting the document body and then searching for the closing tag </head> and inserting the script link before it. Something like this:
$myJS = "<script type='text/javascript' src='http://mysever.com/my.js'>"
$content = JResponse::getBody(); // gets the html in it's ready to send to browser form
$hdPos = strpos($content, '</head>');
$hdPos += 7; //move position to include the <head> tag
$bodyLen = strlen($content);
$content = substr($content, 0, $hdPos) . $myJS . substr($content, $hdPos, $bodyLen);
JResponse::setBody($content);
NB: This is untested and I don't use Jumi these days but it should be close.
You didn't have to go through all this!
Go to: extensions -> template manager -> templates tab (its on "styles" by default) -> go to your template and click on "edit HTML". You'll be able to add your code directly in the header, and it will be loaded in all the pages.
A bit more elegant way is to define a function that does what you want in the header - and call it from the body of the specific article you want.
I am creating a website for products. I am wondering: is it better to use a single dynamic page using PHP, or generate an HTML page for every product, updating the pages from a php template file in a cron job? Most of the material on the page (eg. basic product information) will not change over time , but other parts of the page will be generated from database lookups (inventory, reviews, etc.)
I have heard some people arguing that it is better to have static url's (eg. category/product1.html) instead of dynamic ones (eg. products.php?id=1234) for SEO purposes. The problem I found with the former method is that it seems inconvenient to do database lookups from an HTML page. The way I implemented it was using javascript->php:
<script type="text/javascript" src="http://localhost/inv_lookup.php?UPC=<?php echo $UPC; ?>"></script>
But then in the PHP file, you have to print javascript-formatted text:
echo "document.write(\"" . $field . " : <b>" . $row[$i] . "</b> <br/> \")";
This kind of DB lookup seems sloppy to me. Any suggestions?
There's no reason you can't do it as a single .php file. With the appropriate mod_rewrite rules, you can dynamically remap a example.com/products/1234 into example.com/product.php?id=1234 URL internally.
And if you really hate exposing PHP, you can always configure the web server to treat .html files as PHP scripts (AddHandler php5-script .html).
As for printing "javascript-formatted text", it's easier to use JSON to do "formatting" for you:
<?php
$product = array('name' => 'Deluxe Widget', 'id' => 1234);
?>
<script type="text/javascript">
var product = <?php echo json_encode($product) ?>;
document.write(product.name + ': <b>' + product.id + '</b><br />');
</script>
1) Don't update static html pages with cron and php. thats just crazy talk.
2) Use heredoc syntax if you want cleaner variable interpolation:
echo <<<EOF
this is a {$row['0']} and a "$varable" for you. oh yeah don't forget the '
EOF;
Suggestions:
Indeed storing & serving a page as plain HTML is very resource effective.
Ideally, there should be no part in the URL showing any language or implementation (no .asp, no .php, no .cgi, no .html). That way, you can switch at will, and every part of your URL is to the point for the resource you are viewing. Look into apache's mod_rewrite and the like.
As you noticed, some parts are more volatile then others, so storing content 'parts' (main navigation, product description, reviews) etc. separately is advisable.
Cron jobs are most likely not going to cut it. When someone alters a price in the backend, the frontend should show that as soon as possible. Creating hooks to invalidate / recreate content on change are going to make your life a lot easier.
Most likely you still want some barebone php script on the frontend, which concatenates are your separate caches, and is possibly able to create an html portion on the fly when a cache isn't available.
As a final suggestion: I'd peek at what major frameworks, CMS's & eCommerce solutions implement as a cache, there are a lot of errors you can make, and most are already solved.
What's the best way (to avoid modifying repeated code) to building multilingual web pages?
I know how to build a multilingual web page without having to modify CSS and Javascript files.
But I can't think of a neat solution for HTML and Php files. Because if I have HTML or Php files for each language, I would have to modify each one if, for instance, I add an extra div or other element.
I was thinking to have something like this:
<div id="multilingual div">
<p><?php echo($multilingual-paragraph); ?></p>
</div>
(So, even if I modify these elements, I will just do it once, because the text that is in other language will show up from the variable).
I don't know Php, so I don't know how to tell Php to display a different variable according to the language (I think it has something to do with IF conditions)
Is this a good way of creating multilingual web pages or there are other methods?
(So with this
Check out the gettext() function. You don't really need to build different files for different languages. Altough, you'll have to struggle with the translation files.
You can implement a constants-solution for output messages. Using APC's cache functions, you can store multiple messages inside the cache and load them according to the pages you're viewing (this might not be an easy solution though, you need to know php for this).
This would allow you to maintain an array with values for each language in the cache. For example:
apc_constants_define('en',array('welcomeMessage'=>'Welcome!'));
apc_constants_define('es',array('welcomeMessage'=>'Bienvenidos!'));
apc_constants_define('de',array('welcomeMessage'=>'Willkommen!'));
through AJAX/select form, you can allow the user to choose the language they want to view your pages.
This language would be stored inside a session:
$_SESSION['language'] = 'en';
Next, on every page's top, you should check the session (simple switch statment) and load the constants from the cache accordingly.
apc_load_constants($_SESSION['language']);
then your html page would look like this:
<h1><?php echo welcomeMessage; ?></h1>
This is, as I see it, the most efficient way of internationalizing your website, and with an easily maintainable system, that doesn't require you to delve into the code when you want to translate your page to Romanian.
As you said, you have php and html language files, one way is to go like this:
$lang = '';
switch ($lang_file)
{
case 'en.php': $lang = 'whatever'; break;
case 'fr.php': $lang = 'whatever'; break;
// etc
}
<div id="multilingual div">
<p><?php echo $lang; ?></p>
// or you may include files
<p><?php include_once ($lang); ?></p>
</div>