file_put_contents stops my code from executing - php

I want to send some data as a GET request to my php page (submit.php) and save it in a local file. I have:
$loc = 'data.txt';
if(isset($_GET["data"])) {
echo 'set';
file_put_contents($loc, $_GET["data"], FILE_APPEND);
}
echo 'foo';
But when I access submit.php?data=bar, nothing happens to data.txt; moreover, echo 'foo' does not seem to execute. Why is this?

echo 'foo' does not execute because file_put_contents() encounters an error and the execution stop.
Put error_reporting(E_ALL & ~E_NOTICES); ini_set('display_errors', '1'); in front of your script to let PHP display the errors on screen.
This way you can find that, I guess, the process that runs the PHP code (the web server probably) does not have the rights to write in the directory where you store the code.
Change $loc to '/tmp/data.txt' and it will work.
Or, even better, create a new directory, set its permissions to rwx for everybody and change the code to write files in it.

Related

Calling included remote functions and variables

I'm trying to include a remote file from one of LAN pcs using include, allow_url_fopen = On and allow_url_include = On.
One local PC (let's say pc2), I have remote.php, which contains:
<?php
echo $var_on_pc1; // this doesn't output
$remote_var = 'Var on pc2';
function square($num){
return $num * $num;
}
?>
In my PC (let's say pc1), I have test.php, which consists of this:
<?php
$var_on_pc1 = 'Var on pc1';
include "http://pc2/path/to/remote.php";
echo $remote_var; // this doesn't output
echo square(4); // this got error
?>
When I run the script test.php, i got the error:
"Fatal error: Call to undefined function: square() in
path/to/test.php on line 7.
What happened? I thought I could call the included functions and variables and vice versa?
If I cannot implement this, what is the best way?
I have no security concern because I use this locally for temporary development.
Type http://pc2/path/to/remote.php into your browser and see what you get. PHP gets exactly the same.
If the PHP file is being processed by the web server at pc2, you likely get zilch in that file, because the code as been processed. You'd need to configure the other server to not process the PHP file and serve its raw source code instead.
This is not a good idea overall.

importing files in php using require() not working

i tried the following code to import two files
<?php echo "php";
require('../globalvasr.php') or die("error");
require('../newcosn.php') or die("error2");
$config = new GlobalConfigs();
?>
It does not shows error and it just simply displays a blank page.Also i am unable to use the variable defined in those two files.
Like $config->DBNAME.
I dont know whats wrong in this.
Please help me find it.
Thank you.
require, in contrast to include, automatically dies and does not have a return value.
This means the or die() is bad. Better:
<?php echo "php";
require('./globalvasr.php');
require('./newcosn.php');
$config = new GlobalConfigs();
?>
Require generates a fatal error when require fails, causing the script execution to stop immediatly.
As you seem to be running in a web env, your output (all echo or print statements) is buffered until the end of the script.
So here the require fails, causing a fatal error (that should be available in the error log) before the output buffer is emptied, preventing your first "echo" to be sent to the browser. that's why you get a blank page.
Try replacing the require with an include, you will get a warning instead of the fatal error.
if you have blank page, set error_reporting: E_ALL and Display_errors: On in php.ini or put on start of your script these lines
error_reporting(E_ALL);
ini_set('Display_errors','On');
then you will see errors

Display script result first on browser then run include file in php

I have a script that shows a result done then i call an include file to run at intervals. I would like the script result to display on browser then include file will run in the back. Right now my browser is connecting but showing nothing.I would like the browser echo Done and Logging.
<?php
ob_implicit_flush(true);
require_once('syslog.php');
$syslog = new Syslog();
$line="My msg";
$hostname = gethostname();
$ip= #$REMOTE_ADDR;
$hostnameip = GetHostByName($ip);
$syslog->Send('127.0.9.1', $hostname." ".$hostnameip." ".$line);
echo"Done";
echo "Logging......";
ob_end_flush();
include('execute.php');
?>
I believe you'll be able to get what you want by calling the flush() method right after your echo commands.
The flush() function is described as -
Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.
There are some special considerations when using this function. Certain apache modules and client side buffering will still be enforced, but for now however, I do believe this will help.
Try flush() before include after last echo.

PHP exec() re-executing same script again and again

Here I am writing about my flow in detail.
I am doing an Ajax request on same host.
AJAX call to saveUser.php
in saveUser.php, I have included Common.php.
Common.php have createFile1() and createFile2() function.
createFile1() function just creating a sample1.php for another purpose.
in createFile2(), I am creating a file sample2.php and executing a exec('php /home/public/sample2.php > /dev/null &'); command to execute that file.
I am calling this createFile1() and createFile2() function respectively from saveUser.php which is being called by an AJAX request.
As I have set the exec command to run in background by '&' at end of command, it is returning without waiting for the response and all goes smoothly in front.
But when I am checking on my server, these files sample1.php and sample2.php are getting created again and again. It seems all this saveUser.php action are getting executed again and again until I stops the sample2.php process from SSH.
I checked the processes list, each time 'php /home/public/sample2.php' is having new process_id, so it confirms that it is getting executed again and again. If I remove the exec() code and execute this sample2.php from SSH, it works as expected, there is not such problem.
Please suggest me whats going on wrong? Is there any problem with server configuration, I am using hostgator shared account.
Also I am including same Common.php file in sample2.php also, informing in case it can help it.
Thanks for your help in advance.
saveUser.php code
include_once dirname(__FILE__).'/Common.php';
createFile1();
createFile2();
echo 'saved successfully!';
Common.php code
function createFile1()
{
$template = file_get_contents('sendDmTemplate.php');
$serviceFp = fopen('sendDmFiles/sample1.php',"w");
fwrite($serviceFp , $fileContent);
fclose($serviceFp);
}
function createFile2()
{
$fileContent = file_get_contents(dirname(__FILE__).'/sampleFileTemplate.php');
$serviceFp = fopen('sample2.php',"w");
fwrite($serviceFp , $fileContent);
fclose($serviceFp);
exec('php '.dirname(__FILE__).'/sample2.php > /dev/null &');
}
sample2.php code
include_once dirname(__FILE__).'/Common.php';
echo 'hi';
This exact same thing happened to me. I was trying to have one php script call exec() on another php script but for some strange reason it would just exec() itself again creating an infinite loop. The currently accepted answer didn't get me anywhere, but I was able to get it to work by specifying an absolute path to php.
So, instead of
exec('php /home/public/sample2.php > /dev/null &');
it would be
exec('/usr/local/bin/php /home/public/sample2.php > /dev/null &');
Check the following:
1) Are you sure you are NOT calling your script saveUser.php multiple times? Mayby a codingerror somewhere in the javascript XHR? Check this by looking in the (apache?) log.
2) Are you sure your php executes alright without the -q? I use php -q pathtoscript.php
3) If not 1 or 2: Post the code in here (or somewhere) of saveUser.php
EDIT: I see your problem. The file you create includes common.php again, and executes that again. Etc. <-- wrong Oops. I wrote that too early. Looking into it again now.
4) Is it possible you use some errorhandling that redirects to your saveUser.php?
Edit:
5) There might arise a problem from the fact that you are including the file that is executing the command itself in combination with include_once, but I am not sure. You could simply test this by changing your content of sample2.php content by adjusting sampleFileTemplate.php. Create a common2.php (with identical content as common.php), and use that one. COuld you testdrive that setup and report back?

