Dynamic Title of page? PHP include links? - php

Can the Title of the page (within the head, not a random title) be dynamic?
I was thinking that PHP could return the value of the current page and then echo it into the Title tag after amending it.
I say amending it as I use camel case and I'd need a way of turning userProfile.php into User Profile
Can anyone point me in the right direction please?
I've used :
public function findCurrentPageURL(){
return substr($_SERVER["SCRIPT_NAME"], strpos($_SERVER["SCRIPT_NAME"], "/")+1);
}//end to return current page
as a function and thought that the same principle could be applied.
EDIT: I'm not sure how to word this but here goes, I'm hoping on a simple answer as I can't see this being a rare issue.
I have an init.php file that includes various classes and other files.
This gets called at the top of every page.
It works fine when all the pages that call it are in the same folder. Now I need to create a subdirectory within the main so:
coreFolder
->init.php
->classes
->->class.php
index.php
other.php
otherFolder
->otherPage.php
is an example of what I have now.
In index(and others) my call is require'core/init.php'
In init.php I have
require 'core/connect/dbConnect.php';
require 'core/classes/users.php';
etc etc
The problem I'm now having is when I try and call init from my otherPage.php I have to use include'../core/init.php'
I then get errors as it cannot locate the other includes within init.php.
Is there a solution for this please? I really would prefer to not have one uber great big long list of php files
I can then combine the two and voila

To output the return value of your function in the title tags just put it this way :
<title><?php echo findCurrentPageURL(); ?></title>
in a php page.
Also to split it as you want, see Orangepill comment to the question, linking your question to Split camelCase word into words with php preg_match (Regular Expression) .

First, obtain the filename by:
splitting the requested file path by '/' and obtaining the last item
snipping off the file extension portion
$filename = strstr(end(explode('/', $_SERVER["SCRIPT_NAME"])), '.', true);
Now that the filename is isolated:
split into an array prior to upper-case letter
translate the array into a string with spaces as delimiter
make the first letter of initial word upper-case
return ucfirst(join(' ', preg_split('/(?=[A-Z])/', $filename)));

Related

Str_Replace is replacing php syntax

