Can't use document.write more than one time in PHP - php

Here is my HTML and I call external PHP
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<script src="index.php"></script>
<p>My first paragraph.</p>
</body>
</html>
and my PHP Script
<?
$strFileName = "poom.bis";
$objFopen = fopen($strFileName, 'r');
if ($objFopen) {
while (!feof($objFopen)) {
$file = fgets($objFopen, 4096);
// echo $file;
echo "document.writeln('$file'+);";
}
fclose($objFopen);
}
$test = "hello world";
echo "document.writeln(
'<ul>'+
'<li>.$test.</li>'+
'<li>test2</li>'+
'<li>test3</li>'+
'</ul>'
);";
?>
It error when using document.write more than one time
What should I do to solve this problem
Please Advice
PS. use echo "document.writeln('$file'+);"; for one time there is no error and show a result

First error: your line
echo "document.writeln('$file'+);";
should be
echo "document.writeln('$file');";
(without the plus sign). Also make sure that the file poom.bis doesn't contain a newline, not even at the end. If it does, you have to strip them away (trim()).
Second error was (until you edited it) the use of document.writeIn (which doesn't exist) instead of document.writeln (which does).
Tested and it works.
Also, while I'm at it, since you asked for advice how to solve this problem: look at your browser's error console and try to debug it.

echo '<script>document.writeln(';
echo '"<ul><li>test1</li><li>test2</li><li>test3</li></ul>"';
echo ');</script>';
;

Related

PHP GET parameter not showing without page refresh

any idea what is wrong here. I generate link list from database. When I click link, it navigates to another page, but echo is missing. However, if I check "View page source", I can found my echo. If I want to see it on page, I need to refresh page manually, so I can see my echo. I don't to refresh page, so any idea what is problem here?
Source codes:
page.php:
<?php
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
foreach ($line as $col_value) {
echo '<li>'.$col_value.'</li>';
}
}
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
test.php:
<?php
echo 'TEST ';
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
In your test.php page, replace your code with the following code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
echo 'TEST ';
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
</body>
</html>
Let me know if it works now!
Edited: Explanation of why this solution worked
The image shown in the question showed 2 windows. The confusion starts there. The window on the left is the browser at work displaying the html code that was rendered, while the window on the right is the "Source Code"! What that means is that the browser probably didn't understand what TESTHELLO dbName meant and made a blank page, but when adding all the default tags, then the browser was happy to interpret it as text within the pages body.

Using a txt file to display links with php

I am trying to display a links using php and txt file.
My Text file (text.txt)
Spiderman, www.spiderman.com
See No Evil, www.seenoevil.com
My php code so far (index.php);
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<?php
$f = fopen("text.txt", "r");
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode(",",fgets($f));
// Write links (get the data in the array)
echo "<li><a href='http://" . $arrM[1] . "'>" . $arrM[0]. "</a></li>";
}
fclose($f);
?>
</body>
</html>
Error I keep getting when I run index.php. This is what the browser displays;
If the browser gives you the output you have mentioned, this means that PHP has not been installed in your machine.Download and install WAMP server to execute php scripts.But, if php has been installed, you are not using the server address, i.e. http://localhost/APP/. file:///C:/server/www/APP/ will not execute the php script.
I think you opened the index.php directly in a browser. There is no error in this code. Try run it in the proper way .that is (localhost/yourDirectory/index.php)
You can use trim() to remove the whitespace and the new line characters, then it should work fine, I just tried:
(Also, make sure the txt file doesn't have the utf-8 BOM)
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<?php
$f = fopen("text.txt", "r");
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode(",",fgets($f));
// Write links (get the data in the array)
echo "<li><a href='http://" . trim($arrM[1]) . "'>" . trim($arrM[0]). "</a></li>";
}
fclose($f);
?>
</body>
</html>

PHP write to file minus the PHP code?

