In an attempt to make my code more encapsulated, and thus easier to read, I've opted to use echo statements to fill in redundant sections across my web application's webpages. For example, all of my pages have the same nav-bar, footer, and header(for the most part). I've implemented a way to "inject" html fragments dynamically, much like jQuery can do. A snippet of my index page looks something like this:
<html lang="en">
<?php
// START Head.
echo "<head>";
// Inject Head here.
echo $page_content['head'];
echo "</head>";
// END Head.
// START Body.
echo "<body>";
// Inject Navbar here.
echo $page_content['navbar'];
// START Div{.container}.
echo "<div class=\"container\">";
// Inject Search Bar here.
echo $page_content['searchbar'];
// Inject Footer content here.
echo $page_content['footer'];
echo "</div>";
// END Div{.container}.
echo "</body>";
// END Body.
?>
The $page_content variable hold all the fragments.
What are the benefits? What are the drawbacks? Are there any concepts I am overlooking here in an attempt to make my code more concise?
Generally mixing markup and PHP is considered bad practice, and makes maintenance a nightmare. Also should the need arise, it is harder for the work to be divided between a front-end developer and you. Consider using an off-the-shelf templating engine instead like Twig (among others) as this allows you to achieve what you are trying to do more elegantly:
<head>
{{ $page_content['head'] }}
</head>
http://twig.sensiolabs.org/
Related
I am a little bit stuck trying to get a tracking code to work for my website.
Every click to my website through a tracker inserts a randomly generated unique string within the URL. For example, http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd
When someone does goes through a step by step process on my website, a PHP script will load containing various variables, one of which is an external javascript:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251"></script>
In order for me to facilitate the tracking, I want to be able to add the unique string in the URL into the javascript. The idea is that I can track when someone clicks my website and then completes an entry with an external script. For example:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251?sub_ref=333ktcm1ckpv2uvd"></script>
Could someone advise the best way to achieve this? I've been playing around with this for most of the day without success.
I should add, at the point I want the unique ID added onto the script, the URL on my website is http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd#submit-entry
Thank you #CFP Support that's really useful.
So based on your advice, I've managed to work out that using the below displays the correct URL string that I'm looking to add within the javascript.
https://example.com/test/test.php?sub_ref=230948324095
<?php
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";?>
8 here, we look at _GET Array ( [sub_ref] => 230948324095 )
So based on the above, I believe I should be using:
<?php echo ($_GET['sub_ref'])?>"
The problem I've got now, is that if I use the following, I end up with an error:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php
on line 13" while reading response header from upstream
EDIT:
This is where I am at currently. I've made the change you recommended (first one) which doesn't product an error, however the sub_ref in the button that loads the script is still blank.
settings.php file
<?php
// Set the referral network
$network = 'A';
// Set your submit code below.
$onClick_code = 'call_referral()';
// Set your the referral script below.
$script = '
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
?>
final-step.php
<?php
require_once '../settings.php';
?>
<h1>Submitting Data</h1>
<p class="second-paragraph">Please wait while we process your data.</p>
<div class="data-processing-wrapper">
<div class="data-processing-inner-wrapper">
<div class="cssload-loader-walk">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<span class="console-msg"></span>
<div class="data-verification-wrapper">
<h3>Data Verification</h3>
<p>Thank you, you are almost done submitting your data.
<br>Click on the Submit Now button below to submit your data.
</p>
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button"
<?php if ($network == 'A' || $network == 'B') {?> onclick="
<?php if (!empty($onClick_code)) { echo $onClick_code; } ?>"
<?php } ?>>Submit Now
</a>
<?php if ($network == 'A' && !empty($script)) { echo $script; } ?>
</div>
</div>
<div id="progressBarConsole" class="console-loadbar">
<div></div>
</div>
</div>
</div>
From inspecting the Submit Now button in Chrome, this is what it shows (the ?sub_ref is blank):
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button" onclick="call_referral()">Submit Now</a>
<script type="text/javascript" id="js1" src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="></script> </div>
Am I correct in assuming that the sub_ref does not appear because the script is not being when the page is opened (only when final-step.php runs)?
Looks to me like you are close, just need to point to the right query....
src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251&sub_ref=<?php echo urlencode($_GET['sub_ref'])?>"
Looks fine (though from the example you gave you shouldn't need the urlencode).
It is really hard to tell what is going on though without some actual code.... (which is likely why nobody is answering you..... - nor can I give you much of an answer......)
However, as a 'troubleshooting' tip......
You have to know what you have as variables to work with at any given moment, so learn to stop the code at any given point and take a look what the code sees.
In this case, a good one would be to see what is in the $_SERVER array to see what links are really available before trying to build the reference link (this will tell you where you really are as well as how the user got to you, etc. - a wealth of info to be sure!)
echo __LINE__ . " here, we look at _SERVER "; print_r($_SERVER); echo "<br>";
Another good one at this point is the $_GET, which will tell you what is in the query string as an array....
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";
Having the results of both those will tell you that you actually have the data you think you do (and that is quite often the reason things don't work like you expect!)
(you can also add a
die();
after any line to make the code stop..... Lots of ways to do this, and the most important part is just seeing what is going on!
Use the above, change your question to include more code and show what you are getting in $_SERVER and $_GET at that point and you will get some great, exact answers, I'm sure!
EDIT (after a bit more info.... - but still no full code..... :( again, seeing the script around all this would help get this done..... not sure why you aren't including it...)
Obviously you are in PHP at this moment (as it is a PHP error - the script would tell us that...) and your code won't work in PHP.
You have....
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
and
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php on line 13"
while reading response header from upstream
Which is telling you the issue - - - you can't write JS inside PHP! You can make it a variable, then use it later, or you could 'jump in/out' of PHP/HTML to do it, but you must remember what language you are in and respect that language's rules.
So, you could have:
$script = '<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
Or, 'jump in/out' with:
// PHP code ......
// 'jump out'....
?>
<!-- now you are in HTML and can do some JS -->
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
<!-- where you had correctly 'jumped', but improperly mixed... -->
<!-- now, back to PHP... ->
<? // and you can do more PHP code here.....
You have to respect the language - and where you are at any point in the code!
If you still have issues, INCLUDE THE FULL CODE AROUND THIS (I'm sure it isn't rocket science gov't secret stuff, so save us all some time so you can get the help you are asking for, please!
EDIT:
in your settings.php the link shows as
src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref']
However, you say in the button it is
src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="
Your code is not clear on how things are going...... (does this sound familiar? SHOW THE CODE AS IT IS PROCESSED..... - I can't {and now, won't be able to - I've put too much time on this and am getting 'looks'...} try to guess where that weird change came from. You need to show something that is logical.....
and, prove that you have the _GET - use the print_r just before the _GET to make sure you have the data as it is being processed (sometimes with PHP you have to do some 'tricks' to keep the data on one page and use it on another..... there are several ways to do it, but until I understand your flow and what you are trying to do overall {and mostly, why you are using so many pages.... - it could be an overall design/flow issue...}, it is really hard to get a picture of what you are trying to accomplish..)
SO is not really a training facility - and I have other projects (I'm allowed a bit of time each day to answer questions, etc. - part of the 'give back to the community' policy around here, but my primary work is on paid projects {I'm sure you understand...}, so I can't do more today, but if you give some clear 'steps' on what is going on and errors you see, etc. I can look at this again tomorrow.
I am just trying to exercise on xss and I want the alert box to pop up on echo which should work on echo. I am doing exercises based on concepts and hier I have a wrong usage of htmlspecialchars, which is vulnerable to xss. However this is not really working and I don't get why. here is my code
$name=htmlspecialchars($_GET['myname']);
echo "<HTML><body>";
echo '<form action="">';
echo "name: <input type='text' name='myname' ><br>";
echo "<input type='submit' ></form>";
echo $name; // here I want the xss to execute a popup box
echo "</HTML></body>";
The input script looks like this.
<script>alert();</script>
I have also tried many alternatives. The script is displayed as I typed it and there is not alert box.
I am doing exercises based on concepts and hier I have a wrong usage of htmlspecialchars, which is vulnerable to xss.
You don't, though. You've used htmlspecialchars exactly as it's supposed to be used, and are thus protected against XSS here.
I have a wrong usage of htmlspecialchars, which is vulnerable to xss
Your usage isn't wrong for the rest of the code you have, and it isn't vulnerable to XSS for the code that you have.
Using htmlspecialchars with only one argument uses the default settings which makes <, ", >, and & characters safe.
This is absolutely fine when the content is being output somewhere that you could put a text node.
The main situation where it isn't enough to protect your HTML is when you are:
Delimiting your attribute values with ' instead of "
Putting the data inside an attribute value
That's when you need ENT_QUOTES so that ' gets escaped to. Otherwise you could end up with:
$user_input = "' onmouseover='alert(1)'";
?>
<body data-userinput='<?php echo $user_input; ?>'>
… so new attributes which trigger JS could be added.
(Note you also need different sanitisation techniques if you are inserting data into JS or URLs).
I am attempting to build a very simple advertising system which is included on all of my websites and is called using a variable above the script to determine what kind of advert is displayed.
For this system, I have been using basic include functions. For example, on a clients website, near the footer, I would have:
$ad_type = 'banner';
include = '../../adsystem/adsystem.php';
The code for this adsystem.php is:
///// BANNER AD //////
if($ad_type == 'banner'){
$today = date("Y-m-d");
$sql = "SELECT * FROM `ad_adverts` WHERE `ad_start_date` <= '$today' AND `ad_end_date` >= '$today' AND `ad_type` = 'banner' ORDER BY RAND() LIMIT 1";
$result = $ad_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ad_id = $row["ad_id"];
$ad_link = $row["ad_link"];
$ad_direc = $row["ad_direc"];
?>
<div align="center">
<a target="_blank" href="http://mysite.co.uk/adsystem/adsystem.php?redirect=<? echo $ad_link; ?>&adid=<? echo $ad_id; ?>"><img src="<? echo $ad_direc; ?>" alt="<? echo $ad_link; ?>" style="width:70%; height:70px;"></a>
</div>
<?
}
}
$ad_type = '';
}
/////////////////////
VERY BASIC AT THE MOMENT - IS NOT YET COMPLETE. Simply using this as a test to get it working, then I will deal with fixing security problems and SQL injection, etc...
This will then display the adsystem.php code at the bottom of the site, or wherever I decide to add it. And this works perfectly for local websites - although I am working with websites which are not on the same server, and as you can imagine, that's where I run in to problems due to security issues.
Google Adsense and other advertising agencies combat this issue by using JS code to call the adverts, although I'm not skilled enough with JS to do this. On that direction though, I am wondering if it might be possible to use JS to just call the PHP script or if that would even work?
If anybody could point me in the right place here that would be great?
Without JS you are not able to do it. Please check document.write method. Here you have an example how to add dynamically your JS file with ads into html document:
<script>
var url = 'http://ads.com/buyme?rand='+Math.random()
document.write('<script src="'+url+'"></scr'+'ipt>')
</script>
Under this url, you should generate piece of JavaScript code dynamically in PHP, which should contains content of advertising and write in into html document using document.write method again.
You could use AJAX to call asynchronously to that script. In your php return a JSON with available advertisements.
Also you should consider using template engine and/or PHP framework. Mixing views with business logic isn't great idea.
I am using Accordion (jQuery) on my school webserver. Currently, my coding-scheme uses PHP/HTML/CSS/Javascript. I started noticing an opportunity for automation/templating when writing the entries for the Accordion modules. I write the following code:
<h3>Title</h3>
<div class="nobg">
<p class="nobg">
<!-- Entry text -->
</p>
</div>
so I am looking for pointers for the best way to template that code based on the following needs:
Adjustable parameters: Title, Content
When making new modules with a large content 'parameter', the creation of that parameter should maintain readability.
Since I am already on PHP, I was thinking maybe some sort of template function:
<? php accordion_entry("Title", "Entry Text" ?>
But the text is usually a lot of HTML: like the following:
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
I would like to write that HTML myself in the designated spot where the module will eventually manifest as a whole. Perhaps even cooler would be something like this:
<accordion-entry title="Title">
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
</accordion-entry>
I have no idea how to get started creating such a mechanism, or if it's too much trouble to bother.
I found my temporary solution, until someone comes along with something better! Please review! I am no PHP Expert!! :D
The PHP Function:
<?php
function accordionEntry($title, $entry)
{
echo '<h3>' . $title . '</h3>';
echo '<div class="nobg">';
echo ' <p class="nobg">';
echo $entry; // <!-- Entry text -->
echo ' </p>';
echo '</div>';
}
?>
The PHP function call:
<?php accordionEntry(
"GSM0107IG001 - Integration Manual",
'PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>');
?>
Create a partial, and load your content into it along with settings
accordian.phtml (just use .html if you want, doesn't really matter)
<accordion-entry title="<?php $title ?>">
<?php $content ?>
</accordion-entry>
page.html
<div><?= renderPartial('accordian.phtml',array(
'title'=>'GSM0107IG001 - Integration Manual',
'content' => '<p>your html</p>'
)); ?>
partial.php
function partial($partial, $settings){
//will load html from indicated file, and merge passed settings and content into place before returning all $html
// this allows the reuse of the 'partial()' function for other snippets
$template = file_get_contents($partial);
//$settings should be an array, and then your keys can be extracted as variables that match the $settings variables (such as $title) that exist in the .html partial file
extract($settings); //will assign any keys in your array, such as 'title' to php variables of the same name... so in this case $title, and $content
echo $template;
}
How to add inline JavaScript to a WordPress template file?" Plus add it to every post on my page? for instance, <script type="text/javascript">alert('hello world');</script> would be...
Adding it to a template is easy; just stick it within a tag in any part of the template you want to add it to. For instance:
<script>alert('Hello world!');</script>
as an incredibly basic (and kinda messy and improper) way to demonstrate it. Any template file is just a PHP file, or in other words an HTML file with some extra PHP code thrown in.
Also, to add something to a post, you'll want to add it to the appropriate part of your Wordpress template. For instance, in the default Twentytwelve theme, that'd be the content.php file--that contains the code for a single article, and adding something to that will add it to every instance of an article on the page.
To add some javascript to every post on your page just place it inside the loop. Something like:
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
<script type="text/javascript">alert('hello world');</script>
<?php
the_title();
the_excerpt();
} // end while
} // end if
?>
Would add an alert for every post on the page. That would be pretty messy to have a popup for every post but that's the gist.