I'm new to PHP and I seem to be doing something wrong. On one hand, I have a Perl script that looks like this:
use LWP::UserAgent;
my $browser = LWP::UserAgent->new;
my $url = 'https://url/index.php';
my $response = $browser->post($url, [
"command" => "test",
"data" => "123"
]);
die "Error getting $url" unless $response->is_success;
print $response->content;
On the server, the index.php file looks like this:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
echo "Hello!\n";
}else {
echo "Error\n";
}
?>
And... that's it. If I try to execute the Perl script, however, it prints the whole index.php file, instead of Hello! or that other error message. I guess it makes sense that I'm requesting a file and that's what it's printing, however I'm quite confused about what it is I'm doing wrong. I've been looking around for examples for a while but I've found nothing so far that could point me in the right direction.
I think the problem here is that the server doesn't know that it should be treating the PHP file as PHP. Instead of parsing/interpreting it it's just returning it.
Make sure that you have PHP installed on the server and then make sure that the following line is in your Apache config:
AddType application/x-httpd-php php
Sounds like you don't have PHP set up on your server.
Here's some info on the steps required to get it up and running on Apache. Even if you have the module installed, you are likely missing some httpd.conf configuration steps.
Can you load https://url/index.php in your web browser? My first guess would be that your Webserver isn't executing PHP and is just outputting the contents of the index.php file.
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'm working with PHP and HTML, but I have an issue popping up whenever I write some PHP code. An example of this is as follows:
<?php
echo "<h2>Hello?</h2>";
$var = 5;
echo "You have $var minutes to go.";
?>
What this ends up outputting on screen is:
Hello?"; $var = 5; echo "You have $var minutes to go."; ?>
But what I want to happen is this:
Hello? You have 5 minutes to go.
Is there something I'm forgetting to do? It doesn't seem to matter whether or not I add the HTML preamble, or if I put a tag like around the second echo line. Does anyone have any advice?
EDIT: Apparently I have failed to parse PHP correctly. This computer is new and I have XAMPP installed on it, but nothing else. Did I miss something I needed in order to use PHP?
That sounds like if the php code wasn't interpreted.
Make sure to have the code in a file with a filename ending with .php and that PHP is installed/enabled on your server.
The PHP isn't being parsed properly.
Make sure you are saving your files as .php
If you are running this locally through WAMP the make sure to use localhost in your URL because if your URL looks like this file:///C:/wamp/www/index.php then that is incorrect.
I think CakePHP uses .ctp files so that could also be an issue
You can setup Apache to interpret any file extension as PHP
make php and html different.so things become much easier.
try like this:
<h2>Hello?</h2>
<?php
$var = 5;
?>
You have <?php echo $var;?> minutes to go.
I have a client in php who make an http get request to a server. that's the code:
client
<?php
function xml_post($xml_request)
{
$url="http://localhost/malakies/server.php?xml=" . urlencode($xml_request);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result=curl_exec($ch);
if (curl_errno($ch)){
$ERR .= "cURL ERROR: ".curl_errno($ch).": ".curl_error($ch)."\n";
}
return $result;
}
$result=xml_post("Send sth");
echo $result; ?>
and the server code:
<?php
$postdata = $_GET['xml'];
echo $postdata; ?>
All work perfect. But i have a question that it may be a rookie one:)
I want in the server side to have sth like a listener that listens when an http get request have come and do sth with this request. i don't know if http request is the technique that gives me an option like this.. i want sth like that:
while(http request hasn't come yet)
just wait;
do sth with the http request.
Thank you in advance.
PHP script is ran automatically for each separate request. So actually PHP/Apache is already doing what you're asking for.
Maybe this is a bit confusing if you're coming from different programming language (like Java) where you typically have an event loop waiting for new connection.
On the other hand, maybe you had a specific situation in your mind. Please explain your requirements further if that's the case ...
Because your url "ends" in server.php, you need to place a file on your server named "server.php". If your curl script returns a 404 error, you don't have the file at the right location. Where you need to place the file, depends on the operating system. On Linux, this COULD be /var/www/. So you need to find out what your "document root" is. There you would create a subdir malakies. In the Linux example this would be /var/www/malakies/server.php.
PHP will then execute the script inside your file when the request comes in. The data you pass will be placed in an associative array named $_GET. I suggest the following contents for server.php:
<?php
echo "Have a first line so you see something even when no data is passed\n";
var_dump($_GET['xml']);
?>
xml_post in you curl function will then return (disregard the colors)
Have a first line so you see something even when no data is passed
Send sth
If it's not working, what's the error code you get?
I assumed that you have apache installed and that you want to catch the request with PHP.
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.
I have this little function
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
Which whatever I try, simply outputs the php code as the html source, and not the result of the php code. This was previously working fine, and I am not sure what I have changed to result in this behavior.
I have pasted all the code now. An error is generated by a link that calls updateByQuery, preventing makewindows from being parsed correctly..I think. I am not sure what is wrong with updateByQuery however:
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
Have you recently moved this file out of a PHP parsed file (i.e. .phtml/.php) and into a .js file? Note that any PHP you expect to be executed must be parsed by the PHP parser before delivery to the client. If it was originally in a .php file, then it would have been parsed/ executed, and worked fine.
However, .js files are not, by default, parsed by PHP. Perhaps they were, at one point, but your server administrator has recently upgraded something, and lost this behaviour? You may be able to use a local configuration file (in Apache, .htaccess) to re-enable it.
This code must be in a file that is parsed by PHP before being sent to the browser. Make sure it has a ".php" extension (or that Apache/(or other) is configured to put whatever extension it is using through PHP). Also, make sure PHP is installed correctly and working.
I assume you still have it in a file that is parsed by PHP, like the others already have said. Then it is probably something above this code snippet that confuses the php-parser so it don't recognize the php-tag.
To test that, try to output something else before this function, maybe just a comment or something.
Also, use "var" before client1, or else client1 will be in the global scope.
update 1
Since you tried to insert a piece of php-code and it broke, then the problem is that the server don't parse the file as it should.
To test if the server really parses your .js files (its not the default setting I believe), create a new file: test.js
<?php echo "This is a test"; ?>
Open the test.js file in your browser and look at the page source. If it has the php tags your server don't parse .js files.
update 2
If the php works in .js files, try to rewrite the function like this (sorry I have not tested it because I don't have access to a php-server right now)
<?php
echo "function makewindows(){var child1 = window.open (\"about:blank\"); " .
"child1.document.write(\"" . htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES) . "\");" . "child1.document.close(); }";
?>
Make sure you are running the page from the webserver like such: http://localhost/yourpage.php and not directly from the file itself like such: file://yourpage.php
I'm not sure if this will help, but best practices dictate that whenever you write to a new window using JavaScript, you should open and close the document. Can you try this?
function makewindows(){
var child1 = window.open ("about:blank");
child1.document.open();
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}