what is wrong with this snippet - php

<?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.

Related

PHP if/else without echo

How do I replace echo with proper html codes? Since there will be hundreds of html codes, using echo doesn't make sense.
<?php
if ($this->item->catid == 9) {
echo "yes, it exists";
}
else {
echo "no, it don't exist";
}
?>
I'm new to PHP.
Do you mean, how can one cleanly output many lines of HTML conditionally without having to echo each individual line?
If that's the case, something like this would do the trick:
<?php
if ($this->item->catid == 9) {
?>
<!--- put all the raw output you like here --->
<?php
} else {
?>
<!--- put all the raw output you like here --->
<?php
}
?>
The "raw output" would be anything sent to the browser. HTML, JavaScript, etc. Even though it's outside of the server-side PHP tags, as far as the PHP processor is concerned it's still between the { ... } brackets. So it's only output as part of that conditional block.
There is two way to do it :
1) As suggested by David, by closing your php tags to write raw HTML.
<?php
if ($this->item->catid == 9) {
?>
// HTML goes here
<?php
}else{
?>
// HTML goes here
<?php
}
?>
But if you're planning to write a lot of text it might be a be hard to read your code in the end so you can use the following.
<?php
$htmlOutput = '';
if ($this->item->catid == 9) {
$htmlOutput .= "yes, it exists";
} else {
$htmlOutput .= "no, it doesn't exist";
}
?>
You create a variable that will contain all your HTML by appending a part of it everytime you need to so in the end you'll only need to print a single variable.

if Else php need explanation

