Quiting a PHP script within another PHP page - php

I'm trying to implement caching for a PHP script I'm writing, but I keep running into the following problem. I want the script to be included in other PHP pages, but when I try to pass the cached file and exit the embedded script it exits both the script and the parent page, but doesn't parse the rest of the code on the parent page. See the code below for an example.
index.php
<?php
echo "Hello World!<br />";
include("file2.php");
echo "This line will not be printed";
?>
file2.php
<?php
$whatever = true;
if ($whatever == true) {
echo "file2.php has been included<br />";
exit; // This stops both scripts from further execution
}
// Additional code here
?>
If the above index.php is executed you get the following output:
Hello World!
file2.php has been included
However, I'm trying to get it to look like this:
Hello World!
file2.php has been included
This line will not be printed

Use return; instead of exit; in the included file - this will only halt execution of that script.
Note that you an also use this to return a value to the parent script e.g.
file1.php
<?php
echo 'parent script';
$val = include('file2.php'); //$val will equal 'value'
echo 'This will be printed';
file2.php
<?php
echo 'child script';
return 'value';

Just wrap the "additional code here" in an else statement?
<?php
$whatever = true;
if ($whatever == true) {
echo "file2.php has been included<br />";
} else {
// Additional code here
}
?>
Otherwise I'm not sure what you're getting at. The exit command always terminates the current execution in whole - not just execution of the current file (for which, there is no command)
EDIT
Thanks to comments and posts by PHLAK, tomhaigh, MichaelM, and Mario, I myself learned something today - that you CAN indeed terminate the execution of a single included file w/the return command. Thanks, guys!

