Including not working , is it too many includes? - php

Hi StackOverFlow members.
I need a favor regarding my programming script.
I'm stunned trying out different various ways to make my code more simpler.
Before I tried to make things simpler . The code works great and it able to do the function.
Here goes:
Detection PHP which worked on a HTML previously before I tried to tweak it a little:
<?php
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
if ($detect->isMobile()) {
header('Location: http://facebook.com');
exit(0);
}
?>
<b> Testing / This is not a supported page for mobile </b>
This code works like a charm. When I'd use the browser to access the following page.
It shows me the message "Testing / This is not a supported page for mobile ".
When I'd used a mobile phone to access it , it works like a charm and redirect me back to Facebook.
So this is the new problem that I faced .
I just removed the PHP from the HTML and put it in a file called "detection.php"
<?php
include 'detection.php';
?>
<b> hello </b>
<p> testing on anarchy </p>
But this time , when I used the web browser to access the site , it showed me the message
"Testing on anarchy" and when I used the mobile as well. It still redirect me to the same page
"Testing on anarchy".
How do we make it in a way where you just need to include the PHP files on the HTML header rather than writing the PHP code on the HTML page.
Any idea?

Try Using: you have to use the brackets ('page');, and you should not repeat any code as you are already calling the code from another page, so all you add is:
<?php
include('Mobile_Detect.php');
?>
and on the mobile_detect.php page add:
<?php
$detect = new Mobile_Detect();
if ($detect->isMobile()) {
header('Location: http://facebook.com');
exit(0);
}
?>

Always use "require" instead of "include".
"require" throws a Fatal Error if the function doesn't find the file, and the script is halted.
"include" throws a Warning if the function doesn't find the file and the script continue to run, which means that you might not notice this bug if you turned off the PHP errors.
Also rely on "require_once" to avoid problems such as "Cannot redeclare function" or "Cannot redeclare constant" etc.
Also, if you're using "header()" you need to make sure you're not using "print" or "echo" prior to the "header" function. Otherwise, you'll get the "headers already sent" error.
To debug your problem, you should use "require_once" and then you should check if it fails. If it fails, then you probably have a problem with your path.

Related

What is _once's true meaning in file manipulation?

I have a doubt that makes me very confused, it's about require_once. I saw a question on StackOverflow about it but I'm still not sure I understand...
I know the difference between require and include is that using require, the script will issue a fatal error and stop execution, while include does not. But there is something that I have been asking myself, the true meaning of _once, most people say something like: PHP will check if the file has already been included, and if so, not include (require) it again. How will the script be required only once? I don't understand this, because in my point of view PHP scripts are not like CSS that our browser downloads and is saved on the machine, so then not needing to download again, I think that every time a PHP script is executed, it will do its job again, there is no way to understand that it has already been required just as browsers understand that we have already downloaded CSS files.
What is the real meaning of _once? And could someone please give me an example, because I don't really understand it, I'm a beginner, I don't even know if I'm asking a proper question
If possible demonstrate some code so that I finally understand
Imagine this scenario. It's nice to be able to include the same file as you can use it multiple times with different outcomes:
display.php
echo $var;
index.php
$var = 'Hello ';
include('display.php');
$var = 'World ';
include('display.php');
This outputs:
Hello
World
However, sometimes this will cause problems. This could be an include in different files, so you need to include_once, but to illustrate:
functions.php
function display($var) { echo $var; }
index.php
include('functions.php');
display('Hello ');
//more code
include('functions.php');
display('World ');
Generates a fatal error:
Fatal error: Cannot redeclare display() (previously declared in index.php:1) in index.php on line 6
So if you have hundreds of files and some include others depending on some logic/program flow but some files can only be included once (as seen above) then that is the use case.

php require_once modify the local variable?