i write a code in php and i found that there is a problem in a code like this :
<?php if(isset($_GET['f'])) { ?>
<?php if($_GET['f']=="message_reçus") { ?>
-- another code here --
<?php } ?>
<?php } ?>
<?php else { ?>
But when i just write it this way :
<?php if(isset($_GET['f'])) { ?>
<?php if($_GET['f']=="message_reçus") { ?>
-- another code here --
<?php } ?>
<?php } else { ?>
It works.
I need a clear explanation about what caused the problem in the first version because i still convinced that both version are syntactically right!
PHP Parser shows me : Parse error: syntax error, unexpected 'else' (T_ELSE)
I don't need any alternative solution i just wonder to know why there is a problem in the first version and what's wrong with it!
One way to think about it is to replace ?> ... <?php with echo "...";
So your code becomes:
<?php
if(isset($_GET['f'])) {
echo "\n\t";
if($_GET['f'] == "message_reçus") {
echo "\n\t\t";
// more code here
echo "\n\t";
}
}
echo "\n"; // problem!
else {
// ...
}
Whereas if you just have } else { you don't have that extra echo "\n"; in the way.
The description to the problem was detailed in a different answer by #NietTheDarkAbsol. I'm adding this answer to add an alternative solution to the problem by removing it.
The problem exlained (#NietTheDarkAbsol answer describes this)
By separating out the lines you add in a \n or new line whereas else MUST always come after the closing brace of the opening if.
<?php if ($a === $b) { ?>
<?php } ?>
<?php else { ?>
This is interpreted as if ($a === $b) { \n } \n else {
The \n or new line after the ifs closing bracket removes any ability for the parser to understand that the else is associated with the if and throws the error.
An alternative approach to remove a requirement for curly braces.
An approach that is particularly useful when interpolating HTML files with PHP is to use an alternative control structure that removes the need for braces. This will also help you in your current predicament as well as making your code look a little cleaner.
<?php if(isset($_GET['f'])) : // Colon instead of an '{' ?>
<?php if($_GET['f']=="message_reçus") : ?>
<!-- HTML here -->
<?php else : ?>
<!-- alternative HTML here -->
<?php endif; // endif; instead of an '}' ?>
<?php endif; ?>
As your code is now non reliant on curly braces your problem vanishes as it is waiting for either an endif;, else : or elseif (...) : block.

HTML disable enter in my code

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]

PHP function return. Cheats allowed

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: "unexpected $end" in the middle of a file

When I try to run this page (video.php), I get the following error:
Parse error: syntax error, unexpected $end in /base/path/masked/inc/functions.php on line 37
The strange thing is "functions.php" has more than 37 lines... why is it detecting an end of file there? I don't think I'm missing any parens or brackets since each function is only one statement (a print statement) long.
I've done several things to try and fix the problem. If I remove the statements in the function definition for both print_head() and print_foot(), the error goes away (the rest of the page works fine). If I remove statements in either one of the functions, I get the same error, just on a different line. If I move the function definitions around on the page, I get the same error. I've even tried removing parts of the print statement, but I still get the same error.
EDIT:
'videos/transfer/playlist' is an example file that get_vids() loads. It's a flat txt file with an even number of lines; odd lines are the name of a video file, and even lines are the title that go with the preceding file. I've tested to make sure get_vids() works as expected.
EDIT:
Here's what I get when I try to run everything from the command line:
$ php -l video.php
No syntax errors detected in video.php
$ php video.php
Parse error: syntax error, unexpected $end in /home/nova20/http-dir/orientation/inc/functions.php on line 37
$ php -l inc/functions.php
Parse error: syntax error, unexpected $end in inc/functions.php on line 37
Errors parsing inc/functions.php
Here's my code:
video.php:
<?php
include('inc/functions.php');
$type=$_GET['type'];
if($type == '') {
$type = 'transfer';
}
$vidno = $_GET['vid'];
if($vidno == '') {
$vidno = 1;
}
$vidindex = $vidno - 1;
$videos = get_vids($type);
$filename = $videos[$vidindex]['file'];
$title = $videos[$vidindex]['title'];
$basedir = "videos/$type";
$vidfile = "$basedir/$filename";
if($vidfile != '') {
$extra = '<script src="/flowplayer/flowplayer-3.1.4.min.js"></script>';
print_head($title, $extra);
print <<<ENDHTML
<p>
<a
href='$vidfile'
style="display:block;width:640px;height:498px;"
id="player"
></a>
</p>
<p id="contlink" style="display:none">
Click Here to continue
</p>
<script language="JavaScript">
flowplayer(
"player",
"/flowplayer/flowplayer-3.1.5.swf",
{
clip: {
onFinish: function(){
//window.location = "done.php";
//alert('done!');
document.getElementById('contlink').style.display = "block";
}
},
plugins: {
controls: {
play:true,
volume:true,
mute:true,
time:true,
stop:true,
fullscreen:true,
scrubber:false
}
}
}
);
</script>
ENDHTML;
print_foot();
} else {
print_head('OOPS!');
print <<<ENDERROR
<h1>OOPS!</h1>
<p>
It looks like there's no video here. <a onclick="history.go(-1);return false;" href="#">Go back</a> and try again.
</p>
ENDERROR;
print_foot();
}
?>
inc/functions.php (where I think the problem is):
<?php
function get_vids($type) {
$base = "videos/$type";
$playlist = "$base/playlist";
$vidinfo = file($playlist);
$videos = array();
for($i = 0; $i < count($vidinfo); $i += 2) {
$filename = trim($vidinfo[$i]);
$title = trim($vidinfo[$i+1]);
if($filename != '') {
$index = $i / 2;
$video['file'] = $filename;
$video['title'] = $title;
$videos[$index] = $video;
}
}
return($videos);
}
function print_head($title, $extra = '') {
print <<<ENDHEAD
<html>
<head>
<title>$title</title>
$extra
</head>
<body>
ENDHEAD;
}
function print_foot() {
print <<<ENDFOOT
</body>
</html>
ENDFOOT;
}
?>
videos/transfer/playlist
1.flv
Introduction
2.flv
Why am I doing this?
3.flv
What can I access with RAIN?
4.flv
How do I access my RAIN Account?
5.flv
How do I Check my registration status?
6.flv
Evaluating transfer credit
7.flv
Transferable degrees
8.flv
Physical Education and History
9.flv
Regents exemptions
10.flv
Academic status
11.flv
How to find my academic advisor?
12.flv
Is Financial Aid available?
13.flv
How do I check my financial aid status?
14.flv
How do I transfer my hope scholarship?
15.flv
Payment information
16.flv
Student Services (Part 1)
17.flv
Student Services (Part 2)
18.flv
Student Services (Part 3)
19.flv
Campus Bookstore
20.flv
Where can I eat on Campus?
21.flv
Where can I live on Campus?
22.flv
How do I register for Parking?
23.flv
Still Have questions?
It's not detecting an end-of-file, per se, but a logical end of the executable lines of code.
Make sure your HEREDOC end tokens (ENDHEAD; and ENDFOOT;) have no spaces before them - the moment they're not the first token on the line, they don't register as HEREDOC end tokens but as an arbitrary string within, so your HEREDOC eats up more of the codeblock.
That's the only thing that comes to mind - php -l <your functions.php> netted me no errors (but adding a space before ENDHEAD; gave me the error you described).
I've fixed the code for you:
<?php
include('inc/functions.php');
$type=$_GET['type'];
if($type == '') {
$type = 'transfer';
}
$vidno = $_GET['vid'];
if($vidno == '') {
$vidno = 1;
}
$vidindex = $vidno - 1;
$videos = get_vids($type);
$filename = $videos[$vidindex]['file'];
$title = $videos[$vidindex]['title'];
$basedir = "videos/$type";
$vidfile = "$basedir/$filename";
if($vidfile != '') {
$extra = '<script src="/flowplayer/flowplayer-3.1.4.min.js"></script>';
print_head($title, $extra);
?>
<p>
<a
href='<?=$vidfile;?>'
style="display:block;width:640px;height:498px;"
id="player"
></a>
</p>
<p id="contlink" style="display:none">
Click Here to continue
</p>
<script language="JavaScript">
flowplayer(
"player",
"/flowplayer/flowplayer-3.1.5.swf",
{
clip: {
onFinish: function(){
//window.location = "done.php";
//alert('done!');
document.getElementById('contlink').style.display = "block";
}
},
plugins: {
controls: {
play:true,
volume:true,
mute:true,
time:true,
stop:true,
fullscreen:true,
scrubber:false
}
}
}
);
</script>
<?php
print_foot();
} else {
print_head('OOPS!');
?>
<h1>OOPS!</h1>
<p>
It looks like there's no video here. <a onclick="history.go(-1);return false;" href="#">Go back</a> and try again.
</p>
<?php
print_foot();
}
?>
You can just open and close the php tags around the html that you want to display - as you will see above :)
Hope that helps

Categories