I want to write a file to a file and the file contains some PHP code. I don't want the file to run the PHP when someone reads the file. Basically, I want all the text between the <?php and the ?>, plus those tags. Is there any way to do this in PHP? Possibly with strpos? I tried to use strpos; but I couldn't figure it out.
Here's an example:
<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is what I want written to a file!</p>
</html>
The easiest way is probably to parse the file using token_get_all, loop through the result and discard everything that's not of type T_INLINE_HTML.
If your <?php ?> tags are always gonna me at the top of your input file, you could just explode the input and write to your output everything around your tags:
Input:
<?php echo "This is the PHP I want removed!"; ?>
<html>
<p>This is what I want written to a file!</p>
</html>
Code:
$inputTxt = file_get_contents($path . $file , NULL, NULL);
$begin = explode("<?php", $inputTxt);
$end = explode('?>', $inputTxt);
fwrite($output, $begin[0] . $end[1] . "\n\n");
?>
Output:
Before
<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is what I want written to a file!</p>
</html>
After
<html>
<p>This is what I want written to a file!</p>
</html>
But, if you plan on having more than one set of <?php ?> tags, then you would need to use preg_match:
Input:
<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is <?php echo $something; ?> I want written to a file!</p>
</html>
Code:
<?php
$file="input.txt";
$path='C:\\input\\';
$output = fopen($path . "output.txt",'w');
$inputTxt = file_get_contents($path . $file , NULL, NULL);
$pattern = '/<\?php.+\?>/isU';
$replace = '';
$newInput = preg_replace($pattern, $replace, $inputTxt);
fwrite($output, $newInput);
?>
Output:
Before
<?php
echo "This is the PHP I want removed!";
?>
<html>
<p>This is <?php echo $something; ?> I want written to a file!</p>
</html>
After
<html>
<p>This is I want written to a file!</p>
</html>
If you can choose the filename you're writing to, you can write to a .phps file, which won't be evaluated as PHP. If a visitor views the .phps page, they'll be served up a plaintext file that includes everything inside the <?php ?> tags, as well as the HTML.

php with preg_match_all() generates no results

I'm trying to use this php script in order to locate a stock quote from yahoo finance. The problem I'm having is that when the script is run it generates no results. This leads me to believe that my regular expression is incorrect, but when I use the same regex on myregextester.com it shows the results that I expect with the given input. Any help will be greatly appreciated. Also, my php may be incorrect for what I'm trying to do.
<html>
<head>
<title>Stock Quote from Nasdaq</title>
</head>
<body>
<?php
// choose stock to look at
$symbol = 'AMZN';
echo "<h1> Stock Quote for $symbol </h1>";
//echo 'this printed (1)<br />';
$theurl = 'http://finance.yahoo.com/q?s=AMZN';
//echo 'this printed (2)<br />';
$contents = file_get_contents($theurl);
//find the part of the page we want and output it
if (preg_match_all('/amzn">([0-9]+\.[0-9]+)/', $contents, $matches)) {
echo "The price for $symbol: ".$matches[1][0];
} else {
echo "No Results";
}
?>
</body>
</html>
What you are searching for is:
<span id="yfs_l10_amzn">221.37</span>
Your regex would succeed for that.
So your actual problem is retrieving the page. Besides the obnoxious $theurl variable name, you should just use file_get_contents instead of fread etc.
$contents = file_get_contents($theurl);
Worked in your snippet.
I just downloaded the url http://finance.yahoo.com/q?s=AMZN and looked at the page source. Done a seach for /amzn. One match. That was <a href="/marketpulse/AMZN">Market Pul.... Hence no match.
Need to have a rethink.
Escape the >
try this:
preg_match_all('/amzn"\>[0-9]+\.[0-9]+/',$contents, $matches);

Best practice: where to put the PHP code?

I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.
So I do:
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
...
</body>
</html>
This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
<div class="error_block">
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
</div>
...
</body>
</html>
Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.
I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.
Anyone can give their 2 cents on this issue? Thanks.
If you're looking for an alternate solution, I have one for you. What I like doing is having the logic in before the DOCTYPE
if(error) { $error = "Please do something" }
Than, down in the document I have a div just for the error (Thanks #Dave for the input)
<?php echo $error != '' ? '<div id="error">' . $error . '</div>' : ''; ?>
This div will not appear if there isn't an error (meaning $error is empty) and it makes it easier for you to style the error message the way you would like
#error { color:red; }
If you want to get fancy, you can use some jQuery to hide/show the div so that the error doesn't have to persist.
$('#error').show().delay(7000).fadeOut();
You should look into using try-catch blocks and generating exceptions if you want to do some post-processing with the error message, which includes display.
What is often forgotten is that PHP is an INLINE programming language in essence, this means it is designed to be processed by the server as the server reads down the page, and with this it is designed to be split up into chunks. Recently OOP (Object Oriented Programming) has been introduced to PHP making it more flexible.
So with this information in hand I would take the OOP path in this case and do something like:
<!DOCTYPE>
<?php
include("somefile.inc");
function bla()
{
...
}
function failureError($code){
if(!empty($code)) ...
}
if ($a = $b) {
code goes here
} else {
$code = 'error123';
}
?>
<html>
<head>
<script>
...
<?php failed($code); ?>
...
</script>
</head>
<body>
...
</body>
</html>
By writing using functions you can cut down your development time and group the majority of your code just calling what you need when you need it.
Another way of declaring your error class(es)/functions to help with server response time is to do something like:
if ($a = $b) {
code goes here
} else {
include("errorStuff.php");
}
This will only include the error class(es)/functions when an error is encountered.
Just remember when you're writing PHP with OOP techniques like this that the server will take longer to process the script than if you write inline. The biggest advantage to an OOP basis is it will cut down your development time and if done correctly it will make it easier to administer future updates to your script.

Categories