Calling php from php through exec() gives no result

I have a PHP script that creates other PHP files based on user input. Basically, there are files containing language specific constants (define) that can be translated by the user. In order to avoid runtime errors, I want to test newly written files for parse errors (due to "unusual" character sequences). I have read several posts here on SO (like PHP include files with parse errors) and tried a function that uses
$output = exec("php -l $filename");
to determine whether a file parses correctly. This works perfectly on my local machine, but at on the provider's machine, the output of calls to exec("php ...") seems to be always empty. I tried a call to ls and it gives me output, leading me to the assumption that PHP is somehow configured to not react to command line invocations or so. Does anyone know a way around this?
EDIT: I forgot to mention, I had already tried shell_exec and it gives no result, either. In response to sganesh's answer: I had tried that too, sorry I forgot to mention. However, the output (second argument) will always be an empty array, and the return value will always be 127, no matter if the PHP file to test has syntax errors or not.
I had the same problem. The solution that worked for me was found in running-at-from-php-gives-no-output. I needed to add output redirection.
$output = exec("php -l $filename 2>&1");
You can try with exec second and third arguments.
second argument will have the output of the command.
third argument will have the return value.
And exec will return only last line of the command.
$filename = "a.php";
$output = exec("php -l $filename",$op,$ret_val);
print $output."\n";
print $ret_val."\n";
var_dump($op);
By executing shell_exec(), you can see the output as if you executed that file via command line. You can just see if there is an error right here.
<?php
if (strpos(shell_exec('php -l file.php'), 'Syntax Error')) {
die('An error!');
}
There may also be a possibility that shell_exec() or exec() may be disable by your host.
Nice idea to check the file validity :-)!
Now, from the PHP manual for exec():
Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have components in the path to the executable.
Can you check if this is not the case for you?
Also, can you check by providing the full path of the PHP interpreter in the exec() instead of only php. Let me know how you fare.
Pinaki
the correct way is to add >2&1 as tested on a windows system using imagemagick!
I worked around my original problem by using a different method. Here is what I do now:
Write a temporary file with contents <?php include "< File to test >"; echo "OK"; ?>
Generate the correct URL for the temporary file
Perform HTTP request with this URL
Check if result equals "OK". If yes, the file to test parses without errors.
Delete temporary file
Maybe this could be done without the temporary file by issuing an HTTP request to the file to test directly. However, if there is a parse error and errors are suppressed, the output will be empty and not discernible from the output in the case of a file that gives no parse errors. This method is risky because the file is actually executed instead of just checked. In my case, there is only a limited number of users who have access to this functionality in the first place. Still, I'm naturally not entirely happy with it.
Why the exec() approach did not work, I still do not know exactly. pinaki might be right by suggesting to provide the full path to the PHP executable, but I cannot find out the full path.
Thank you everyone for answering, I upvoted you all. However, I cannot accept any of your answers as none of your suggestions really solved my problem.

Categories