PHP assign variable definition from a string - php

Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.

eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!

First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.

Related

Php include to skip the first 12 lines read

I am reading data from a htm page into a Wordpress post with <?php include("liveresults/140403F001.htm"); ?> it works perfectly. I however need to skip the first 12 lines of the html file and only start reading from line 13. Any ideas?
If the file only contains HTML and you don't want to execute it as PHP, then you should not be using include anyway. readfile() is much better suited for that.
However, since you want to ignore the first 12 lines, you should use an SplFileObject which allows you to seek by line:
$file = new SplFileObject("liveresults/140403F001.htm");
$file->seek(12);
$file->fpassthru();
Note that if your file comes from some sort of external input, you should escape it for HTML, to guard against XSS.

writing to text file - layout messed up - PHP

ive got the following fwrite code, with , separating the data and it ending in ))
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
but this is how it saves in the text file...
,,,,))Triangle,180,120,80,Red))
why have the first set of
,,,,,))
appeared in front of what it should look like?
You need to add a new line character to the end of each line. Otherwise your lines will all run into each other.
Use PHP_EOL for this as it will automatically use the Operating System appropriate new line character sequence.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
Available since PHP 4.3.10 and PHP 5.0.2
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))'.PHP_EOL;
FYI, this might be a little cleaner to do using sprintf():
$shapeType = sprintf("%s,%s,%s,%s,%s))%s",
$_POST['shapeType'],
$_POST['triangleSide1'],
$_POST['triangleSide2'],
$_POST['triangleSide3'],
$_POST['triangleColour'],
PHP_EOL
);
Without seeing more of the code I would guess that you post to the same file and you do not check if a POST request was made before you write your file. So probably you write to your file on a GET request as well, causing empty entries to appear.
You would need something like:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// ...
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
// ...
}
Edit: By the way, you should probably use fputcsv as that takes care of escaping quotes, should you change something in the future that adds for example a description field.

var reads HTML code as STRING

Very simply, i want to make a variable reads the html code as string ,, i mean dont execute it (run it) .
the problem with the code is : i have a html file , and i want to get the content of it , and make some preg_replace for it (run a function on the html code), the problem is i cant use preg_replace, or any another function because the html code is executed by php (php reads the html code)..
i wish you understand me, i want something like highlight_string, but it save the html code in the variable.
Thank you.
you're probably trying to include or require the HTML code.
which is incorrect since it is evaluated as part of the source.
instead, use a function such as file_get_contents() to read the file into a string.
Use file_get_contents() as #David Chan suggested and then pass the result through htmlentities()... it converts the characters to HTML entities (i.e., < to <).
$getTheContent = file_get_contents($filepath);
echo htmlentities($getTheContent);
It should return the code, not executed.

Why is fopen() behaving like this?

I am currently working on this project which requires me to make a function which dinamically decides the directory name and then creates a simple .txt file in that directory.
my code is as follows:
($destinatario is a string)
$diretorio="../messages/".$destinatario;
if (is_dir($diretorio)) {
;
}else{
mkdir($diretorio);
}
$path=$diretorio."/".$data.",".$assunto.",".$remetente.".txt";
$handle=fopen($path,'w+');
fwrite($handle, $corpo);
fclose($handle);
nevermind the portuguese, but the bottom line is that it should create a .txt file using the naming guidelines i've provided. The funny thing is that when i do this, php creates this weird file whose filename is "01.09.2010 04"
(with no extension at all) which amounts to the first few characters of the actual filename i'd like to create...
edit($data is actually the output from a call to date("d.m.Y H:i"))
Per comment by OP:
[$data is] actually the output of a call to date("d.m.Y H:i")
The problem is the : character. (Still, there may be other illegal characters in the other parts composing the final file name.)
EDIT
The essence of the problem and solution is in the comments to #tchen's answer. Keep in mind that colon is a valid file name character on (some? all?) *nix platforms but is invalid on Windows.
Make sure there's no bad characters at the end of $data. Call trim() on it.
If it's data taken from a file, it may have a '\r' or '\n' at the end of it.
Not related, but make sure your if statements don't have unused conditions:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}
This will also get rid of that blank line with a single terminator ;, I'm sure that isn't right.
Some ideas:
have you tried not using commas in the filename?
Have you checked the return value if fopen and fwrite?
Just to try to isolate the problem
also you can simplify to:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories