How to add link within if-statement? - php

I have some problems to put a URL-function within an if-statement properly. The following method works fine outside of my if-statement and the newly created link refers to this URL: "h**p://www.blog.com/?location=Bern&date=1"
<?php $rasp = $_GET["location"]; ?>
<a href="<?php echo preg_replace("/&date=(0|1|2|3)/", "", $_SERVER[\REQUEST_URI\])."&date=0"; ?> " >Heutel</a>
If-Statement works also just fine when I put simply an URL (e.g. https://www.google.com/) in between the quotation marks, then if I put the URL-function above in there, the newly created link refers to this: "h**p://www.blog.com/%3C?php%20echo%20preg_replace%28". Actually it should refer to the URL above "h**p://www.blog.com/?location=Bern&date=1"
URL-Function within if-statement:
<?php $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (false !== strpos($url,'date=1')) { echo
'<?php $rasp = $_GET["location"]; ?>
<a href="<?php echo preg_replace("/&date=(0|1|2|3)/", "", $_SERVER[\REQUEST_URI\])."&date=0"; ?> " >Heutel</a> ' ;
} else {
echo 'No cars.';
} ?>
Any ideas?
Solution thanks to IMSop:
<?php
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (false !== strpos($url,'date=1')) {
?>
<a href="<?php echo preg_replace("/&date=(0|1|2|3)/", "", $_SERVER['REQUEST_URI'])."&date=0"; ?> " >Heutel</a>
<?php
}
else {
echo 'No cars.';
}

This sequence makes no sense:
echo '<a href="<?php echo ...
A quoted string and direct output outside the <?php ... ?> markers are completely different things. The ' starts a string, which will continue until you put another '; the <?php would start a block of PHP code if you weren't in one, but you already are - if you weren't the echo wouldn't mean anything.
To join multiple strings together, you can use the . ("concatenation") operator:
echo '>Heutel';
Alternatively, drop out of PHP mode like you were before, but with the if in place:
<?php
// In PHP mode...
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (false !== strpos($url,'date=1')) {
// Now leaving PHP mode, but still inside the if condition...
?>
<a href="<?php echo preg_replace("/&date=(0|1|2|3)/", "", $_SERVER['REQUEST_URI'])."&date=0"; ?> " >Heutel</a>
<?php
// Re-enter PHP mode to close off the if statement
}
There's even an alternative syntax for control syntax which some people prefer to use in cases like this:
<?php
if ($some_condition) :
?>
your output here
<?php
endif;
?>
which is exactly the same as
<?php
if ($some_condition) {
?>
your output here
<?php
}
?>

Related

PHP statement within echo

I am essentially trying to combine to PHP statements.
<?php echo ROOT_PATH; ?>
<?php echo file_get_contents( "../css/themes/subtitle.php"); ?>
I want to achieve something like this:
<?php echo file_get_contents( "ROOT_PATH/css/themes/subtitle.php"); ?>
If you call constants inside single or double quotes then it will be always picked as a string.
You need to add like below:
<?php echo file_get_contents( ROOT_PATH."/css/themes/subtitle.php"); ?>
Its pretty simple you can change it to following
//full path of the file
$file_name = ROOT_PATH."/css/themes/subtitle.php";
echo file_get_contents($file_name);
it should work
. operator is used to concatenating.
Like:
$str = "Hello";
echo $str;
echo "World";
can be written as
$str = "Hello";
echo $str."World";

php inserting link parts into http

I am trying to retrieve parts of the getcwd() method and inserting them into window.open()
the current getcwd() gives me this C:\wamp\www\qa4u\qa4u_working\Presenter
Using this code :
<?php
if(isset($_POST['genPDF'])){
foreach($_POST['email'] as $email)
{
$eid=$_POST['eid'];
?>
<script type="text/javascript" language="Javascript">
<?
$stringlink = getcwd();
$pieces = explode('\\', $stringlink);
?>
window.open("http://"+"<?php echo $_SERVER['HTTP_HOST']?>"+"/"+"<?php $pieces[3]?>"+"/"+"<?php $pieces[4]?>"+"/"+"<?php $pieces[5]?>"+"/genPDF.php?eid=<?php echo $eid ?>&email=<?php echo $email ?>");
</script>
<?php
}
}
?>
I am trying to achieve this instead :
window.open("http://qna.nyp.edu.sg/qa4u/qa4u_working/presenter/genPDF.php?eid=<?php echo $eid ?>&email=<?php echo $email ?>");
without forming static links is there a way to get the code to work ?
2 issues regarding your code, that I believe prevents it from working.
You're not printing the pieces values. You should use echo, print or a shorthand <?=$var ?>
Since those are PHP variables, you don't need to use the JS + symbol
So, you should update your code:
window.open("http://<?php echo $_SERVER['HTTP_HOST']; ?>/<?php echo $pieces[3]; ?>/<?php echo $pieces[4]; ?>/<?php echo $pieces[5]; ?>/genPDF.php?eid=<?php echo $eid; ?>&email=<?php echo $email; ?>");

PHP script tags

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>
Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)
Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.
Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}
Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }
That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

Including php variable in header()

I'm still learning php and I still haven't figured out when to use ' or ". I'm guessing thats the problem with this code. It redirects me to the right page but the $loc variable isn't carried over.
<?php header("Location: roomdata.php?loc=$loc"); ?>
on the page that has the header() commaned I also have an include command...
<?php include 'include/globalscripts.php'; ?>
and in the globalscripts.php is...
<?php if( isset($_GET['loc']))?>
<?php $loc = $_GET["loc"];?>
I would personally use:
<?php
header('Location: roomdata.php?loc='.$loc);
?>
<?php if( isset($_GET['loc']))?>
<?php $loc = $_GET["loc"];?>
TRY
<?php
if( isset($_GET['loc'])){
$loc = $_GET["loc"];
}
?>
Your code should work, are you sure $loc is defined at this point?
Regarding ' and ":
$value = "derp";
echo "the value is:\t$value";
//output: the value is: derp
echo 'the value is:\t$value';
//output: the value is:\t$value

Echo entire pre-compiled php page

For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

Categories