Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to stop including a php file?

Tags:

include

php

Is it possible to stop the inclusion of a file in the middle of a file?

For example, one file would contain:

include('home.php');

and in home.php, it would try to cancel the inclusion at some point:

break; // I tried it doesn't work
echo "this will not be output

I'm not talking about an exit, which stops everything, even the root file. I just want the current file to be exited from.

like image 764
David 天宇 Wong Avatar asked Dec 08 '11 19:12

David 天宇 Wong


People also ask

How do you stop a PHP file?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script.

How do I stop a PHP script from process?

if you need to stop a script in a windows environment, there is a taskkill command that you can run at a prompt; see computerhope.com/taskkill.htm.

Do I need to end PHP file with ?>?

It's entirely optional but including it provides the opportunity to slip whitespace into the output by accident. If you do that in a file that you include or require before you try to output headers then you'll break your code.

Are .PHP files safe?

PHP is as secure as any other major language. PHP is as secure as any major server-side language. With the new PHP frameworks and tools introduced over the last few years, it is now easier than ever to manage top-notch security.


3 Answers

In place of break, use return:

return

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file.

like image 174
Tim Cooper Avatar answered Sep 22 '22 14:09

Tim Cooper


No. When you include or require. This file gets loaded and parsed entirely. It does not mean that the code in it is executed, but it is loaded entirely.

If you want to have a different flow of execution of this code, then you would need to use some of the control structures.

http://php.net/manual/en/language.control-structures.php

like image 43
Layke Avatar answered Sep 23 '22 14:09

Layke


What you can do is set a flag in the "parent" script that the included script looks for. If it's set, it'll halt execution early, otherwise it'll continue as normal.

Example:

main.php

<?php
$_GLOBAL['is_included'] = true;
include('somefile.php');
// More stuff here
?>

somefile.php

<?php
// Does some stuff

// Stops here if being include()'d by another script
if ( isset($_GLOBAL['is_included']) ) { return; }

// Do some more stuff if not include()'d
?>
like image 39
Mr. Llama Avatar answered Sep 23 '22 14:09

Mr. Llama