I have a PHP script that calls the function fileRead2 function from the file fileRead2.php.
The function below reads username.txt (Which display's the username).
vim fileRead2.php
<?php
function fileRead2() {
global $fh, $line;
$fh = fopen('username.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
echo($line);
}
fclose($fh);
}
?>
If I run the linux command cat on the linux filesystem it show's 'tjones' (the username.)
I run the below in a script.
<?php
// Read the Username
require_once('fileread2.php');
$userName = fileRead2();
echo $userName;
var_dump($userName);
>?
It echo's $userName that display's 'tjones' however var_dump show's its output as NULL.
Is there any reason why var_dump shows the $userName variable as NULL, when it should be string 'tjones'?
The reason I ask is because I need the variable $userName; for other parts of code and because it's NULL nothing else is working, and I have no idea why?
You'd need to modify fileRead2.php to use return instead of echo:
<?php
function fileRead2() {
global $fh, $line;
$fh = fopen('username.txt','r');
$lineReturn = "";
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
$lineReturn = $line;
}
fclose($fh);
return $lineReturn;
}
?>
echo is used to send information to the standard output - what this means is that if you run a php script in the terminal and use echo, it's going to be sent to the terminal (assuming you don't redirect the standard output elsewhere); if you're using the php script to generate web content, it will output the information to the browser (this is a simplification).
Return on the other hand is used inside functions to send information to blocks of code outside of the function. So in your case, you want the function fileRead2 to read from the username.txt file, and then return the first line (username) so that you can set a variable that's outside of the function. In order to do this you have to use return.
As another note, if you're not doing any additional "work" on the line beyond setting the $line variable to the fgets output and the username is on the first line of the username.txt file, then you don't need a while loop. Instead you can just do $line = fgets($fh);, and then of course close the file and return the $line variable.
You function fileRead2() have not a return clause, so it return type void. And the var_dump()'s return type is also void.
so
$userName is null, so echo $userName output nothing.
var_dump($username) will output the NULL.
echo var_dump($userName) output nothing.
And in your code the readfile2 just add return $line; will return false
Related
With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.
I am trying to modify data in a json file with php. The code I am using is below. It is able to successfully ready the file contents and in the foreach loop it will echo out in the if statement.
This is great, the if statement is hardcoded for now to test. What I want to do is modify various properties and write it back to the file. This does not seem to be working. When I load the page, then refresh to see if the new value was set it just keeps echoing the same values. I download the .json locally and nothing has changed.
Any thoughts on what I am doing wrong?
//Get file, decode
$filename = '../json/hartford.json';
$jsonString = file_get_contents($filename);
$data = json_decode($jsonString, true);
foreach ($data['features'] as $key => $segment) {
if ($segment['properties']['UID'] == '25301') {
//echo out properties for testing
echo("KEY: ".$key."<br/>");
echo("UID: ".$segment['properties']['UID']."<br/>");
echo("Full Name: ".$segment['properties']['FULLNAME']."<br/>");
echo("FCC: ".$segment['properties']['FCC']."<br/>");
echo("Render CL: ".$segment['properties']['RENDER_CL']."<br/>");
echo("<hr/>");
//set property to new value.... NOT WORKING?
$segment['properties']['RENDER_CL'] = 111;
}
}
//Test if file is writable to be sure
$writable = ( is_writable($filename) ) ? TRUE : chmod($filename, 0755);
if ( $writable ) {
$newJsonString = json_encode($data);
if (file_put_contents($filename, $newJsonString)) {
echo('Put File Content success');
} else {
echo('NOT put');
}
} else {
echo 'not writeable';
}
In the end it will echo out 'Put File Content success' which seems to indicate it was successful but it isn't... Thanks for any advice.
You need to understand how foreach cycle works. The thing is, that the value you're getting ($segment) is a copy of the real value in the source array. So when you assign to it ($segment['properties']['RENDER_CL'] = 111;), you don't really change the source array. You only change some local variable that goes out of scope when the cycel-loop ends.
There are several ways how to solve this issue. One of them is to add & before the value-variable:
foreach ($data['features'] as $key => &$segment)
This tells it to use the reference of the array-item, not to copy its value.
You should use $segment variable in foreach as a reference:
foreach ($data['features'] as $key => &$segment) {
...
$segment['properties']['RENDER_CL'] = 111;
}
I am often using echo to debug function code:
public function MyFunc() {
// some code...
echo "OK";
// some code...
}
How can I check that my function print's/echo's something?
(pseudo code):
MyFunc();
if (<when something was printed>){
echo "You forgot to delete echo calls in this function";
}
This should work for you:
Just call your functions, while you have output buffering on and check if the content then is empty, e.g.
ob_start();
//function calls here
MyFunc();
$content = ob_get_contents();
ob_end_clean();
if(!empty($content))
echo "You forgot to delete echos for this function";
You could create a $debug flag and a debuglog() function, which checks for the debug flag and only then echos the message. Then you can toggle your debug messages on and off from one location.
define('DEBUGMODE', true); // somewhere high up in a config
function debuglog($msg){
if( DEBUGMODE ){ echo $msg; }
}
Should you ever want to get rid of your debug echos, you can search for "debuglog(" and delete those lines of code. This way you won't accidentally delete any echo statements that are required in normal execution or miss any debug echo statements that should really have been removed.
It's the bad way checking if something is echoed.
You can set a variable named is_echoed to 1 or you can return the value
public $is_echoed = 0;
//rest
$this->is_echoed = 1;
or
function myFunc()
{
return "OK";
}
if(myFunc() == 'OK')
//rest
You can use var_dump() and die() to debug your code more efficiently.
$test = "debud test";
public function MyFunc($test)
{
// some code...
var_dump($test); die();
// some code...
}
Reference:
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.die.php
Why do you want to try such an extensive process of seeing if something has been echoed or not?
For debugging you can definitely use echo to see if the particular block is being hit during a particular use-case. But I would suggest you use flags and return the values to the calling function.
function xyz () {
if (something) return some_value;
else return some_other_value;
}
There is no particular need to have variables and use space in storing a 0 or 1 when you can just return a hard-coded literal.
I would suggest to you to use something like log4php [1]
But if not, I use a function like this:
define('DEBUG', true);
function debug($msg){
if(DEBUG){ echo $msg; }
}
Or something like this to see the log in the browser console:
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
I have some code to get some public available data that i am fetching from a website
//Array of params
foreach($params as $par){
$html = file_get_html('WEBSITE.COM/$par');
$name = $html->find('div[class=name]');
$link = $html->find('div[class=secondName]');
foreach($link as $i => $result2)
{
$var = $name[$i]->plaintext;
echo $result2->href,"<br>";
//Insert to database
}
}
So it goes to the given website with a different parameter in the URL each time on the loop, i keep getting errors that breaks the script when a 404 comes up or a server temporarily unavailable. I have tried code to check the headers and check if the $html is an object first but i still get the errors, is there a way i can just skip the errors and leave them out and carry on with the script?
Code i have tried to checked headers
function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = #get_headers($url);
//print_r($headers);
if (is_array($headers)){
//Check for http error here....should add checks for other errors too...
if(strpos($headers[0], '404 Not Found'))
return false;
else
return true;
}
else
return false;
}
Code i have tried to check if object
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
// and only then start searching (and manipulating) the dom
You need to be more specific, what kind of errors are you getting? Which line errors out?
Edit: Since you did specify the errors you're getting, here's what to do:
I've noticed you're using SINGLE quotes with a string that contains variables. This won't work, use double quotes instead, i.e.:
$html = file_get_html("WEBSITE.COM/$par");
Perhaps this is the issue?
Also, you could use file_get_contents()
if (file_get_contents("WEBSITE.COM/$par") !== false) {
...
}
I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.