Why my variable is undefined inside the function - php

It gives me this error Notice: Undefined variable: newfile and of course it also gives me fwrite() expects parameter 1 to be resource, null given cause of the first error. What I doing wrong?
$file = fopen("mycsv.csv", 'r');
$newfile = fopen("myjson.txt", 'w');
function write($text, $tab) {
$tabs = "";
for ($index = 0; $index < $tab; $index++) {
$tabs .= "\t";
}
fwrite($newfile, $text."\n".$tabs); //error here
}

Have a read about variable scope in the manual
$file and $newfile are global, therfore $newfile cannot be accessed locally in your function. Either move it into the function, pass it in as a parameter or as a last resort declare it as global in the function

You need to make $newfile global to be able to use it inside a function's scope:
function write($text, $tab) {
global $newfile;
// ... the rest
}

Any variable used inside a function is by default limited to the local function scope.
See: http://php.net/manual/en/language.variables.scope.php
You can do what you want if you make $newfile a global variable or pass it in as another function argument.

Function is out of scope. You could send the opened document direct to the function, that would allow it to be used within scope of the function.
function write($newfile,$text,$tab){
//the rest of your code
}
$returned = write($newfile,$text,$tab);

Related

how to require a php file passing parameters

I have a function that does something (and it is included in my files php).
That function should require a php file passing parameters, but it fails and I'm not able to go ahead...
following the initial code of the function:
<?php
function write_pdf($orientation, $initrow, $rowsperpage)
{
ob_start();
require "./mypage.php?orient=$orientation&init=$initrow&nrrows=$rowsperpage";
$html = ob_get_clean();
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
...
...
the "mypage.php" returns the errors:
Notice:Undefined variable: orientation in
C:\wamp\www\htdocs\site\mypage.php on line 8
Notice:Undefined variable: initrow in
C:\wamp\www\htdocs\site\mypage.php on line 8
Notice:Undefined variable: rowsperpage in
C:\wamp\www\htdocs\site\mypage.php on line 8
is there a way to do something like that?
thanks!
You don't need to pass the parameters, as when you require the file is like its code where inside the function, so any variable defined in the function before the require, it will exists and be defined as well in your required file. So, you can directly use inside your required file the variables $orientation, $initrow, $rowsperpage.
Another way, quite ugly, is to add those vars to $_GET before require the file, assuming you're expecting to get them from $_GET:
$_GET['orient'] = $orientation;
$_GET['init'] = $initrow;
$_GET['nrrows'] = $rowsperpage;
require './mypage.php';
And my recommended way is to encapsulate your included file code in a function, so you can call it passing params. Even make a class, if included code is large and can be sliced in methods.
you can do so.
to_include.php
<?php
$orient = isset($_GET["orient"]) ? $_GET["orient"] : "portrait";
$init = isset($_GET["init"]) ? $_GET["init"] : 1;
echo "<pre>";
var_dump(
[
"orient"=>$orient,
"init"=>$init
]
);
echo "</pre>";
main.php
<?php
function include_get_params($file) {
$main = explode('?', $file);
$parts = explode('&', $main[1]);
foreach($parts as $part) {
parse_str($part, $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($main[0]);
}
include_get_params("to_include.php?orient=landscape&init=100");
The method include_get_params, first separates the main part of the string, separates the file from the parameters, through the ?
After that he sets the parameters into pieces and puts all of this within the $_GET
In to_include, we retrieved the parameters from the $_GET
I hope I helped you.

PHP variables in/out a function

I want to write data in a csv.
For that I call a function to fill it.
I don't know how to call the variable outside the function (without global) so i open the file in it, but i need to close it outside, and i can't have my $fileOpen variable:
function doMyCode($args)
{
if (!isset($firstLoop)){
$fileOpen = fopen('customers.csv', 'w');
$firstLoop = true;
}
[...]
fputcsv($fileOpen, $rowData, ";");
}
fclose($fileOpen);
So, how can i do that? With good manners, i don't want to put one looper's counter (like $i)
UPDATE
The call to the function is in Magento, it's like the array_map(), but in this form i don't know how to send another parameter or return anything:
Mage::getSingleton('core/resource_iterator')->walk(
$theList->getSelect()->limit(10),
array('exportClient')
);
This is the reason I have this doubt
The best way would be to handle the file opening and closeing outside
function doMyCode($args, $fileOpen ){
fputcsv($fileOpen, $args, ";");
}
$fileOpen = fopen('customers.csv', 'w');
foreach( $lines as $line ){
doMyCode($line , $fileOpen );
}
fclose($fileOpen);
I would not open the file inside the function and close it elsewhere, either open / close it inside that function or open / close it outside, otherwise it just gets too messy, is it open? is it closed? who knows....

PHP: how to check if a given file has been included() inside a function

I have a PHP file that can be include'd() in various places inside another page. I want to know whether it has been included inside a function. How can I do this? Thanks.
There's a function called debug_backtrace() that will return the current call stack as an array. It feels like a somewhat ugly solution but it'll probably work for most cases:
$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
// ignore calls to include/require
if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
echo 'File has not been included in the top scope.';
exit;
}
}
You can set a variable in the included file and check for that variable in your functions:
include.php:
$included = true;
anotherfile.php:
function whatever() {
global $included;
if (isset($included)) {
// It has been included.
}
}
whatever();
You can check if the file is in the array returned by get_included_files(). (Note that list elements are full pathnames.) To see if inclusion occurred during a particular function call, check get_included_files before and after the function call.

PHP Get Basename of File Where Function Called

Anyone can help me get the basename of directory where the function called? I mean:
file /root/system/file_class.php
function find_file($dir, $file) {
$all_file = scandir($dir);
....
}
function does_exist($file) {
$pathinfo = pathinfo($file);
$find = find_file($pathinfo["dirname"], $pathinfo["basename"]);
return $find;
}
file /root/app/test.php
$is_exist = does_exist("config.php");
Under /root/app i have file "config.php, system.php". Do you know how to get the directory where does_exist() called? In function find_file() argument $dir is important, since scandir() function need directory path to scaned. I mean, when i want to check file config.php i doesn't need to write /root/app/config.php. If i not provide fullpath in $file argument, the $pathinfo["dirname"] will be ".". I've try to use dirname(__file__) in file_find() function but it's return the directory /root/system not /root/app where it is the directory of does_exist() function called.
I need create those function since i can't use file_exists() function.
Found Solutions:
I'm using debug_backtrace() to get the recent file and line number of where users calling function. For example:
function read_text($file = "") {
if (!$file) {
$last_debug = next(debug_backtrace());
echo "Unable to call 'read_text()' in ".$last_debug['file']." at line ".$last_debug['line'].".";
}
}
/home/index.php
16 $text = read_text();
The sample output: Unable to call 'read_text()' in /home/index.php at line 16.
Thanks.
Use any of PHP magic constants
__DIR__
__FILE__
http://php.net/manual/en/language.constants.predefined.php
Or use realpath("./");
To define your own constant paths:
define("MYPATH", realpath("./") . "/dir/dir/";
You can then call this MYPATH from everywhere this code (file) is included.

Unset XML element function not working

This is what I have.
$filename= asql($_GET['filename']);
$fullfile = "xml/".$filename;
function delete_book_id($ids){
$data = simplexml_load_file($fullfile);
$data_count = count($data->item);
for($i = 0; $i < $data_count; $i++)
{
//basically what you want to remove
if(($data->item[$i]->id == $ids))
{
unset($data->item[$i]);
}
}
file_put_contents($fullfile, $data->saveXML());
}
lets say $fullfile is xml/name.xml and the file exists in our folder. Where the variable is called in the function it should work right?
If I replace the variable in the function with xml/name.xml it will work, but using the variable causes the page to break and not reload nor will it remove the line it is supposed to unset. Will the function not accept variables, or am I missing something here?
I have also tried using "xml/".$filename in place of the variable in the function. No luck there either.
$fullfile is defined outside of the function. It's undefined inside of it. Use global $fullfile; within function or define it there.

Categories