functions/SkriptParser.php
<?php
$text = file_get_contents(basename($_SERVER['PHP_SELF']));
preg_match_all("/{(.*?)}/", $text, $matches);
var_dump($matches[0]);
echo str_replace($matches[0],"Test",$text);
?>
Is my current code, this is called from my index page which is here:
index.php
require_once 'functions/SkriptParser.php';
When i open index.php it replace the correct strings [ It'll replace any string inside {} however, it seems to be replacing <?php and I have no clue why.
Any ideas?
I'm not sure I fully understand what you are trying to do.
This line $text = file_get_contents(basename($_SERVER['PHP_SELF']));resolves to a local filename which will be the name of the script it's included in.
It won't load the page which that script would output, it will load the file without executing the code. The contents of $text will be a string containing the pure php content.
When I run your code from the command line and use "Here is a test of {your code}" as my string the output is:
{your code}<?php
require_once 'includetest.php';
print_r(basename($_SERVER['PHP_SELF']));
echo "Here's a test of Test";
If I run it from a browser and view the source I see that too, but the browser escapes the php so it isn't rendered on the page. So (for me at least), your concept kinda works. However, the fact the code isn't executed means it will never do what you intend.
Here's what I don't really understand though. In essence within index.php what you are telling your code to do is load a script which will load another copy of index.php and replace content within it.
If you want to change the behaviour of index.php then alter the code within index.php, don't generate unsuitable output and then load another script in an attempt to parse it before returning it. Just output it the way you want the first time.
Where is the content within the {} that you want to remove coming from? Why do you want/need to remove it? If you can clarify exactly what your aim is then it will be easier to suggest a solution.

How to gather code to be used in a htmlentities() function without rendering beforehand?

To put my question into context, I'm working on an entirely static website where 'post' pages are created by myself manually - there's no CMS behind it. Each page will require a <pre> <code> block to display code as text in a styled block. This could be very few - several which is why I'm trying to do this for ease.
Here's what I've done -
function outputCode($code) {
return "<pre class='preBlock'><code class='codeBlock'>".htmlentities($code)."</code></pre>";
}
The code works as expected and produces an expected outcome when it's able to grab code. My idea is to somehow wrap the code for the code block with this function and echo it out for the effect, fewer lines and better readability.
As I'm literally just creating pages as they're needed, is there even a way to create the needed code blocks with such function to avoid having to manually repeat all the code for each code block? Cheers!
EDIT:
I was previously using this function and it was working great as I was pulling code from .txt documents in a directory and storing the code for code blocks in a variable with file_get_contents(). However, now, I'm trying to get the function to work by manually inputting the code into the function.
Well. Wrapping the function input in ' ' completely slipped my mind! It works just fine now!
If I understand correctly, you want to re-use your outputCode function in several different PHP files, corresponding to posts. If yes, you could put this 1 function in its own file, called outputcode.php for example, and then do
include "outputcode.php";
in every post/PHP file that needs to re-use this function. This will pull in the code, from the one common/shared file, for use in each post/PHP file that needs it. Or maybe I'm misreading your last paragraph :(

wordpress style shortcodes in Ckeditor / PHP

I have built a custom CMS. Recently, I added the ability to create pages dynamically. I used CKEditor for the content of these pages.
I would also like to run some php functions that may be included in the content of the page stored in mysql.
I DO NOT want to store actual PHP code in the database, but rather function names perhaps. For example, in a page stored in the database I may have.
<?php //begin output
hello world!
check out this latest news article.
news($type, $id);
//end output
?>
What is the best way to find and execute this existing function without using EVAL if its found in the output? I was thinking along the lines of wordpress style short codes. Maybe [[news(latest, 71]] ? Then have a function to find and execute these functions if they exist in my functions.php file. Not really sure the best way to go about this.
I'm not searching for any code answers, but more of a best practice for this type of scenario, especially one that is safest against possible injections.
I found a solution from digging around and finding this thread
How to create a Wordpress shortcode-style function in PHP
I am able to pass short codes like this in CKEditor
[[utube 1 video_id]]
Then, in my page that renders the code:
print shortcodify($page_content);
using this function:
function shortcodify($string){
return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
$whitespace_explode = explode(" ", $matches[1]);
$fnName = array_shift($whitespace_explode);
return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
}, $string);
}
If the function name exist (utube) it will fire the function.
Only problem Im having at the moment is not matter where I place the [[shortcode]] in my editor, it always executes first.
For example, in CKEditor I put:
Hello world! Check out my latest video
[[utube 1 video_id]]
It will always put the text under the video instead of where it is in the document. I need to figure a way to have the short code execute in the order it is placed.

How to get an html page from another server, and insert php code at a certain point in that file

