I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.
Related
I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me.
How should I print a log in PHP code?
The usual print/printf seems to go to HTML output not the console.
I have Apache server executing the PHP code.
A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.
error_log(print_r($variable, TRUE));
might be useful
You can use error_log to send to your servers error log file (or an optional other file if you'd like)
If you are on Linux:
file_put_contents('your_log_file', 'your_content');
or
error_log ('your_content', 3, 'your_log_file');
and then in console
tail -f your_log_file
This will show continuously the last line put in the file.
You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.
In PHP, you have 3 categories of debugging solutions:
Output to a webpage (see dBug library for a nicer view of things).
Write to a log file
In session debugging with xDebug
Learn to use those instead of trying to make PHP behave like whatever other language you are used to.
Are you debugging on console? There are various options for debugging PHP.
The most common function used for quick & dirty debugging is var_dump.
That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.
Things to help out if debugging in a webpage, wrap <pre> </pre> tags around your dump statement to give you proper formatting on arrays and objects.
Ie:
<div> some html code ....
some link to test
</div>
dump $tpl like this:
<pre><?php var_dump($tpl); ?></pre>
And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Good luck!
You can also write to a file like this:
$logFilePath = '../logs/debug.text';
ob_start();
// if you want to concatenate:
if (file_exists($logFilePath)) {
include($logFilePath);
}
// for timestamp
$currentTime = date(DATE_RSS);
// echo log statement(s) here
echo "\n\n$currentTime - [log statement here]";
$logFile = fopen($logFilePath, 'w');
fwrite($logFile, ob_get_contents());
fclose($logFile);
ob_end_flush();
Make sure the proper permissions are set so php can access and write to the file (775).
If you don't want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.
Simply way is trigger_error:
trigger_error("My error");
but you can't put arrays or Objects therefore use
var_dump
You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.
This a great tool for debugging & logging php: PHp Debugger & Logger
It works right out of the box with just 3 lines of code.
It can send messages to the js console for ajax debugging and can replace the error handler.
It also dumps information about variables like var_dump() and print_r(), but in a more readable format.
Very nice tool!
I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).
That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.
Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.
If anyone does decide to us that code, I made one minor change. After
function debug($name, $var = null, $type = LOG) {
I added
$name = 'PHP: ' . $name;
This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.
(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)
I use cakephp so I use:
$this->log(YOUR_STRING_GOES_HERE, 'debug');
You can use:
<?php
echo '<script>console.log("debug log")</script>';
?>
You can use
<?php
{
AddLog("anypage.php","reason",ERR_ERROR);
}
?>
or if you want to print that statement in an log you can use
AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);
I am trying to create a simple web service that will give a result depending on parameters passed.
I would like to use file_get_contents but am having difficulties getting it to work. I have researched many of the other questions relating to the file_get_contents issues but none have been exactly the situation I seem to having.
I have a webpage:
example.com/xdirectory/index.php
I am attempting to get the value of the output of that page using:
file_get_contents(urlencode('https://www.example.com/xdirectory/index.php'));*
That does not work due to some issue with the https. Since the requesting page and the target are both on the same server I try again with a relative path:
file_get_contents(urlencode('../xdirectory/index.php'));
That does work and retrieves the html output of the page as expected.
Now if I try:
file_get_contents(urlencode('../xdirectory/index.php?id=100'));
The html output is (should be): Hello World.
The result retrieved by the command is blank. I check the error log and have an error:
[Fri Dec 04 12:22:54 2015] [error] [client 10.50.0.12] PHP Warning: file_get_contents(../xdirectory/index.php?id=100): failed to open stream: No such file or directory in /var/www/html/inventory/index.php on line 40, referer: https://www.example.com/inventory/index.php
The php.ini has these set:
allow_url_fopen, On local and On master
allow_url_include, On local and On master
Since I can get the content properly using only the url and NOT when using it with parameters I'm guessing that there is an issue with parameters and file_get_contents. I cannot find any notice against using parameters in the documentation so am at a loss and asking for your help.
Additional Notes:
I have tried this using urlencode and not using urlencode. Also, I am not trying to retrieve a file but dynamically created html output depending on parameters passed (just as much of the html output at index.php is dynamically created).
** There are several folks giving me all kind of good suggestions and it has been suggested that I must use the full blown absolute path. I just completed an experiment using file_get_contents to get http://www.duckduckgo.com, that worked, and then with a urlencoded parameter (http://www.duckduckgo.com/?q=php+is+cool)... that worked too.
It was when I tried the secure side of things, https://www.duckduckgo.com that it failed, and, with the same error message in the log as I have been receiving with my other queries.
So, now I have a refined question and I may need to update the question title to reflect it.
Does anyone know how to get a parameterized relative url to work with file_get_contents? (i.e. 'file_get_contents(urlencode('../xdirectory/index.php?id=' . urlencode('100'))); )
Unless you provide a full-blown absolute protocol://host/path-type url to file_get_contents, it WILL assume you're dealing with a local filesystem path.
That means your urlencode() version is wrongly doing
file_get_contents('..%2Fxdirectory%2Findex.php');
and you are HIGHLY unlikely to have a hidden file named ..%2Fetc....
call url with domain, try this
file_get_contents('https://www.example.com/inventory/index.php?id=100');
From reading your comments and additional notes, I think you don't want file_get_contents but you want include.
see How to execute and get content of a .php file in a variable?
Several of these answers give you useful pointers on what it looks like you're trying to achieve.
file_get_contents will return the contents of a file rather than the output of a file, unless it's a URL, but as you seem to have other issues with passing the URI absolutely....
So; you can construct something like:
$_GET['id'] = 100;
//this will pass the variable into the index.php file to use as if it was
// a GET value passed in the URI.
$output = include $_SERVER['DOCUMENT_ROOT']."/file/address/index.php";
unset($_GET['id']);
//$output holds the HTML code as a string,
The above feels hacky trying to incorporate $_GET values into the index.php page, but if you can edit the index.php page you can use plain PHP passed values and also get the output returned with a specific return $output; statement at the end of the included file.
It has been two years since I used PHP so I am just speculating about what I might try in your situation.
Instead of trying fetching the parsed file contents with arguments as a query string, I might try to set the variables directly within the php script and then include it (that is if the framework you use allows this).
To achive this I would use pattern:
ob_start -> set the variable, include the file that uses the variable -> ob_get_contents -> ob_end_clean
It is like opening your terminal and running the php file with arguments.
Anyway, I would not be surprised if there are better ways to achieve the same results. Happy hacking :o)
EDIT:
I like to emphasize that I am just speculating. I don't know if there are any security issues with this approach. You could of course ask and see if anyone knows here on stackoverflow.
EDIT2:
Hmm, scrap what I said last. I would check if you can use argv instead.
'argv' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. http://php.net/manual/en/reserved.variables.server.php
Then you just call your php script locally but without the query mark indicator "?". This way you can use the php interpreter without the server.
This is likely to be the most general solution because you can also use argv for get requests if I am understanding the manual correctly.
I've some strange issues with some php code.
if ($user->userType=='admin'){
If I use the above command, the php engine just stop interpreting and display the code in plain text on my browser. On the other hand if I use the below method it works:
if ($user['userType']=='admin'){
Again here also:
$_SESSION['currentUser']->id
If I use the above code it just displays the rest of code as plain text:
id); // fail user }else{ $authentication="failed"; $noAuthPresentation="loginForm"; }
Why this is happening? It's a big project and I don't want to change every line where there is an occurrence of ->.
Do I need to change some setting somewhere? I'm using WAMP server with php 5.5.12.
Any help ? Thanks!
You're mixing up types, user is an array, and not an object. Something in your php config is doing something strange to your error display it seems. Right click on the page that has the errors, and view source if possible.
Does login.php contain html and php code by chance?
Long ago, this code used to work but now it seems something is going on preventing it from functioning properly. I'm hoping somebody can tell me whats going on. I'm concerned upgrades to PHP have killed this code. Or has it?
I use this code (posted below) to check and to see if an html file exists, and if it does it'll use it. If not, it will use the file index2.html.
<?php if ((file_exists("$id.html")) == true) { require ("$id.html"); } else { require ("index2.html"); } ?>
I use this code on my homepage, index.php. However for some odd reason, when I type in a link: example: index.php?id=exampleurlhere, the code isn't checking to see if the file exists and is automatically using the index2.html file, despite my code telling that if the file exists (which it does), then it's required to use it. Why is it now ignoring my command?
Been using this code for years and never had any problems with it until recently it seems. Any suggestions to fix it?
I think the problem lies in the "register_globals" setting. This used to be on by default in the (very) older versions of PHP, but has been removed in the newer versions, as this caused a lot of variable injection attacks in the old PHP.
Your $id came directly from the value in the URL. Now that it no longer auto registers, you can add in a line "$id=$_GET['id'];" just above that line to get it to work again.
This is just a quick fix. I suggest you rewrite the program so that there will not be any change of users accessing files illegally using the URL.
My problem is I need to fetch FOOBAR2000's title because that including information of playing file, so I create a execute file via Win32 API(GetWindowText(), EnumWindows()) and it's working good.
TCHAR SearchText[MAX_LOADSTRING] = _T("foobar2000");
BOOL CALLBACK WorkerProc(HWND hwnd, LPARAM lParam)
{
TCHAR buffer[MAX_TITLESTRING];
GetWindowText(hwnd, buffer, MAX_TITLESTRING);
if(_tcsstr(buffer, SearchText))
{
// find it output something
}
return TRUE;
}
EnumWindows(WorkerProc, NULL);
Output would look like "album artis title .... [foobar2000 v1.1.5]"
I created a php file like test.php, and use exec() to execute it.
exec("foobar.exe");
then in console(cmd) I use command to execute it
php test.php
It's working good too, same output like before.
Now I use browser(firefox) to call this php file(test.php), strange things happened.
The output only foobar2000 v1.1.5, others information gone ...
I think maybe is exec() problem? priority or some limitation, so I use C# to create a COM Object and register it, and rewrite php code
$mydll = new COM("FOOBAR_COMObject.FOOBAR_Class");
echo $mydll->GetFooBarTitle();
still same result, command line OK, but browser Fail.
My question is
Why have 2 different output between command line and browser. I can't figure it out.
How can I get correct output via browser.
or there is a easy way to fetch FOOBAR2000's title?
Does anyone have experience on this problem?
== 2012/11/28 edited ==
follow Enno's opinion, I modify http_control plug-in to add filename info, original json info is "track title".
modify as following
state.cpp line 380 add 1 line
+pb_helper1 = pfc::string_filename(pb_item_ptr->get_path());
pb_helper1x = xml_friendly_string(pb_helper1);
# 1: when firefox opens the php and it gets executed, it the context depends on the user which runs the php-container (apache), this is quite different from the commandline call which gets executed in your context
# 2 and 3: there seems to be more than one way for getting the title: use the foobar-sdk and create a module which simply reads the current title per api, then write your result in an static-html-document inside your http-root-folder OR use the http-client inside the sdk, with it, you do not need a wabserver, even better use a already implemented module: for instance foo_upnp or foo-httpcontrol
Good luck!
If your webserver runs as a service, in windows you need to enable "allow desktop interaction" for the service. Your php script runs as a child of the webserver process when requested via browser.