Not sure if this is possible but what I am wanting to do is echo a html text link only if the page contains certain php code, in particular just the opening reference of 'myApi'. So if the page contains the following code:
<?php myAPI(variables); ?>
Then I would like to include this somewhere else on the page
<?php echo 'Click Here'; ?>
Any help would be much appreciated, thanks :)
Set an if somewhere, and use isset to test if your API has set a specific variable or not.
if(isset($apiVariable)) {
echo "link content...";
}
(The variable should be specific to your API, obviously.)
Update
I said "somewhere", but it's probably best to do the test logic it in a separate place than where you output the HTML. In that case, you'd need a flag for when you're ready to spit out the HTML:
isset($apiVariable) ? $apiFlag = true : $apiFlag = false;
// continue other PHP operations...
//...now your logic is finished, output HTML.
if($apiFlag) { echo "<a>Link</a>"; }
That way, when you re-visit the page later for revision or update, your logic not all mixed up with your display.
<?php if (isset($variable)): ?>
Click Here
<?php endif; ?>
The function isset() check if the variable is set and returns a boolean. so you can use it to check if a variable exist.
Related
i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);
Say I have a variable of a string that contains an html page. Within that html page variable I have an echo statement-
e.g. <?php echo 'whatever' ?>
Can I somehow "render" that variable to the browser, and have php evaluate all the php statements within the variable?
If I just echo the variable, the html renders fine but the php statements are not evaluated.
If I try running eval on the entire page, it just throws an exception (makes sense).
I know this all sounds like bad practice, but I'm trying to figure out a way to do this without saving the variable to a file and loading the file.
BTW: I'm doing this all within codeigniter, so if there's a way to use $this->load->view on that variable... that would be even better :)
Example Code:
$x = /* Some logic to get a template data from another server */
/* $x is "<html><?php echo 'bla'; ?></html> */
echo $x;
This doesn't work- trying to run echo eval($x) also doesn't work
You can write view data to variable and use this variable in other view
In you controller:
$data['view1'] = $this->load->view('my_view1', '', TRUE); // write view data to variable
$this->load->view('my_view2', $data);
In my_view2:
<html>
<?=$view1?>
</html>
This docs can help you Returning views as data - Codeigniter
I'm not sure I follow you, but I think this is what you want.
If page1_view.php contains HTML and needs to echo a variable. e.g.
<div>Foo says: <?php echo $whatever; ?>!!!</div>
To get that "view" as a string with the variable $whatever evaluated you need this.
$view_data['whatever'] = "Hello World";
$page1 = $this->load->view('page1_view', $view_data, TRUE);
$page1 now contains a string which is the contents of page1_view.php. in this case
"<div>Foo says: Hello World!!!</div>"
I am working in php. I want to get some portion of the url using php,
For Example, my url is "http://localhost:82/index.php?route=product/product&path=117&product_id=2153". i want route=product/product only.
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['route'])) {
$route = $_GET['route'];
}else{
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'route');
You can read it using $_REQUEST as below:
<?php
echo $_REQUEST['route'];
?>
It sounds like simply $_GET['route'] will work, although that will only give you product/product. You can just fill in the rest yourself if you know the name of the parameter.
Those URL parameters are called get variables. You can retrieve them using the super global $_GET like so
$route = $_GET['route'];
try this,
<?php
$ans=$_GET['route'];
echo $ans;
?>
Using the following code,
<?php
if(isset($_REQUEST["route"]))
echo $_REQUEST['route'];
?>
I'm pretty new to PHP but trying to find my way which has worked quite well up till now.
Problem is the following: I have a website with 2 links. Both should redirect to the same second website but depending on the link clicked, some values should change. I was trying to use a PHP session for this.
Here is the code up to now:
Link 1:
<a href="<? echo $link ?>" class="helsinki" onclick="<? $_SESSION['clicked']= "helsinki"; ?>"^^Helsinki^^</a>
Link 2:
^^Seattle^^
Now if I try to read which link was clicked on the next side like this:
<? if(isset($_SESSION['clicked']))
echo "clicked ". $_SESSION['clicked'];
?>
I always see "Seattle", Helsinki never appears although (I thought) I input Seattle if the Seattle link is clicked. Apparently it's not like that... Can anyone help me here?
This is because PHP code is server side, and thus executed at the time of the page request. So $_SESSION['clicked'] is set to helsinki then reset to seattle at the time your first page loads. You may want to use $_GET variables instead of $_SESSION variables.
Wait wait wait a second: PHP is "server-side", javascript is "client-side". That means you will ALWAYS execute PHP before javascript.
What you are trying to achieve can be simply done with a GET variable:
^^Seattle^^
^^Helsinki^^
And than in the second site you can get the value of our parameter:
$city = $_GET['city'];
Not sure if this is useful, but you could create a "redirector". It takes the user to a server side page that will redirect them to the final page and at the same time change the session.
The page:
...
...
The code for redirector.php:
<?php
session_start();
// determine where to redirect user (could be done with database or array of options)
switch ($_GET['link']) {
case 'helsinki':
header('Location: /link/to/helsinki');
break;
case 'seattle':
header('Location: /link/to/seattle');
break;
default:
return;
}
$_SESSION['clicked'] = $_GET['link'];
You're mixing up Javascript and PHP.
PHP is server side, that means that all PHP code is parsed and executed on the server side, and then is sent to the client.
So if you write
line #1: ^^Helsinki^^
and then
line #2: ^^Seattle^^
the value of $_SESSION['clicked'] is always first "Helsinki" (line #1), but then immediately overwritten by "Seattle" (on line #2).
In order to achieve what you want the script to achieve, is, for example, as follows:
^^Helsinki^^
^^Seattle^^
and then catch the sent variables from the PHP variable $_GET:
if (isset($_GET['location'])) {
if ($_GET['location'] == "helsinki") {
// Whatever
}
elseif ($_GET['location'] == "seattle") {
// You want
}
}
"^^Helsinki^^
"^^Seattle^^
and use $_GET['location'] at the other page to check weather it is helsinki or seattle.
$link should be the same for both links.
Also you can't mix PHP (server-side) with Javascript (client-side). Look it up for why that is.
You cannot write PHP code in the onclick event. If you want to do it like that, you should use Javascript/AJAX. Even if you do it like that, you won't still get the result as you desire, since AJAX request will delay some seconds.
I think the right way to do this kind of thing is like below:
Helsinki"
and this is the change_city.php:
<?php
$_SESSION["clicked"] = $_GET["city"];
?>
if you want to still use the $link, then you just put this above code top of your PHP file.
I wanted to use PHP and the if statement, and I wanted to do
if ($variable){
display html page1
}
else {
display html page2
}
How do I do this? An please note, that I do not want to redirect the user to a different page.
--EDIT--
I would have no problem doing that with one of them, but the other file, it would be too much of a hassle to do that.
--EDIT--
Here is the coding so far:
<?PHP
include 'uc.php';
if ($UCdisplay) {
include("under_construction.php");
}
else {
include("index.html");
}
?>
My problem is that it would be really complicated and confusing if I were to have to create an html page for every php page, so I need some way to show the full html page instead of using include("index.html")
if ($variable){
include("file1.html");
}
else {
include("file2.html");
}
The easiest way would be to have your HTML in two separate files and use include():
if ($variable) {
include('page1.html');
}
else {
include('page2.html');
}
using the ternary operator:
include(($variable ? 'page1' : 'page2').'.html');
If you want to avoid creating "an html page for every php page", then you could do something like this, with the "real" content directly inside the PHP page.
<?PHP
include 'uc.php';
if ($UCdisplay) {
include("under_construction.php");
exit;
}
?>
<html>
<!-- Your real content goes here -->
</html>
The idea is this: If $UCdisplay is true, then your under construction page is shown, and execution stops at exit; - nothing else is shown. Otherwise, program flow "falls through" and the rest of the page is output. You'll have one PHP file for each page of content.
You could side-step this issue by moving the code that checks $UCdisplay directly into uc.php; this would prevent you from having to write that same if statement at the top of every file. The trick is to have the code exit after you include the construction page.
For those still looking:
See the readfile(); function in php. It reads and prints a file all in one function.
Definition
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
Reads a file and writes it to the output buffer.