File & file_get_contents bugging on reading simple file - php

file or file_get_contents do not read this sample file properly
<?php
?>
This is the test program
$flines=file('../include/test.php');
echo '<pre>';
print_r($flines);
echo '</pre>';
for($i=0;$i<count($flines);$i++) {
echo("$i:".$flines[$i]."\n<br>");
}
echo "File Get Contents";
echo(file_get_contents('../include/test.php'));
This is the output
Array
(
[0] => ?>
)
0:1:?>
File Get Contents
Basically it skips the php declaration for some reason... and the file is empty
addition
every works fine when removing the opening < of course

You didn't trick php, php was right all along; you tricked yourself....
$flines=file('./x.php');
echo '<pre>';
print_r(array_map('htmlentities',$flines));
echo '</pre>';
for($i=0;$i<count($flines);$i++) {
echo("$i:".htmlentities($flines[$i])."\n<br>");
}
echo "File Get Contents";
echo(htmlentities(file_get_contents('./x.php')));
Think about what a web browser does when it encounters < rather than <

Related

reading metadata from php file using php

After looking around for something like octopress in php and not finding anything, I decided to create something myself in php that would do the trick.
I'd like to start with writing some code in php that reads php files and can extract meta-data from them, so I can build an archive page of blog posts, etc.
I thought I could create yaml files, and include php/html in these files for the main content of the blog posts, but it's not clear to me if this is possible at all? Googling around for "use php in yaml" didn't really get me much further.
So I thought I'd ask here what the best approach would be for doing something like this.
Can anyone help?
Thanks
B
I am not familiar with yaml - can you simply use PHP's get meta tags?
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');
// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
var_dump($tags);// See any and all meta tags that have been picked up.
?>
Edit: I added the var_dump in so you can see all the tags you get. Test it out on the page you want to hit.
<?php
header('Content-Type:text/html; charset=utf-8');
$tags = get_meta_tags('http://www.narenji.ir');
var_dump($tags);
?>
Output is
array
'keywords' => string 'اخبار, تکنولوژی, نارنجی, گجت, فناوری, موبایل, خبر, تبلت, لپ تاپ, کامپیوتر, ربات, مانیتور, سه بعدی, تلویزیون' (length=186)
'description' => string 'مکانی برای آشنایی با ابزارها و اخبار داغ دنیای فناوری' (length=97)
Or you can use following code
<?php
$url = 'http://www.example.com/';
if (!$fp = fopen($url, 'r')) {
trigger_error("Unable to open URL ($url)", E_USER_ERROR);
}
$meta = stream_get_meta_data($fp);
print_r($meta);
fclose($fp);
?>
If your source file is image then you can try with it
<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";
$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
echo "$key.$name: $val<br />\n";
}
}
?>

getting data from php variable

$content = file_get_contents('file.php');
echo $content;
nothing displays, expect when displaying the page sourcecode in browser the display is this
<? foreach(glob("folder/*.php") as $class_filename) { require_once($class_filename); } ?>
so it wont execute the script when getting the content..
file.php contains this code
<? foreach(glob("folder/*.php") as $class_filename) {
require_once($class_filename);
}
?>
and if I do next
$content = foreach(glob("folder/*.php") as $class_filename) { require_once($class_filename); } ?>
it complains about unexpected foreach...
is there a way to read the folder/.php files content to single $variable and then echo/print all folder/.php files to page where it should be?
thanks for help already.
Is that what you want to do ?
$content = '';
foreach (glob('folder/*.php') as $class){$content .= file_get_contents($class);}
echo $content;
What you're trying won't execute the contents of the "file.php", jsut display the contents of them on screen.
If you want to execute file.php, use eval ($content)
To capture the output, use something like:
ob_start(); // Don't echo anything but buffer it up
$codeToRun=file_get_contents('file.php'); // Get the contents of file.php
eval ($codeToRun); // Run the contents of file.php
$content=ob_get_flush(); // Dump anything that should have been echoed to a variable and stop buffering
echo $content; //echo the stuff that should have been echoed above

Storing an html page into a php variable [duplicate]

