I have this code
<a href="
?page=<?php echo $_GET['page'] ?>
&tab=<?php echo $_GET['tab'] ?>
&subtab=list"
Nazwa</a>
Chrome renders the above code as this:
?page=nurk-edycja-tresci-home &tab=artykuly &subtab=list
With a lot of whitespaces :C I know a cause comming from my coding style but for me this improves readability a lot. Is there any solution to reconcile my style with browsers? ;)
Keeping the white-space server-side
It also doesn't look like your HTML syntax is valid, you're missing a >
When the PHP is preprocessed, it won't return any of the whitecaps in the code so you should be good:
<a href="<?php
echo '?page' . $_GET['page'];
echo '&tab' . $_GET['tab'];
echo '&subtab=list";
?>">Nazwa</a>
You could also put the whitespace in <?php ?> so the server will process it and then return it to the client
<a href="<?php
?>?page=<?=$_GET['page'] ?><?php
?>&tab=<?=$_GET['tab'] ?><?php
?>&subtab=list"
>Nazwa</a>
You can also replace <?php echo with <?=
How I would do it
<a href="<?= '?page=', $_GET['page'], '&tab', $_GET['tab'], '&subtab=list' ?>">
This syntax is very readable and also let's you put newlines:
<a href="<?=
'?page=', $_GET['page'],
'&tab', $_GET['tab'],
'&subtab=list'
?>">
JavaScript?
If you really like your code right now, you can use JavaScript to get rid of the spaces:
(function () {
window.onload = function () {
var elems = document.getElementsByTagName('a'),
i = 0;
for (; i < elems.length; i += 1) {
elems[i].href = (elems[i].href || '').replace(/\s/g, '');
}
}
}());
Even shorter:
window.onload = function () { Array.prototype.forEach.call(document.getElementsByTagName('a'), function (t) { t.href = (t.href || '').replace(/\s/g, '') }) }
ECMAScript2015 (Harmony):
window.onload = () => Array.from(document.querySelectorAll('a[href]')).map(t => (t.href = a.href.replace(/\s/g, ''));
You can solve it by moving the PHP close tag, (and the opening quote), although it still doesn't look very nice:
<a href=
"?page=<?php echo $_GET['page']
?>&tab=<?php echo $_GET['tab']
?>&subtab=list">
Nazwa</a>
But personally, I would choose to build the url earlier, so you just have to output a small variable in your HTML:
<?php
// I know you can use array items in strings too, but I like to split it up.
$page = $_GET['page'];
$tab = $_GET['tab'];
$url = "?page=$page&tab=$tab&subtab=list";
?>
<a href="<?=$url?>">
Nazwa
</a>
[opinion] I think the last way is better. You have just a simple variable to output, which is constructed somewhere else. This way it's also much easier to move the HTML to a separate template. Such template should contain as little logic as possible and concatting variables should not be there. [/opinion]
Related
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
i am trying to insert a link in an echoed line,
regular links work, but not this one, cant figure it out what's wrong
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
the_permalink() is a not a return function, it echoes the permalink. Replace it with get_permalink, which returns the permalink.
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
Your first problem is that. You don't include a function on a string that way.
echo '<li><a href="**<?php the_permalink(); ?>**">
Try this:
echo '<li><a href="'.the_permalink().'">
Then
.$gallery_image[SN.'gallery_post_title'].
You got a syntax error there.
SN.'gallery_post_title' // notice SN
It's fine if you define SN though.
Also, why do you have a close curly brace }?
Did you just copy and paste your code here sloppily or is that intentional? It's confusing if it is.
so after all the confusion here (my apologize)
here is what I have figure I will just re-write it here and make it clear and just for the future notes (I know people won't really need this) but then will just be like a case study
what I was actually wanted is like this example
***********************************************
** link1 - link2 - link3 - link4 - link5 **
***********************************************
** content here, here's the words **
** content here, here's the words **
** content here, here's the words **
** content here, here's the words **
** content here, here's the words **
***********************************************
then I found it something like this
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
</ul>
<?php
if(!isset($HTTP_GET_VARS['link'])){
$link = 1;
} else {
$link = $HTTP_GET_VARS['link'];
}
if ($link == 1) {
echo "<div id="player1"blah blah with video link1";
} elseif ($link == 2) {
echo "<div id="player2"blah blah with video link2"";
} elseif ($link == 3) {
echo "<p>Some text about link 3</p>";
} elseif ($link == 4) {
echo "<p>Some text about link 4</p>";
} else {
echo "<p>Some text about link 1</p>";
}
?>
then #royrui clarify me that
the solution should be like this
<?php
if(!isset($_GET['link'])){
$ch = 1;
} else {
$ch = $_GET['link'];
}
if ($link == 1) {
echo "<div id='player1'blah blah with video link1'";
} elseif ($link == 2) {
echo "<div id='player2'blah blah with video link2'";
} elseif ($link == 3) {
echo "<p>Some text about link 3</p>";
} elseif ($link == 4) {
echo "<p>Some text about link 4</p>";
} else {
echo "<p>Some text about link 1</p>";
}
?>
so if you notice first thing I changed from if(!isset($HTTP_GET_VARS['link'])){
to if(!isset($_GET['link'])){
in the div all it was " so I change it to ' and now the div can be place in echo
and now every single time when people click on link 1 then that div will be place and 2 and so on.
I know it was my problem with the confusion questions but then I really appreciated with all the help from here.
I want to vote the best answers but all it was useful so I just thought of put together to answer myself in this first post
Thanks once again!
The trick is that your PHP code is running on the server and not the browser. You need a combination of code running on both sides to accomplish this (known as AJAX).
Here is some example JavaScript code (no library needed) to replace the contents of a div:
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function getLinkText(linkNo) {
http.open("GET", "getLinkText.PHP?link=" + linkNo, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('divLinkText').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<p>Link1</p>
<div id="divLinkText">
This will be replaced by the AJAX Call.
</div>
The next step is to make a PHP page that returns the contents of the DIV tag at getLinkText.PHP?link=1. I'll leave that to you as it seems you have that part down.
As others have mentioned, adding the jQuery library makes this code a lot more compact and I recommend it.
I'm doing this with a javascript library called jquery, because the way you specify it, it looks like you want some AJAX functionality. You can do this in javascript without the use of a library, but then you have to work around quite some browser incompatibilities.
For this example, I will assume that all your navigation items are placed in an element with an id of nav.
then your javascript code should look like this:
$('#nav a').click(function(){
$('#destinationdiv').load($(this).attr('href'));
});
The php looks like this: First, you make your main php file, such as page.php or whatever.
<?php
$secure=true; //This will ensure that users can't request any content without this script in between.
$pagenum = (isset($_GET['page'])) ? $_GET['page'] : 1;
require('page'.$pagenum.'.php');
?>
and now, you add php files for every page of content that you want to serve, they should all look like this:
<?php if(!$secure) die("access denied!"); ?>
<h1>My awesome page content!</h1>
<p>bla bla bla</p>
so, to glue it all together
On your server, you should have files for each page you want the user to ba able to view. In your navigation, your a tags should have a href tag of page.php?page=1 or whatever. So, if you have a file called page1.php, and then put page.php?page=1, the javascript will stop the link from actually linking to that file. Instead, it will make a request to your server for page.php with a get variable called page, with a value of 1. the php script now looks on the server for a php file called page1.php and includes that in the current script. When PHP is done executing, the output will be sent back to the browser. Than the javascript load function that we called to request the page will insert it into the div we selected.
<li>Link 1</li>
<li>Link 5</li>
</ul>
<?php
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "<div id='player1'>content here, here's the words plus html'video link1'</div>";
} elseif ($link == 2) {
echo "<div id='player1'>content here, here's the words plus html'video link1'</div>";
} elseif ($link == 3) {
...
} else {
echo "<p>Some text about link 1</p>";
}
?>
OK.
I have a very long and pretty complicated function.
It looks almost like this one:
<?php
function hello() {
echo 'My Function!' ?>
<ul>
<li> Blablabla </li>
<ul>
(...)
<?php } ?>
The HUGE problem here is that I'm UNABLE to echo anything.
My function HAVE to return it's contents instead of echoing or direct outputting (it has to be that way, it's a Wordpress shortcode and when I echo - the contents are getting displayed at the top of the page - ALWAYS, not in the place where I want them):
<?php
function hello() {
$output .= 'My Function!';
$output .= '<ul>';
$output .='<li> Blablabla </li>';
$output .='<ul>';
(...)
return $output;
} ?>
I hope it's easy till now.
Now, the real problems are:
I have tons of direct input code like:
?>
<div>
<span>
<p>Smth</p>
<a>smth</a>
</span>
</div>
<?php
Adding $output everywhere kills the nice paragraphs/whitespace and code is getting VERY HARD to read and understand (and all HTML elements are parts of variable now, so even my php editor is not treating them well and coloring them as PHP elements).
And another thing, I have tons of lines like this one:
<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link">
(yes, this is a single line)
And I have absolutely no idea how to add such lines to $output.
$output .= '<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link"> ';
Doesn't work of course (even with \'s before ' and ").
I believe there MUST be an easier way to attach all the code to return, but how?
I've tried with ob_start(); before code and return ob_get_clean(); after, but it outputs shortcode name instead of contents.
Its very hard to imagine what the problem you are trying to solve here is - although I'm not familiar with wordpress. Can't you just call the function where the output is supposed to go?
You could use output buffering - use echo/print as usual but...
ob_start();
hello();
$output=ob_get_contents();
ob_end_clean();
But that doesn't solve the problem that you still need to send to the browser at the right place in the page - and if you can do:
print $output;
in the right place, then you can surely do:
hello();
in the same place.
I agree with symcbean, but this might be a more practical approach at integrating with Wordpress: if you now have a single function called hello( ) which displays HTML, you might want to consider renaming that function to hello_content( ) (or something similar) and replace the hello( ) function with the suggestion symcbean gave you:
function hello_content( ) {
echo "foo";
}
function hello( ) {
ob_start( );
hello_content( );
return ob_get_clean( );
}
That should fix your immediate issue.
PHP Heredoc syntax will keep things looking neat and tidy and you can return the output to a variable. As long as you don't require any constants it will work fine.
You use it in this fashion:
function bar() {
$var = <<<EOV
anything here
anything there
EOV;
return $var;
}
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php $_NAME = urlencode($_NAME); ?>
<?php $_MGT_NAME = urlencode($_MGT_NAME); ?>
</div>
<?php } ?>
I am getting this error expected ';'
The horror. The horror.
Here's the actual error, in the onclick attribute value:
lpButtonCTTUrl = 'http:...Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer
That is, there should be a +' instead of ; after the document.location inclusion, and there should be a closing quote after the imageURL inclusion, and referrer is in the wrong place (it should be just before the document.location inclusion.
It also has problems like the use of escape (never use escape. For URL-encoding you actually want encodeURLComponent); the unescaped ampersands all over the place; and the lack of HTML- and URL-encoding of values output from PHP, potentially causing cross-site scripting risks.
Writing a value inside a URL component inside a URL inside a JavaScript string literal inside an attribute value inside HTML is utter insanity so it's no surprise there are mistakes. Let's try to bring some maintainability to this madness. Break out the JavaScript and URL creation into separate steps where getting the escaping right is possible.
function urlencodearray($a) {
$o= array();
foreach ($a as $k=>$v)
array_push($o, rawurlencode($k).'='.rawurlencode($v));
return implode('&', $o);
}
function h($s) {
echo htmlspecialchars($s);
}
With these utility functions defined, then:
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php
$lpbase= 'http://server.iad.liveperson.net/hc/84152841/?';
$linkurl= $lpbase.urlencodearray(array(
'cmd'=>'file',
'file'=>'visitorWantsToChat',
'site'=>'84152841',
'byhref'=>'1',
'skill'=>'somesiteILS',
'SESSIONVAR!skill'=>'somesiteILS',
'SESSIONVAR!Management Company'=>$_MGT_NAME,
'SESSIONVAR!Community'=>$_NAME,
'SESSIONVAR!Ad%20Source'=>'somesite.com',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
$imgurl= $lpbase.urlencodearray(array(
'cmd'=>'repstate',
'site'=>'84152841',
'channel'=>'web',
'ver'=>'1',
'skill'=>'somesiteILS',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
?>
<div id="caller_tag">
<a id="_lpChatBtn" target="chat84152841" href="<?php h($url); ?>">
<img src="<?php h($imgurl); ?>" name="hcIcon" alt="Chat" border="0">
</a>
<script type="text/javascript">
document.getElementById('_lpChatBtn').onclick= function() {
var url= this.href+'&referrer='+encodeURIComponent(location.href);
if ('lpAppendVisitorCookies' in window)
url= lpAppendVisitorCookies(url);
if ('lpMTag' in window && 'addFirstPartyCookies' in lpMTag)
url= lpMTag.addFirstPartyCookies(url)
window.open(url, this.target, 'width=475,height=400,resizable=yes');
return false;
};
</script>
</div>
With an unformatted mess like that it's no wonder you can't find the error.
I tried running it through HTML Tidy but it doesn't like anything between the comments.
mesite.com& ='+escape(document.location); imageUrl=<?php print "ht
I'm not good at reading long lines like that but shouldn't this be
mesite.com& ='+escape(document.location) +'imageUrl=<?php print "ht
First of: why are you opening and closing PHP so many times, you could write it like:
<?php
} elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) {
$_NAME = urlencode($_NAME);
$_MGT_NAME = urlencode($_MGT_NAME);
?>
<div id="caller_tag">
<!-- BEGIN LivePerson Button Code --><a id="_lpChatBtn" href='http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&byhref=1&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>' target='chat84152841' onClick="lpButtonCTTUrl = 'http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl); lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);window.open(lpButtonCTTUrl,'chat84152841','width=475,height=400,resizable=yes');return false;" ><img src='http://server.iad.liveperson.net/hc/84152841/?cmd=repstate&site=84152841&channel=web&&ver=1&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&skill=somesiteILS' name='hcIcon' alt='Chat Button' border=0></a><!-- END LivePerson Button code -->
</div>
And also: the error must be somewhere else, I can't see a missing ";" in php in the code you pasted, unless the error is in javascript.