Use PHP fwrite to write php file - php

I'm building a CMS and I'm stuck on this problem. I need to write a simple php file for every page and I need to pass an ID and the include function.
Here is my code to write the file:
$filename=mysqli_fetch_array($query))['pagename'];
$fw=fopen("../".$filename,'w',true);
fwrite( "<php
\$id = $id;
include('admin/renderpage.php');
?>");
fclose($fw);
and this is the result, which looks like what I need, only that the variable $id is not an actual variable and include function doesn't work either.
<php
$id = 2;
include('admin/renderpage.php');
?>

Try:
$filename=mysqli_fetch_array($query))['pagename'];
$fw=fopen("../".$filename,'w',true);
fwrite( $fw, "<?php
\$id = $id;
include('admin/renderpage.php');
?>");
fclose($fw);
The PHP open tag is: <?php not <php.
PHP tags

Related

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

How can I replace braces with <?php ?> in php file?

I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

how to echo php file without pars?

how to read a php file and echo it in a html file?
i try to use readfile() , file() file_get_content() to read a php file.
but when i echo file_string its parsed and then show.
how i can prevent to pars stirng var that included php codes.
here my code:
<?php
$path = '..../ex.php';
$source = fopen($path , "r");
echo fread($source,filesize($path ));
fclose($source);
?>
how to echo $source without compiled or parsed.
With this function
<?php
echo htmlspecialchars($text);
?>
php.net/htmlspecialchars
fread should works fine. Remember that when you use echo it prints <?php opening tag and in rendered page it can be not visible.
To test it, just try with var_dump:
$content = fread($source,filesize($path));
var_dump($content);
I'll go out on a limb and guess that the code is not showing up completely in your HTML page, because the browser is trying to interpret <?php as HTML tags. The solution is to HTML encode any text which may contain characters with a special meaning in HTML:
echo htmlspecialchars(file_get_contents('..../ex.php'));
See The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
use this
$path = 'ex.php';
$source = fopen($path , "r");
echo "<textarea style='border:0px; overflow: hidden; width:100%; height:100% '>";
echo fread($source,filesize($path ));
echo "</textarea>";
fclose($source);

Jquery send data within function param

I have this issue with my jquery code:
<?php
//I oppen a text document, read the text inside of it and write it inside my html page.
//When someone clicks on a line, I want to take that very same line and send it via select(String) function.
$handle = fopen($_POST['lien'], 'r');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
//It works when I put a simple string within the select param:
//echo "<div onclick='select(\" text \");'>".$buffer."</div><br/>";
}
fclose($handle);
}
?>
The jquery code :
function select(text){
alert(text);
//$("#selected").html();
}
where do you guys think is the problem ?
Thanks :)
Maybe Your $buffer contains some double-quotes, which then interfere with surrounding double-quotes. Look at produced HTML code if this is the case, maybe You'll see something like this:
<div onclick='select("He said: "Freeze!"")'>
... which Javascript can't parse correctly. If this is the case, consider using:
echo "<div onclick='select(".json_encode($buffer).")'>";
Try to change line:
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
to
echo "<div onclick='select(\" ".rtrim($buffer)." \");'>".$buffer."</div><br/>";
or to:
echo "<div onclick='select($(this).text());'>".$buffer."</div><br/>";

How do I use PHP to supply info to JavaScript?

I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).

Categories