Get Url Source Html with enabled JavaScript in PHP [duplicate] - javascript

I've got this piece of code, which should fetch the source code of the website.
$homepage = file_get_contents('http://homepage.com');
echo $homepage;
Instead of actually giving me the source code.. It's shows me the page that I'm trying to get the source code from.

Either use htmlentities or change the content type.
$homepage = file_get_contents('http://homepage.com');
echo htmlentities($homepage);
or
header('Content-type: text/plain');
$homepage = file_get_contents('http://homepage.com/');
echo $homepage;

Try this, using htmlspecialchars:
$homepage = file_get_contents('http://homepage.com');
echo htmlspecialchars($homepage);

That's because you're fetching the source code and (re)outputting it. Your page is just mirroring http://homepage.com.
To see the actual page source, add a Content-Type header before your echo statement:
header('Content-type: text/plain');
This tells the browser treat the source as plain text and not interpret it as HTML.

It's because you are printing the source, your browser will interpret that as a webpage. To see the actual code use:
echo htmlspecialchars($homepage);

Related

PHP echo plain text

I am working on an AWS Elastic Beanstalk and using php on it.
But when I try to echo some html / javascript text, it just get print me plain text !
Here's an example :
<?php
public function testing (){
echo "<h1>Hello World !</h1>";
}
?>
Gives me this.
For information I am working with an api, and my testing function is called on http://xxx.eu-west-1.elasticbeanstalk.com/test/lavachart
I really can't understand why the html / javascript code isn't interpreted.
Thanks for answers
<?php
header('Content-type:text/html; charset=UTF-8');
public function testing (){
echo "<h1>Hello World !</h1>";
}
?>
for example you need response right content type for your php script, if this html then content type text/html. But you can have not right configuration server.
you can just adding mime for php in you .htaccess file or virtualhost configuration
AddType text/html .php

Calling Javascript function in an external file through php file?

Javascript code (In another file in the same directory):
function js(str)
{
alert(str);
}
PHP code(in current file):
<?php
echo '<script type="text/javascript" src="C:\xampp2\htdocs\ARD\call_jsfunc_diff_page.js"> </script>';
echo '<script>js("hello!!")</script>';
?>
I have checked on many links on the internet, i think i'm doing the right way, but the javascript function js(str) doesn't get called !!
Can somebody help me please ??
Before you edited the question: You called the function js but you are trying to call the func function.
Access to local hard disks is also problematic. Use a relative URI and access the .js over HTTP instead.

PHP: Outputting the system / Shell_exec command output in web browser

I tried to output a simple ping command on a web page in a similar way( and same time) as it is displaying in terminal, using shell_exec; But it is displaying only after the complete execution, while I needed it to display whenever it is displaying on terminal, My code is
<?php
$i= shell_exec("ping -c 4 google.com");
echo "<pre> $i <pre>";
?>
It is waiting for a while and the dumping the whole thing on a single shot.. can PHP recognize the outputting of each line and display it on the web page
EDIT I tried this also
<?php
$proc = popen("ping -c 4 google.com", 'r');
echo '<pre>';
while (!feof($proc)) {
echo fread($proc, 4096);
}
echo '</pre>';
?>
But still I gets the same result..
EDIT When I tried to execute this PHP code in terminal , ( php test.php) it is working properly in the same way it gives when we directly do ping on server. but in web page it is still the same.
Uhm, strange behavior from the web browser. I'm using this code:
<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
function pingtest()
{
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc))
{
echo "[".date("i:s")."] ".fread($proc, 4096);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<pre>
Immediate output:
<?php
pingtest();
?>
</pre>
</body>
</html>
In the browser the content appears after all bytes has been received.
But, the content is actually delivered on time, do this test:
wget -O - -q "http://localhost/ping.php"
You will see that the response is delivered by php & apache2 on time.
I'm using this kind of execution on long task for a while, but using a more complex solution:
an html file for interface
a php file that run the long task
Connect html interface with php long execution using EventSource object (available on html5)
interface (test.html)
<!DOCTYPE html>
<html>
<head>
<title>Simple EventSource example</title>
</head>
<body>
<script type="text/javascript">
function eventsourcetest() {
var ta = document.getElementById('output');
var source = new EventSource('test.php');
source.addEventListener('message', function(e) {
if (e.data !== '') {
ta.value += e.data + '\n';
}
}, false);
source.addEventListener('error', function(e) {
source.close();
}, false);
}
</script>
<p>Output:<br/><textarea id="output" style="width: 80%; height: 25em;"></textarea></p>
<p><button type="button" onclick="eventsourcetest();">ping google.com</button>
</html>
Server Side Component (test.php)
<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function echoEvent($datatext) {
echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
}
echoEvent("Start!");
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc)) {
echoEvent(fread($proc, 4096));
}
echoEvent("Finish!");
Put both files in one place on a webserver and enter test.html, I think this is what you are looking for from the beginning.
Use output buffering and flush. You might also want to look into the Symfony 2 process component.
Its not a PHP matter, or rather its a shared matter between php and the browser.
In PHP: Make sure output buffering is off, you can do this by running ob_end_clean() before outputting anything.
As this SO post suggests you have to either pad the very first string outputted to 512 bytes OR specify a charset encoding via http header. The padding solution may very well be the easiest way around this, its basically this: echo(str_pad("Live Ping Test!",512)); and then start echoing the result of your fread.
You might want to try using flush() to flush the output as and when its ready, and use passthru() to execute the command.
Carlos C Soto is right, you have to use javascript. EventSource is the way to go. Basically, it's javascript code that will constantly call a url
You can write the output of ping in a file, and write a php script that will read the last line, then call this script with eventsource.
Search "Server Sent Events" on the web to find more examples
if can resolve using apache execution user. if your root user is diffrent and server user different then it will not allow to execute command line command.
I tested Carlos's answer on my side...
and I HAD to add flush();ob_flush(); for it to work properly (both needed flush AND ob_flush)
like this
<?php
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc))
{
echo "[".date("i:s")."] ".fread($proc, 4096).'<br>';flush();ob_flush();
}
?>