We're completely redoing our website, and putting most of our pages into a new CMS (Adobe cq5- on server
1). However, we have some php/mysql pages that cant go in there, so we are housing them on our own server(server2). I need our pages on server2 to look exactly like the page on server1.
There is a template on Server 1, with a url of:
http://staging-cms.com/content/directory/template.html
So, I need to
1.pull the template from Server1 using the above URL.
2.Look in that template for this div:
<div class="text"><p>CONTENT FOR TEMPLATE GOES HERE.<br></p></div>
3.Take the content of the page on server 2 and insert it at the above point.
4. Return the full page, with template and contents onto a page on server2.
So, the final url would be something like:
http://server2.com/books.php
Is this possible?
I've tried this below, but all I get is a page with
databases.php printed.
$Content = file_get_contents("http://staging-cms.uc.edu/content/libraries /template.html");
$Content = str_ireplace('CONTENT FOR TEMPLATE GOES HERE','databases.php','What goes here??');//staging-cms.uc.edu/content/libraries/template.html);
print ($Content);`
I've tried other things where I can return the template (kind of). But I cant seem to get it all working together?
$template = file_get_contents("http://staging-cms.uc.edu/content/libraries/template.html");
list($top, $bottom) = explode('CONTENT FOR TEMPLATE GOES HERE', $template);
echo $top;
include '/path/to/databases.php';
echo $bottom;
The PHP code in databases must actually be executed before displaying to the user, so you can't use str_ireplace(), this deals with literal strings only, not file names or PHP code.
Instead you need to split the template into 2 parts (top and bottom), and then include the PHP code which will be executed.
I highly recommmend explode(); function. If you have have the exact text "CONTENT FOR TEMPLATE GOES HERE." your code will be something like this.
<?php
$Content = file_get_contents("http://template.url");
$PHPFileContent = file_get_contents("/path/to/databases.php");
$explodedContent = explode("CONTENT FOR TEMPLATE GOES HERE", $Content);
$theFinalContent = "$explodedContent[0] $PHPFileContent $explodedContent[1]";
?>
You need to search how explode() works btw.
Hope helps.
One Good Design Patters that i like to use is that:
$new_file = file_get_contents($file_for_future);
$old_file = file_get_contents($file_to_copy_body);
preg_match('\preg to find the right position\', $new_file,$match, PREG_OFFSET_CAPTURE);
reg pattern can be '\div class=\"text\">\' but is untested, do it yourself.
$pos = $match[0][1];
The third and forth command is for find the right position that you want to put your new code inside the new file, is a INT number and should be the exact point that you want to start writing your old code.
PREG_OFFSET_CAPTURE in the preg_match force the regular expression to say where they find the standart.
And the magic is:
$final_file = substr($new_file, 0, $pos)."\n".$old_file."\n".substr($new_file, $pos);
This logic will generate a file, using the new template, inserting the old code right where you want to put it.

Read parent URL from included file

OK, so I have searched around for long enough to finally post this one here. Sure enough, it has been asked before a zillion time...
What I have, is one file, which includes another. No magic here. The trouble is, the included file then includes another file, which... includes yet another... Yep, a pain. Actually it's all working quite nicely, except that I now wanted to read the URL of the original file in the last of the included files.
So I thought in the original file, file_1.php I just say
$var_foo = dirname(__FILE__);
or
$var_foo = $_SERVER['SCRIPT_NAME'];
and then read that value in the first include, file_2.php, passing it on like
$var_foo_2 = $var_foo;
then in file_3.php
$var_foo_3 = $var_foo_2
etc, until I arrive at the final file, file_4.php, where I'd like to know the exact value of the original file's URL. Passing it on the first level works OK, but then it gets lost somewhere along the way. Tried going GLOBAL in file_1 -- to no avail.
Since file_3 and file_4 must both execute to produce data, setting a breakpoint a la echo / exit to spoof the current value (if any) is no option. I can live without that particular value, but I just would like to have it -- for the fun of it... Any ideas how to accomplish this?
Your examples use filesystem paths, not "URLs";I am assuming the filepath of the parent file is what you actually want.
You don't need to "pass" the variable on each included page. It will automatically be available to the code on the new page.
(If it is not, you may not be in the right scope: e.g., if you're inside a class or function, you'll need to pass it deliberately or use some other method - global, maybe, or even define the filename as a constant instead of a variable.)
main script
$parent_filename = __FILE__;
// alternatively
// define( 'PARENT_FILENAME',__FILE__ );
include "other-file.php";
other-file.php
include "other-dir/somefile.php";
other-dir/somefile.php
print $parent_filename;
// alternatively
// print PARENT_FILENAME;
/* prints something like:
/path/to/main.php
*/
As mentioned before, the issue has been solved like so:
set variable before the first include
add variable to query string
Thanks all for the input, appreciated.

Categories