Reputation: 2821
I'm simply experimenting with PHP to prepare me for some upcoming projects and I've encountered a string which won't have <br />
inserted into it even though it is a multi-line string.
The code is simple PHP (which I've enclosed in simple html tags)
$ping = passthru('ping www.google.com');
$ping = htmlspecialchars_decode($ping);
$ping = strip_tags($ping);
$ping = nl2br($ping);
echo $ping;
The result is a multi-line string but without any <br />
tags added, however, the page source shows the result as a mutli-line string so there's definitely multiple lines there but nl2br()
is not doing anything.
Page source (which has mysteriously added extra whitespace lines when I pasted it in here)
<html>
<head>
<title>Derp</title>
</head>
<body><p>
Pinging www.l.google.com [209.85.227.147] with 32 bytes of data:
Reply from 209.85.227.147: bytes=32 time=44ms TTL=48
Reply from 209.85.227.147: bytes=32 time=28ms TTL=48
Reply from 209.85.227.147: bytes=32 time=40ms TTL=48
Reply from 209.85.227.147: bytes=32 time=29ms TTL=48
Ping statistics for 209.85.227.147:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 28ms, Maximum = 44ms, Average = 35ms
</p>
</body>
</html>
And the actual string shown on the webpage:
Pinging www.l.google.com [209.85.227.147] with 32 bytes of data: Reply from 209.85.227.147: bytes=32 time=30ms TTL=48 Reply from 209.85.227.147: bytes=32 time=29ms TTL=48 Reply from 209.85.227.147: bytes=32 time=28ms TTL=48 Reply from 209.85.227.147: bytes=32 time=31ms TTL=48 Ping statistics for 209.85.227.147: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 28ms, Maximum = 31ms, Average = 29ms
After extensive Googling all I can find is people who are not using nl2br()
when they should be
What am I missing here?
Upvotes: 2
Views: 386
Reputation: 49376
You're misunderstanding what passthru($cmd)
does. It executes $cmd
, but sends stdout
directly to the browser - you do not get the results back as a string. Instead, it returns the return code of the called $cmd
.
If you want to capture output, use exec
, and pass an $output
array by reference.
Upvotes: 1
Reputation: 46610
<?php
$ping = `ping www.google.com`;
$ping = nl2br($ping);
echo $ping;
?>
<br />
Pinging www.l.google.com [209.85.147.104] with 32 bytes of data:<br />
<br />
Reply from 209.85.147.104: bytes=32 time=24ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=23ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=23ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=25ms TTL=53<br />
<br />
Ping statistics for 209.85.147.104:<br />
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),<br />
Approximate round trip times in milli-seconds:<br />
Minimum = 23ms, Maximum = 25ms, Average = 23ms<br />
Upvotes: 3