Save output of $_SERVER to file - php

I use this :
<?php
foreach($_SERVER as $key => $value){
echo "<b>$key:</b> $value<br>\n";
}
?>
Which outputs in browser. Is there anyway to redirect output to file and hide it from the browser page ?

I would suggest something like:
<?php
foreach($_SERVER as $key => $value)
{
file_put_contents('the_file.txt', "<b>$key:</b> $value<br>\n", FILE_APPEND);
}
?>
Make sure that the_file.txt has write permissions.

Instead of echoing build an output to put in your file:
<?php
$in='';
foreach($_SERVER as $key => $value){
$in .= $key.' - '.$value.PHP_EOL;
}
//save it
file_put_contents('_SERVER.txt', $in);
?>
Also, Your not going to want to add any html tags.

To write a file you would want to use file_put_contents(). To generate a (human) readable representation of the contents of $_SERVER you should look into print_r() or var_export().
file_put_contents("/tmp/exported-server.txt", print_r($_SERVER, true));
using $s = print_r($_SERVER), $s = var_export($_SERVER) or even ob_start(); var_dump($_SERVER); $s = ob_get_clean(); makes sure you get a proper visualization of any value type. Your approach only works well for strings and numbers, but fails for arrays, objects, …

Related

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.

Formatting XML in to JSON with PHP

I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));

PHP - fwrite PHP Data With Set Variables

I am trying to figure out how to fwrite into a .php file with variables given through $_POST, or $_GET, supplied by the user to set variables and such. So, how would I go about getting the below code to work so that instead of fwriting the code, insert a $_GET variable for example, or in the below description, being $derp.
<?php
$derp = "working!";
$something = '<?php echo "Well Thats {$derp}' ?>';
$file = fopen("worked.php","w");
if (fwrite($file,$something) > 0) {
echo "Fwrite Successful!";
}
fclose($file);
?>
Although this use case looks very weird the following should work:
$data = array('<?php');
foreach ($_REQUEST as $key => $value) {
$data[] = "\$$key = \"$value\";";
}
$data[] = '?>';
$data = join("\n", $data);
file_put_contents('/path/to/file.php', $data);
Beware: This code imposes several security risks.
WTF is going on here?
The above code iterates through all array elements of $_GET and $_POST, combined.
By that it creates an array of lines to be written to a file.
This array will then be join()ed into a string by using the NEWLINE ascii character as the glue.
Assuming this script is called with the following query string:
?foo=bar&bar=baz
The file /path/to/file.php will then contain (file_put_contents):
<?php
$foo = "bar";
$bar = "baz";
?>
The example above does not support nested query parameters like foo[bar]=baz.

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";
}
}
?>

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