PHP code is displayed in user's browser - php

I have a php script like this :
<?php
$confirmationCode = trim($_GET['confcode']);
$_SERVER['REMOTE_ADDR'] = 'xxx.xxx.xxx.xxx';
$emailLogId = 1;
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>' .'xxxxx' . $emailLogId . '###'; //exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
It is running on my server. Actually some people are complaining that they are seeing the source code of this script( pasted below ) on their browser and they send me snap shot of this issue:
' .'xxxxx' . $emailLogId . '###'; //exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
Actually I am really confused because I am not able to reproduce this problem, but 3-4 people are complaining about same the thing.
Do you have any idea what is the issue?

Yes, similar thing happened with me too.
2 things:
. Apache configuration.
Make sure php engine is ON. If you cannot access your apache configuration file then, add this in your .htaccess:
php_flag engine on
. CDN.
If you are using any Cloud Distribution Network, it is time for you to ask them to purge your existing cache and re-load the new one.
Browser will display PHP source code ONLY AND ONLY if apache configuration is going wrong.
Hope that helps.
EDIT:
After reading Sabin's comment, I gave a second look at the code.
Problem is, he has ASSIGNED the value to $_SERVER['REMOTE_ADDR'] (line 3)
Here is how it should be:
<?php
$confirmationCode = trim($_GET['confcode']);
$ip = 'xxx.xxx.xxx.xxx';
$emailLogId = 1;
//Whatever conditions.
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') {
// print '<pre>' .'xxxxx' . $emailLogId . '###'; exit ;
}
if( is_numeric($emailLogId)) {
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') {
// print '<pre>yyy' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
//$osDB->query('UPDATE ! SET clicktime=? WHERE id=?', array('email_logs', time(), $emailLogId));
} else {
if ($_SERVER['REMOTE_ADDR']=='xxx.xxx.xxx.xxx') {
// print '<pre>zzz' . $_GET['emaillog_id'] . 'yyyxxxxxx ' . $emailLogId; print_r ($row) ; exit ;
}
}
?>
However, echo-ing the source code cannot be due to this. I would ask you to put FULL FILE so that we could see if you are missing a closing single quote!

It sounds like PHP is not working at all. The only reason you are not seeing the first part, is because your browsers is parsing it as if it were an HTML tag.
And Please try to print phpinfo() once,
please check for the below link, for more details
PHP code displayed in browser

Related

SSE not logging disconnect

I currently have a simple SSE page for testing. I can currently get the page to log when a user connects and while they are connected; however, when the page closes it seems (eg user disconnects) it doesnt log anything. I am using the function error_log for logging. Also, using NGINX and PHP 7.2. Here is my code:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
ignore_user_abort(true);
$aid = 1;
function sendMsg($id , $msg) {
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode(array('x'=> $msg)) . PHP_EOL;
echo "retry: 0" . PHP_EOL;
echo PHP_EOL;
#ob_end_flush();
flush();
}//END FUNCTION sendMsg
function endPacket() {
echo "0\r\n\r\n";
#ob_end_flush();
flush();
}//END FUNCTION endPacket
$startedAt = time();
error_log("Starting SSE to User: " . $aid);
while (true) {
set_time_limit(15);
if ( connection_status() != 0 ) {
error_log("Ending SSE to User: " . $aid);
endPacket();
die();
}//END IF
error_log("Connected SSE as User: " . $aid);
sendMsg( $startedAt, $aid . ' | ' . connection_status() );
sleep(10);
}//END WHILE
Your code is failing to detect a disconnect because you need to write to the user before you can detect a disconnect
While it looks like your demo code does this, it actually doesn't. This is what your code does now:
detect_connection();
sendMsg();
sleep();
detect_connection();
sendMsg();
<timeout>
The only way in your example to trigger the connection disconnect message is if the connection is closed the first time you call "sendMsg()", what probably is not going to happen as you are not that quick

How to create a page periodically using wiki bot