I personally try to avoid if-else conditions where possible and use (not sure if there's a coined term for it but) early-exit intercepting conditions.
index.php
<?php
echo 'header';
include 'content.php';
echo 'footer';
?>
content.php
<?php
if ($cached)
{
echo cached_version();
return; // return is not just for functions, in php...
}
//proceed with echoing whatever you want to echo if there's no cached version.
...
...
?>

Why not encapsulate the contents of file2.php into a function. That way you can return from the function when you need to, and the rest of the execution will not halt. eg:
file2.php
<?php
// this function contains the same code that was originally in file2.php
function exe()
{
$whatever = true;
if ($whatever)
{
echo "file2.php has been included <br />";
// instead of exit, we just return from the function
return;
}
}
// we call the function automatically when the file is included
exe();
?>
Leave index.php exactly as it is and you should see the output you are trying to achieve.

Related

Include an IF and his corresponding else in PHP

Hi guys I'm trying to do a strange thing, I want put all of my code, of all my website pages inside an if, for example I want do this:
<?php
include('..../...../php/secure-open.php');
if(......){
ALL OF WEBSITE CODE HERE
include('..../...../php/secure-close.php');
}
Where secure-open.php is:
<?php
if(security check here){
?>
And secure-close.php is
<?php
}else{
die();
}
?>
So all the will will be executed only if the security condition is true, but when I try to do it, it says, Unexpected document ends on line`....
Looks like you have missed closing bracket :)
You really should not resolve your security checks that way, but if you really sure that's what you need, move "ALL OF WEBSITE CODE" to different file and just include it inside that if.
if(security_check) {
include "website.php";
} else {
die();
}
And one more easy-to-implement fast check:
index.php:
if (security_check) {
define('SECURE', true);
}
require "website.php";
website.php:
if (!defined('SECURE')) {
die();
}

Passing data between PHP files

Here I have foo.php that runs in the background without any HTML, it's never visited by the user.
<?php
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
echo $str;
}
This is just a simple example, but let's say I wan't to pass $str to another file, script.php for extra processing.
What's the best method for this? The only way I can think of doing this is by posting it into a database and then retrieving it inside of script.php ?
Using Session:
//On page 1
$_SESSION['varname'] = $bar;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $bar;
//On page 2
$var_value = $_COOKIE['varname'];
As # Rizier123 mentioned "Cookies can be deleted or disabled! Wouldn't do that if the variable is very important ". So better avoid this approach.
Something like this is probebly a easy way to do it:
You can make a function out of the if statement
foo.php:
<?php
function fooFunction() {
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
return $str;
}
}
?>
script.php:
<?php
require_once 'foo.php';
?>
OR if you already have a session you can insert it into the session array like this:
foo.php:
<?php
session_start();
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
$_SESSION['str'] = $str;
}
?>
script.php:
<?php
session_start();
echo $_SESSION['str'];
?>
If you include (or require) a php script X into another php script Y, Y will have acces to all X datas and functions. You could also use sessions like #sanki commented.
Here are some links that could be useful for you:
include
require
Sessions
Pass data as GET parameter
<?php
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
echo $str;
header("Location: script.php?data={$str}");
}
?>
But this will make script.php run immediately after current file.
you can do
`php script.php $str`;
to invoke script.php with your string as a command line argument.
http://php.net/manual/en/language.operators.execution.php

Echo (or display errors) after page reload

My latest idea which didn't seem to work was to store the array in a session,
include_once "scripts.php"
.........
//some code later
$errorlog .= "a random message<br/>";
$_SESSION['errorlog']=$errorlog;
reloadPage();
And then if 'errorlog' wasn't empty then display it,
[code]
<div class="randomclass">
<?php
displayErrors('errorlog');
?>
</div>
//here are the functions
function reloadPage(){
Header('Location: '.$_SERVER['PHP_SELF']);
}
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
[/code]
scripts.php
<?php
if(!isset($_SESSION)) session_start();
........
I have included scripts.php which starts with if(!isset($_SESSION)) session_start();.
I'm new to php, still making my first webpage (or actually, preparing scripts for it). I can't seem to successfully find bugs in my scripts because I don't know how to show the errors after a page reload is needed.
What I want, is a way to store strings like in this $errorlog and display it just like an echo(in div or whatever) after the page was reloaded
I don't get any errors with headers, the page reloads correctly but the problem is that no text is displayed after the page reloads, so I don't see why I shouldn't be using them unless you know another way to reload the page after script is done
surely this way is not the best one, but I think that the problem is very easy..
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){ // here you must put a variable $valuename instead a simple string 'valuename'
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
You must change the session key at this row whit: $_SESSION[$valuename]
if(!empty($_SESSION['valuename'])){
The correct function is the follow:
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION[$valuename])){
echo $_SESSION[$valuename];
unset($_SESSION[$valuename]);
return true;
}else{
return false;
}
}
Bye!
Marco

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

PHP - how to load HTML files? [duplicate]

This question already has answers here:
Is it possible to include an html file inside a php file
(3 answers)
Closed 9 years ago.
At the moment I have a file like this
<?php
if(some condition)
{
//Dont allow access
}
else
{
echo "<html>My HTML Code</html>";
}
?>
But I wanted to do something like this to keep my php file short and clean.
<?php
if(some condition)
{
//Dont allow access
}
else
{
//print the code from ..html/myFile.html
}
?>
How can I achieve this?
save your html content as seperate template and simply include it
<?php
if(some condition)
{
//Dont allow access
}
else
{
include ("your_file.html");
}
?>
OR
<?php
if(some condition)
{
//Dont allow access
}
else
{
readfile("your_file.html");
}
?>
readfile is faster and less memory intensive than file_get_contents
you may have a look at PHP Simple HTML DOM Parser, seems a good idea for your needs! Example:
// Create a DOM object from a string
$html = str_get_html('<html><body>Hello!</body></html>');
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');
Use this code
if(some condition)
{
//Dont allow access
}
else
{
echo file_get_contents("your_file.html");
}
OR
if(some condition)
{
//Dont allow access
}
else
{
require_once("your_file.html");
}
Extending nauphal's answer for a more robust solution..
<?php
if(some condition)
{
//Dont allow access
}
else
{
if(file_exists("your_file.html"))
{
include "your_file.html";
}
else
{
echo 'Opps! File not found. Please check the path again';
}
}
?>
Use functions like
include()
include_once()
require()
require_once()
file_get_contents()
<?php
if(some condition)
{
//Dont allow access
}
else
{
echo file_get_contents("your_file.html");
}
?>
This should do the trick
Or, as nauphal's answer say, simply use include()
Don't forget that, if file doesn't exists, you could have some trouble (so, maybe, check before include or getting content)
I think you want to include your HTML file or have I misunderstood the question.
<?php
if(some condition)
{
//Dont allow access
}
else
{
include ("..html/myFile.html");
}
?>
Way 1:
ob_start();
include "yourfile.html";
$return = ob_get_contents();
ob_clean();
echo $return;
Way 2:
Use templaters, like CTPP, Smarty, etc...
Templaters are useful to transfer some logic from php to template, for example, in CTPP:
$Templater -> params('ok' => true);
$Template -> output('template.html');
in template html:
<TMPL_if (ok) >
ok is true
<TMPL_else>
ok not true
</TMPL_if>
The same ideas are in other templaters.
Templaters are better, cause it helps you to standartize your templates and send all primitive logic to them.

Categories