This question already has answers here:
HTML into PHP Variable (HTML outside PHP code)
(7 answers)
Closed 4 years ago.
Hi i'd like to store a dinamically generated(with php) html code into a variable and be able to send it as a reply to an ajax request.
Let's say i randomly generate a table like:
<?php
$c=count($services);
?>
<table>
<?php
for($i=0; $i<$c; $i++){
echo "<tr>";
echo "<td>".$services_global[$i][service] ."</td>";
echo "<td>".$services_global[$i][amount]."</td>";
echo "<td>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$services_global[$i][service_price].",00</td>";
echo "<td>".$services_global[$i][service_vat].",00%</td>";
echo "</tr>";
}
?>
</table>
I need to store all the generated html code(and the rest) and echo it as a json encoded variable like:
$error='none';
$result = array('teh_html' => $html, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;
I could maybe generate an html file and then read it with:
ob_start();
//all my php generation code and stuff
file_put_contents('./tmp/invoice.html', ob_get_contents());
$html = file_get_contents('./tmp/invoice.html');
But it sounds just wrong and since i don't really need to generate the code but only send it to my main page as a reply to an ajax request it would be a waste of resources.
Any suggestions?
You don't have to store it in a file, you can just use the proper output buffering function
// turn output buffering on
ob_start();
// normal output
echo "<h1>hello world!</h1>";
// store buffer to variable and turn output buffering offer
$html = ob_get_clean();
// recall the buffered content
echo $html; //=> <h1>hello world!</h1>
More about ob_get_clean()
if the data is so much expensive to regenerate then I would suggest you to use memcached.
Otherwise I would go regenerate it every-time or cache it on the frontend.
for($i=0;$i<=5;$i++)
{
ob_start();
$store_var = $store_var.getdata($i); // put here your recursive function name
ob_get_clean();
}
function getdata($i)
{
?>
<h1>
<?php
echo $i;
?>
</h1>
<?php
ob_get_contents();
}

Problem with ob_start function in php

I have this code, which uses ob_start php function. Which basically puts the echoed data into an html file. It works before. I do not know what version of php I was using then. But my current version is 5.3.0. I cannot explain why it wouldn't work. Because the script below is working and it just puts the output of that script into the html file:
<?php
ob_start();
?>
<h2>Customer Payment Summary</h2>
<img id="tablez" src="../img/system/icons/Oficina-PDF-icon.png"></img>
<?php
if($amtopay>=$curcred){
$custchange=$amtopay - $curcred;
$newcred = 0;
echo "Change: ". $custchange."<br/>";
query_database("DELETE FROM sales_transaction WHERE Cust_Name='$customer'", "onstor", $link);
}else{
query_database("UPDATE customer_credit SET CREDIT='$newcred' WHERE Cust_Name='$customer'", "onstor", $link);
echo "Remaining Balance: ". $newcred."<br/>";;
}
echo "Customer: ".$customer."<br/>";
echo "Amount paid: ". $amtopay. "<br/>";
echo "Date: ". $date." ". date('A');
close_connection($link);
?>
<?php
file_put_contents('../tmp/customerpay.html', ob_get_contents());
?>
Here's the output of the code above:
But when I checked the html file which I specified in the file_put_contents. It gives me this. And I don't really understand why:
My problem is how to get the correct output from the html file that is being produced.
You aren't closing your output buffer before you do a file_put_contents...
At the end of your script change it to the following:
//...
close_connection($link);
$contents = ob_get_contents();
ob_end_clean();
file_put_contents('../tmp/customerpay.html', $contents);
?>

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Is there a Shortcut for
echo "<pre>";
print_r($myarray);
echo "</pre>";
It is really annoying typing those just to get a readable format of an array.
This is the shortest:
echo '<pre>',print_r($arr,1),'</pre>';
The closing tag can also be omitted.
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
You can set the second parameter of print_r to true to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo (don’t forget htmlspecialchars if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
teach your editor to do it-
after writing "pr_" tab i get exactly
print("<pre>");
print_r($);
print("</pre>");
with the cursor just after the $
i did it on textmate by adding this snippet:
print("<pre>");
print_r(\$${1:});
print("</pre>");
If you use VS CODE, you can use :
Ctrl + Shift + P -> Configure User Snippets -> PHP -> Enter
After that you can input code to file php.json :
"Show variable user want to see": {
"prefix": "pre_",
"body": [
"echo '<pre>';",
"print_r($variable);",
"echo '</pre>';"
],
"description": "Show variable user want to see"
}
After that you save file php.json, then you return to the first file with any extension .php and input pre_ -> Enter
Done, I hope it helps.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r does - but nicely formatted and in a <pre>.
(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)
echo "<pre/>"; print_r($array);
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
I just add function pr() to the global scope of my project.
For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
Just write
print_r($myarray); //it will display you content of an array $myarray
exit(); //it will not execute further codes after displaying your array
Maybe you can build a function / static class Method that does exactly that. I use Kohana which has a nice function called:
Kohana::Debug
That will do what you want. That's reduces it to only one line. A simple function will look like
function debug($input) {
echo "<pre>";
print_r($input);
echo "</pre>";
}
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
I would go for closing the php tag and then output the <pre></pre> as html, so PHP doesn't have to process it before echoing it:
?>
<pre><?=print_r($arr,1)?></pre>
<?php
That should also be faster (not notable for this short piece) in general. Using can be used as shortcode for PHP code.
<?php
$people = array(
"maurice"=> array("name"=>"Andrew",
"age"=>40,
"gender"=>"male"),
"muteti" => array("name"=>"Francisca",
"age"=>30,
"gender"=>"Female")
);
'<pre>'.
print_r($people).
'</pre>';
/*foreach ($people as $key => $value) {
echo "<h2><strong>$key</strong></h2><br>";
foreach ($value as $values) {
echo $values."<br>";;
}
}*/
//echo $people['maurice']['name'];
?>
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Download AutoHotKey program from the official website: [https://www.autohotkey.com/]
After Installation process, right click in any folder and you will get as the following image: https://i.stack.imgur.com/n2Rwz.png
Select AutoHotKey Script file, open it with notePad or any text editor Write the following in the file:
::Your_Shortcut::echo '<pre>';var_dump();echo '</pre>';exit();
the first ::Your_Shortcut means the shortcut you want, I choose for example vard.
Save the file.
Double-click on the file to run it, after that your shortcut is ready.
You can test it by write your shortcut and click space.
For more simpler way
echo ""; print_r($test); exit();

Categories