My prime aim is to get a page , parse the text and create a subpage periodically depending on the text. To get a page ,create and login, i have the following code .Php version-5.3.3,server:localhost
private function login($username, $password, $wiki) {
$response = $this->postAPI($wiki, 'api.php?', 'action=login&lgname=' . urlencode($username) . '&lgpassword=' . urlencode($password));
if ($response['login']['result'] == "Success") {
//Unpatched server, all done
} elseif ($response['login']['result'] == "NeedToken") {
//Patched server, going fine
$token = $response['login']['token'];
$newresponse = $this->postAPI($wiki, 'api.php?', 'action=login&lgname=' . urlencode($username) . '&lgpassword=' . urlencode($password) . '&lgtoken=' . $token);
if ($newresponse['login']['result'] == "Success") {
//All done
} else {
echo "Forced by server to wait. Automatically trying again.<br />\n";
sleep(10);
$this->login($username, $password, $wiki);
}
} else {
//Problem
if (isset($response['login']['wait']) || (isset($response['error']['code']) && $response['error']['code'] == "maxlag")) {
echo "Forced by server to wait. Automatically trying again.<br />\n";
sleep(10);
$this->login($username, $password, $wiki);
} else {
die("Login failed: " . $response . "\r<br />\n");
}
}
}
Function to get a page is:
public function get_page($page, $wiki = "")//get page's content
{
$response = $this->callAPI($wiki, 'api.php?action=query&prop=revisions&titles=' . urlencode($page) . '&rvprop=content');
if (is_array($response)) {
$array = $response['query']['pages'];
$array = array_shift($array);
$pageid = $array["pageid"];
return $response['query']['pages'][$pageid]['revisions'][0]["*"];
} else {
echo "Unknown get_page error.<br />\n";
return false;
}
}
I have a problem with login. I always get Forced by server to wait. Automatically trying again regardless my password and id is correct. Infact the URI works properly if given manually.And if i try to create a page or get a category, i get the following error:
Cannot modify header information - headers already sent by (output started at serverlocation/Phpwikibot.php:188) in serverlocation/includes/WebResponse.php
Can some one help me with this issue?
You say "localhost", so you have server-side access and you should be using the internal PHP API, not the web API. In particular, to edit a page you can use maintenance/edit.php. See a real world example I used for some Wikimedia wikis:
#!/bin/bash
{
# Stuff
# Fetch stuff
echo -e $stuff
} | php edit.php --user "FuzzyBot" \
--bot --summary "Update stats" "Meta:Babylon/Translation_stats"

Cannot modify header information [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am getting the following error from the following code, and I am not entirely sure why. If you could tell me how to fix it, that would be great. Thanks in advanced.
Warning: Cannot modify header information - headers already sent by (output started at...) on line 45.
<?php
// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$ref = isset($_GET['ref']) ? $_GET['ref'] : "";
// Protect against sql injections
// Insert the score
$retval = mysql_query("INSERT INTO $table(
site
) VALUES (
'$ref'
)",$conn);
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
mysql_close($conn);
?>
<?php
$url = $_GET['url'];
$loc = 'Location: '. $url;
header($loc);
exit;
?>
Take out the echo calls, you can't send information to the browser before the headers.
You can try something like this to still show if an error happens:
if(!$retval) {
echo "Unsuccessfull " . mysql_error();
}
If you change the headers you cannot output any text prior to to the header command otherwise the headers will already be sent.
ie.
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
Is outputting text before you change the headers.
Use Output Buffers: http://php.net/manual/en/function.ob-start.php
ob_start();
at the start and
ob_end_flush();
at the end.
What I generally recommend for situations like this, is save all output to the end, as gmadd mentioned, you can do the ob_start, but I prefer to store the data in a string without having to add the extra code (I know you can also designate this in the .htaccess file, I would go that route over adding the actual ob_start items).
What I would do:
$display = ""; // initiate the display string
// etc doe here
if($retval) {
$display .= "Successfull";
} else {
$display .= "Unsuccessfull " . mysql_error();
}
// end of the script right before ?>
echo $display;
?>
The ob_start method works and if you want to go that route, you can add this in the .htaccess file (given that allowoverride is set in your apache setup):
php_value output_buffering On
Again I still recommend the $display storage method, but that is my personal opinion.
Use:
<meta http-equiv="Refresh" content="0;url=http://www.example.com" />

PHP - IRC Bot Script Hanging

I am having problem with my IRC Bot script, I have implemented it into my Curl transfer method.
I have a problem, once the IRC bot sends a message to the IRC channel, all of the "echo" at the end of the script does not show and the page hangs. The whole Apache hangs.
<?php
$ircServer = "///";
$ircPort = "6667";
$ircChannel = "#bots";
set_time_limit(0);
$msg = $_POST['msg'];
$paper = $_POST['paper'];
$sizzor = $_POST['sizzor'];
$hand = $_POST['hand'];
$ircSocket = fsockopen($ircServer, $ircPort, $eN, $eS);
if ($ircSocket)
{
fwrite($ircSocket, "USER Lost rawr.test lol :code\n");
fwrite($ircSocket, "NICK Rawr" . rand() . "\n");
fwrite($ircSocket, "JOIN " . $ircChannel . "\n");
ignore_user_abort(TRUE); // Noob Close down page
fwrite($ircSocket, "PRIVMSG " . $ircChannel . " :" . $msg . "\n");
while(1)
{
while($data = fgets($ircSocket, 128))
{
echo nl2br($data);
flush();
// Separate all data
$exData = explode(' ', $data);
// Send PONG back to the server
if($exData[0] == "PING")
{
fwrite($ircSocket, "PONG ".$exData[1]."\n");
}
}
echo $eS . ": " . $eN;
}
}
?>
if ($bootcontents == 'success') {
echo '<center><marquee behavior="alternate" direction="left">Spinning xxx at ' . $power . '% power.</marquee></center>';
This part does not show during the script:
if ($bootcontents == 'success') {
echo '<center><marquee behavior="alternate" direction="left">Spinning xxx at ' . $power . '% power.</marquee></center>';
The page just hangs, if I add the exit(); function onto near the top the whole "echo" info does not show.
Please can someone help.
You are creating an infinite loop:
while (1)
// ...
This loop can never finish, since you did not use an exit statement (like break). Therefore the code after the infinite loop is never executed.
Furthermore is it a busy loop (using a lot of CPU resources), so the whole apache (and computer) will hang.
You're leaving some lines out of the <?php ?> tags, so whatever is outside them will be treated as plain text. You fix it moving the closing ?> tags further down:
[this is the while(1) closing bracket]
}
// code past this line will never run, see below for details
echo $eS . ": " . $eN;
}
}
if ($bootcontents == 'success') {
echo '<center><marquee behavior="alternate" direction="left">Spinning xxx at ' . $power . '% power.</marquee></center>';
}
?> <!-- closing tag goes here -->
The page would anyway not work properly because the while(1) loop is missing an exit condition:
while(1) {
while($data = fgets($ircSocket, 128)) {
// ...
}
}
After the inner while finishes, your script keeps looping, ending up trapped in an empty, infinite loop (which would hang the server up, if it's not configured to detect and kill this kind of loophole).
On a final notice, PHP isn't probably the best tool for the job: you would be much better off with a stand-alone application.
while($data = fgets($ircSocket, 128))
This part blocks the script running until it receives data, and if somehow you're not getting data through that socket... well you're stuck there... forever... lol ok, stuck until the PHP script times out.
If that part doesn't catch, you're still stuck inside the while loop and so there is no way of ever running the part of your code that echos stuff out... so both apfelbox and Alex are correct, just not explained fully...
In order to have a infinite loop but also be able to run code outside, you would need to catch the "event" in which you want to capture and run code. All the events you want to capture would need to sit inside the while loop, or at least dispatched from the while loop to a function that would parse the input from server and respond correctly.
An even better way to do this is to utilise the observer pattern.
I really wouldn't make an IRC bot with PHP, even if you run it via commandline... PHP isn't meant to run as a long-running application.

php telnet no response from script

I'm running PHP5 on Windows XP Professional. I'm trying to write a telnet php script which simply connects, sends a text string and grabs the response buffer and outputs it. I'm using the telnet class file from here:
http://cvs.adfinis.ch/cvs.php/phpStreamcast/telnet.class.php
which i found in another thread.
<?php
error_reporting(255);
ini_set('display_errors', true);
echo "1<br>";
require_once("telnet_class.php");
$telnet = new Telnet();
$telnet->set_host("10.10.5.7");
$telnet->set_port("2002");
$telnet->connect();
//$telnet->wait_prompt();
$telnet->write('SNRD 1%0d');
echo "3<br>";
$result = $telnet->get_buffer();
echo $result;
print_r($result);
// flush_now();
echo "4<br>";
$telnet->disconnect();
?>
I'm not receiving any kind of errors or response. If I send an invalid string, I should get an 'ERR' response in the least however I don't even get that. Any ideas what i could be doing wrong? If I do the same thing from the command prompt, I receive the string output I need. Could this is because the write function is sending
After some reading in the source code and on the original (french) site referred to in the header....
<?php
error_reporting(255);
ini_set('display_errors', true);
echo "1<br>";
require_once("telnet_class.php");
$telnet = new Telnet();
$telnet->set_host("10.10.5.7");
$telnet->set_port("2002");
if ($telnet->connect() != TELNET_OK) {
printf("Telnet error on connect, %s\n",$telnet->get_last_error());
}
//$telnet->wait_prompt();
if ($telnet->write('SNRD 1' . "\xd") != TELNET_OK) {
printf("Telnet error on write, %s\n",$telnet->get_last_error());
}
// read to \n or whatever terminates the string you need to read
if ($telnet->read_to("\n") != TELNET_OK) {
printf("Telnet error on read_to, %s\n",$telnet->get_last_error());
}
echo "3<br>";
$result = $telnet->get_buffer();
echo $result;
print_r($result);
// flush_now();
echo "4<br>";
$telnet->disconnect();
?>
Okay, explanation: get_buffer() does just that, read what's in the buffer. To get something in the buffer you have to execute read_to($match) who will read into buffer up to $match. After that, get_buffer should give you the desired string.
EDIT:
if you cannot find some string that follows the string you are interested in read_to will end in an error due to this part of the read_to method (translation of original french comment is mine):
if ($c === false){
// plus de caracteres a lire sur la socket
// --> no more characters to read on the socket
if ($this->contientErreur($buf)){
return TELNET_ERROR;
}
$this->error = " Couldn't find the requested : '" . $chaine . "', it was not in the data returned from server : '" . $buf . "'" ;
$this->logger($this->error);
return TELNET_ERROR;
}
Meaning that when the socket is closed without a match of the requested string, TELNET_ERROR will be returned. However, the string you're looking for should at that point be in the buffer.... What did you put in read_to's argument? "\n" like what I did or just "" ?
EDIT2 :
there's also a problem with get_buffer. IMO this class is not really a timesaver ;-)
//------------------------------------------------------------------------
function get_buffer(){
$buf = $this->buffer;
// cut last line (is always prompt)
$buf = explode("\n", $buf);
unset($buf[count($buf)-1]);
$buf = join("\n",$buf);
return trim($buf);
}
It will throw away the last line of the response, in your case the one that contains the
answer.
I suggest to add a "light" version of get_buffer to the class, like this
//------------------------------------------------------------------------
function get_raw_buffer(){
return $this->buffer;
}
and do the necessary trimming/searching in the result yourself.
You might also want to add the following constant
define ("TELNET_EOF", 3);
and change read_to like this
...
if ($c === false){
// plus de caracteres a lire sur la socket
if ($this->contientErreur($buf)){
return TELNET_EOF;
}
$this->error = " Couldn't find the requested : '" . $chaine . "', it was not in the data returned from server : '" . $buf . "'" ;
$this->logger($this->error);
return TELNET_EOF;
}
...
in order to treat that special case yourself (a result code TELNET_EOF doesn't have to be treated as an error in your case). So finally your code should look more or less like this:
// read to \n or whatever terminates the string you need to read
if ($telnet->read_to("\n") == TELNET_ERROR) {
printf("Telnet error on read_to, %s\n",$telnet->get_last_error()); } echo "3<br>";
} else {
$result = $telnet->get_raw_buffer();
echo $result;
print_r($result);
}
Have you checked how the telnet class works? Maybe it wasn't designed to run under windows. If it's a simple socket that you're speaking to, maybe consider using a regular socket-connection instead.
http://se2.php.net/sockets
If you open up a socket which you don't close, you should se an entry in netstat as long as your script is running.
netstat -na|find ":2002"
You can't insert hex values like that. The remote process just sees
SRND 1%0d
and now it's waiting for the line to be terminated. Try this
$telnet->write('SNRD 1' . "\r");
or
$telnet->write("SNRD 1\xd");
The double quotes are quite critical, see here
EDIT:
you might try adding some error reporting as right now you don't really check much (error_reporting won't show anything on the errors in the telnet class).... For example:
<?php
error_reporting(255);
ini_set('display_errors', true);
echo "1<br>";
require_once("telnet_class.php");
$telnet = new Telnet();
$telnet->set_host("10.10.5.7");
$telnet->set_port("2002");
if ($telnet->connect() != TELNET_OK) {
printf("Telnet error on connect, %s\n",$telnet->get_last_error());
}
//$telnet->wait_prompt();
if ($telnet->write('SNRD 1' . "\xd") != TELNET_OK) {
printf("Telnet error on write, %s\n",$telnet->get_last_error());
}
echo "3<br>";
$result = $telnet->get_buffer();
echo $result;
print_r($result);
// flush_now();
echo "4<br>";
$telnet->disconnect();
?>
also, are you sure you need \r\n line termination? write is defined as
function write($buffer, $valeurLoggee = "", $ajouterfinLigne = true){
and does
if ($ajouterfinLigne){
$buffer .= "\n";
}
?
Also, did you test the host and port with the command line telnet client? Like
telnet 10.10.5.7 2002
?

Categories