In my web page, I wrote:
<?php
//define('__PUBLIC__', $_SERVER['DOCUMENT_ROOT'].'/public');
$doc_public = $_SERVER['DOCUMENT_ROOT'].'/public';
echo "Before include...<==============>$doc_public";
?>
<?php require_once($doc_public.'/inc/head.php'); ?>
<?php echo "After include...<==============>$doc_public"; ?>
And the page shows:
This firstly happened when I notice the fatal error in the footer, but the head is fine.
Although I can implement define or constant variable to avoid this, I am still curious how it happens.
P.S.: I run this under Apache with a port 8001. This is set in 【apache\conf\extra\httpd-vhosts.conf】. I am running more than one webapp under this site. I just share this information, as I am not sure this has anything to do with this case.
Thanks!
When you require a file, if a variable is modified it affects the original script as well, that's how it's designed. Require doesn't create a secondary environment separated from the including file, it just adds the PHP code in sequence, exactly like if you had written the code in the initial file.
Have a look at the official PHP documentation, the first example is exactly the same as your case
http://php.net/manual/en/function.include.php
(include is the same as require, the latter just throws an error. For more info about differences between include and require http://php.net/manual/en/function.require.php)

PHP include working, include header is not

So I've tried looking around in other questions, but can't seem to find a question consistent with my problem.
What's going on is that I have been working on a project using angularjs, and primarily working on pure html for most of the development, and am finally at a stage where I want to cut out the header/footer code and bring it in as php with includes.
However, include("../Includes/header.php"); is not working. Other includes with basic code seems to be working okay. Here's my code:
<?php
//require_once ("Includes/simplecms-config.php");
//require_once ("Includes/connectDB.php");
include("./svg.php");
include("../Includes/include.php");
echo "<i>This is an echo from the current file.</i><br />";
include("../Includes/header.php");
?>
This is the code from ../Includes/include.php:
<?php
echo "<b>This is an included echo from another directory.</b><br />";
?>
the .svg.php file is irrelevant, just some svg graphics I use. If I move the include header ABOVE the echo, then nothing shows up. If I have it below (like it is in the code above), the echo commands work, but everything stops after the include header.
There are no errors that I can seem to find, no warnings, no nothing...just not outputting anything past that specific include.
(Working with Microsoft WebMatrix if that is even remotely relevant)
This might be a shot in the dark but in general it's best practice to leave the closing ?> off of php-files. I don't see how that could affect including a file, but I also don't see anything else "wrong" with your code.

Call to undefined function from another php file

Alright this is what my code looks like
index.php
require_once($WebsiteRoot . "/include/testfile.php");
TestFunction();
/include/testfile.php
function TestFunction()
{
echo "It Works";
}
And it gives me the error:
Fatal error:
Call to undefined function TestFunction() in /path/index.php on line 49
Any idea what i'm doing wrong?
Thanks
You haven't included a <?php tag in the included file, so it's just interpreted as plaintext input.
Remember... there's no such thing as a PHP script. There's only files which contain PHP code blocks. Without at least one <?php opening tag, the PHP interpreter will never be invoked and the file's contents will simply be treated as output.
try calling another function from testfile.php, if this is'nt working, its something with the include. Add the code:
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
to the top of index.php and refresh the browser to see your errors, try debugging from there.
The problem that i can forsee is that you are using a URL instead of a path, your $websiteRoot variable should contain a path like:
$websiteRoot = "/var/www/html/websiteName";
OR
$websiteRoot = "C://xampp/htdocs/websiteName";
instead of a URL like:
$websiteRoot = "http://www.somesite.com";
I had a similar issue. I dug into the PHP in the included file and found an invalid PHP tag. I had <? instead of <?php. PHP 7.2 and earlier forgave that, but PHP 7.3 was throwing that same error you faced.
Make sure you're including the file you think you are. If your index.php page looks exactly like you've stated, then it won't return anything.
If you want to link to the same location from anywhere on the site without worrying about relative locations, then at the beginning of the file, put:
$WebsiteRoot=$_SERVER['DOCUMENT_ROOT'];
And it should work fine, provided your file would be located at http://mywebsite.com/include/testfile.php
Try renaming the included file.
I had an included file with the name "system.php". It looked as if the include command was just skipped. Even with the most strict error reporting there was no message and even an echo command in the main body of the included file did not produce output. It had worked ok under PHP 5 but after the upgrade to a 7.2 environment these problems arose. After much effort - I forgot how - I managed to get an error message. It said there was a conflict with a PEAR class with the name "system". Yet my file didn't contain any class, just variables and functions. Anyway, giving the file another name than "system.php" worked for me.
I hope someone else can add a more technical comment on what was going wrong here.

Ajax issues, Invalid JSON

I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.

Categories