Getting PHP variable in Javascript code

I'm trying to use PHP variables in Javascript but I couldn't. After over 2000 lines of writing different JS functions I was fine avoiding that but now I really needed it. I'm a bit lost on all the ways to go about this but nothing really worked. Here is my sequence:
index.html file:
...
<script src="myfunctions.js" />
....
myfunctions.js file:
....
function test() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
I was trying to rename the .js file into .php file and add
header("Content-type: text/javascript");
at the beginning - that didn't work. I was trying to make .htaccess file with
AddType application/x-httpd-php .js
But that didn't work either. I'm probably missing just a tiny thing. I just need someone fresh and bright to point it out.
You can do something like this within your JS code.
var php_var = "<?php echo $_conf['user_id'];?>"
Your javascript file should be named as "javascript.php" (just put the name you want, the only important thing is the .php
You have an index.php
Write in your index.php
include("javascript.php");
Then in your javascript.php
<script>
function test(){
var variable = "<? echo $conf['user_id'] ?>";
alert(variable);
}
<script>
PS: Yo don't need any header.
Since you're doing this via a <script> tag, your PHP script MUST output valid Javascript code, as if you'd literally type your variable assignment in manually. That means doing something like:
HTML/JS:
<script src="myscript.php"></script>
PHP:
<?php
$myvar = 'foo';
?>
var myvar = <?php echo json_encode($myvar); ?>;
Which in the end, will produce somethign that will function exactly as if you'd manually typed in the following:
<script>
var myvar = 'foo';
</script>
Note the use of json_encode(). Using this ensures that whatever you're outputting from PHP will become syntactically valid Javascript.
You're not assigning PHP value to a Javascript variable. Try:
var v = "<?php echo $_conf['user_id'];?>";
index.html
..
<script src="myfunctions.js.php" />
...
myfunctions.js.php
<?php
header('Content-Type: text/javascript');
...
?>
var val = <?php echo json_encode($val); ?>;
...
Other possible solution is to assign server-side data to attributes in html and read them in javascript. For example index.html could contain something like this:
<div id="user-profile" data-user-id="<?php echo $conf['user_id']; ?>"></div>
and in js file you can get them while necessary(example with jQuery):
var userID = $('#user-profile').attr('data-user-id');
Of course you should adjust your server-side settings to process html files.

Including php file as JS

I am trying to change the image_list_url of tiny_mce to php file.
I changed the url to image_list.php file. It generated the exact output text same as the js file.
But even after giving same output it doesn't show's the image list.
I am wondering if the content-type is affecting it or not?
my JS file content:
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system.
// There images will be displayed as a dropdown in all image dialogs if the "external_link_image_url"
// option is defined in TinyMCE init.
var tinyMCEImageList = new Array(
// Name, URL
["Logo 1", "media/logo.jpg"],
["Logo 2 Over", "media/logo_over.jpg"]
);
my PHP COde:
<?php
require('../../../system/config.php');
$strPath = APP_ROOT.DS.'sys_uploads/images/';
$objFileList = dir( $strPath );
$arrFileList = array();
while (false !== ($entry = $objFileList->read())) {
if( is_file( $strPath.$entry) )
$arrFileList[] = array($entry, ABS_URL.'/sys_uploads/images/'.$entry);
}
$objFileList->close();
header('Content-type: application/x-javascript');
//header('Content-type: text');
?>
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system.
// There images will be displayed as a dropdown in all image dialogs if the "external_link_image_url"
// option is defined in TinyMCE init.
var tinyMCEImageList = new Array(
// Name, URL
<?php
if( count( $arrFileList )>0 )
foreach( $arrFileList as $dataRow ):
?>
["<?php echo $dataRow[0];?>", "<?php echo $dataRow[1];?>"],
<?php endforeach; ?>
);
my PHP Output:
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system.
// There images will be displayed as a dropdown in all image dialogs if the "external_link_image_url"
// option is defined in TinyMCE init.
alert('test working or not');
var tinyMCEImageList = new Array(
// Name, URL
["Logo 1", "media/logo.jpg"],
["Logo 2 Over", "media/logo_over.jpg"]
);
Edit:
As per suggestion i even added a popup message too which even didn't show up.
Solution:
dun know what was error on my code but found good solution from link suggested:
http://tinymce.moxiecode.com/wiki.php/Configuration%3aexternal_image_list_url
As both the .js and your PHP file outputs are identical, there should be no difference. text/javascript is the most widely supported mime type for JS, so using that might help.
It would also not hurt to name your dynamically generated JS files using a convention such as XYZ.php.js and using mod_rewrite to parse the php.js files as php.
Edit:
Also, per official TinyMCE docs, please make sure that there is no whitespace before the <?php opening tag in the dynamically generated JS, also check for UTF8 BOM which can be a sneaky cause of invisible output.
No need to change any headers. Just output the JavaScript.
js.php: alert("Working!")
test.htm: <script type="text/javascript" src="js.php"></script>
When I loaded test.htm, I got an alert box
This is definitely a problem of incorrect header type.
could you please change the line
header('Content-type: application/x-javascript');
to
header('Content-type: application/javascript');
As application/x-javascript is not a correct javascript header. Tell me if this thing helps

Categories