Update JSON file with PHP - php

I'm very new to both JSON and PHP but I'm building a game that needs a seperate database that keeps track of the doors that are locked and unlocked in a maze.
My JSON file looks like this:
{ "doors":
[
{"left":true, "right":false, "bottom":false},
{"left":false, "right":false, "bottom":false},
{"right":false, "bottom":false, "top":false}
]
}
and my PHP file looks like this:
$jsonString = file_get_contents('info.json');
$data = json_decode($jsonString);
$data["doors"][0]["right"] = true;
$newJsonString = json_encode($data);
file_put_contents('info.json', $newJsonString);
I'm calling this using ajax in javascript and I can read the file if I use var_dump($data) but as soon as I try to edit the file I get a 500 error. I feel like I'm really close, but I'm just really stuck right now. If someone could help me out that would be really great. Thanks.

Are you running this in var/www through localhost or some other server folder? If so the web-process may not have sufficient privileges to write to the directory.
Edit:
If you are running in a restricted directory (e.g. var/www or outside you user dir) you may try and change the permission of the file you are trying to write to with something like:
(try this only cd'd into the dir where your JSON file is)
sudo chmod -777 info.json
(then enter your pw if you are a linux box)
Please be aware, though, that is for testing purposes only and may lead to security & performance concerns:
For more information about this particular level of security with file permissions please view:
In a PHP / Apache / Linux context, why exactly is chmod 777 dangerous?

A 500 error is an Internal Server Error. It usually means that there is a misconfiguration somewhere. The best way to debug it is by checking your web server's error log, it should tell you why it threw a 500 error.
Also, be aware that a json_decode() without the second $assoc parameter, returns an object rather than an array, so to overrule a key you'd need to set it as an object property:
$data->doors[0]->right = true;

Related

PHP: Why is chmod() setting my file/folder to 555 or 444?

I created a web application with a file browser. I'm trying to add a functionality where the user can change the chmod/permissions via an ajax request which is handled via PHP on the back-end.
(Side Note: I'm running my local with WAMP)
So initially, I'm reading the permissions with this
substr(sprintf('%o', fileperms($relativePath)), -4)
to get this format (0777, 0644, etc), if not it returns something like 32726. This info is used to be displayed in the UI for the user to know whats current.
However, when I run the script, I set it to 0777 and it seems to run fine. But then when I read the file again, it returns 0555 or 0444. Anyone know what I'm missing?
Does your web server own the files it is trying to change the permissions on? You can check whether chmod ran correctly or failed by testing its return value. It will return FALSE if the webserver did not have permissions. For more information you can read: http://php.net/manual/en/function.chmod.php
<?php
$is_success = chmod("myfile.pdf", 777);
if($is_sucess) {
echo "success<br />\n";
}
I realized this was not an issue, but rather the chmod command does not work properly on a windows/apache setup.

How to view PHP or Apache error log online in a browser?

Is there a way to view the PHP error logs or Apache error logs in a web browser?
I find it inconvenient to ssh into multiple servers and run a "tail" command to follow the error logs. Is there some tool (preferably open source) that shows me the error logs online (streaming or non-streaming?
Thanks
A simple php code to read log and print:
<?php
exec('tail /var/log/apache2/error.log', $error_logs);
foreach($error_logs as $error_log) {
echo "<br />".$error_log;
}
?>
You can embed error_log php variable in html as per your requirement. The best part is tail command will load the latest errors which wont make too load on your server.
You can change tail to give output as you want
Ex. tail myfile.txt -n 100 // it will give last 100 lines
See What commercial and open source competitors are there to Splunk? and I would recommend https://github.com/tobi/clarity
Simple and easy tool.
Since everyone is suggesting clarity, I would also like to mention tailon. I wrote tailon as a more modern and secure alternative to clarity. It's still in its early stages of development, but the functionality you need is there. You may also use wtee, if you're only interested in following a single log file.
You good make a script that reads the error logs from apache2..
$apache_errorlog = file_get_contents('/var/log/apache2/error.log');
if its not working.. trying to get it with the php functions exec or shell_exec and the command 'cat /var/log/apache2/error.log'
EDIT: If you have multi servers(i quess with webservers on it) you can create a file on the machine, when you make a request to that script(hashed connection) you get the logs from that server
I recommend LogHappens: https://loghappens.com, it allows you to view the error log in web, and this is what it looks like:
LogHappens supports kinds of web server log format, it comes with parses for Apache and CakePHP, and you can write your own.
You can find it here: https://github.com/qijianjun/logHappens
It's open source and free, I forked it and do some work to make it work better in dev env or in public env. That is:
Support token for security, one can't access the site without the token in config.php
Support IP whitelists for security and privacy
Sopport config the interval between ajax requests
Support load static files from local (for local dev env)
I've found this solution https://code.google.com/p/php-tail/
It's working perfectly. I only needed to change the filesize, because I was getting an error first.
56 if($maxLength > $this->maxSizeToLoad) {
57 $maxLength = $this->maxSizeToLoad;
58 // return json_encode(array("size" => $fsize, "data" => array("ERROR: PHPTail attempted to load more (".round(($maxLength / 1048576), 2)."MB) then the maximum size (".round(($this->maxSizeToLoad / 1048576), 2) ."MB) of bytes into memory. You should lower the defaultUpdateTime to prevent this from happening. ")));
59 }
And I've added default size, but it's not needed
125 lastSize = <?php echo filesize($this->log) || 1000; ?>;
I know this question is a bit old, but (along with the lack of good choices) it gave me the idea to create this tiny (open source) web app. https://github.com/ToX82/logHappens. It can be used online, but I'd use an .htpasswd as a basic login system. I hope it helps.

Magento instance pointing to wrong database

Anyone ever have this problem?
local.xml has been modified. core_config_data table has been modified for unsecure and secure url as well as cookie domain. Cache dirs have been wiped clean, session values have been cleared, log tables have been truncated.
it is under version control with subversion.
have also run find to locate where it could possibly be getting the production DB IP.
find ~/path/to/application -type f -print0 | xargs -0 grep -l "IP Of incorrect DB"
yet still throwing an error on DB
SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'IP of incorrect DB' (4)
Extremely baffled and can not for the life of me locate where it would possibly be getting the production DB's IP
local.xml points to development address.
You might want to check that the magento/var/ directory, as well as all subdirectories, are writable by the web server. If those directories are not writable Magento uses /tmp/ which can cause strange effects and even conflict with other Magento sites.
Make sure you're editing the config file you think you're editing. Take a look at the following code
#File: app/code/core/Mage/Core/Model/Config.php
public function loadBase()
{
$etcDir = $this->getOptions()->getEtcDir();
$files = glob($etcDir.DS.'*.xml');
$this->loadFile(current($files));
while ($file = next($files)) {
$merge = clone $this->_prototype;
$merge->loadFile($file);
$this->extend($merge);
}
if (in_array($etcDir.DS.'local.xml', $files)) {
$this->_isLocalConfigLoaded = true;
}
return $this;
}
This is the code that merges in your local.xml file to the configuration tree. Add some debugging code
public function loadBase()
{
var_dump('Called ' . __METHOD__); //ensure we're being called
$etcDir = $this->getOptions()->getEtcDir();
$files = glob($etcDir.DS.'*.xml');
$this->loadFile(current($files));
while ($file = next($files)) {
var_dump($file); //dump the file path being loaded to the browser
$merge = clone $this->_prototype;
$merge->loadFile($file);
$this->extend($merge);
}
if (in_array($etcDir.DS.'local.xml', $files)) {
$this->_isLocalConfigLoaded = true;
}
exit; //bail out early
return $this;
}
Load your site in a browser, and observe the paths being output via var_dump. Make sure that the file(s) being loaded are the ones you think are being loaded. Keep in mind that it looks like every XML file from the etc folder is loaded and merged in.
If the paths are what you expect, next add some debugging code to output the contents of the XML file(s) being loaded.
public function loadBase()
{
var_dump('Called ' . __METHOD__ . ''); //ensure we're being called
$etcDir = $this->getOptions()->getEtcDir();
$files = glob($etcDir.DS.'*.xml');
$this->loadFile(current($files));
while ($file = next($files)) {
header('Content-Type: text/plain'); //so the browser renders it as plain text
echo file_get_contents($file); //dump the contents of the file being loaded to the browser
$merge = clone $this->_prototype;
$merge->loadFile($file);
$this->extend($merge);
}
if (in_array($etcDir.DS.'local.xml', $files)) {
$this->_isLocalConfigLoaded = true;
}
exit; //bail out early
return $this;
}
If the database information is correct in these files, then your system has been customized and/or hacked in some way that there's code calling out to another database server.
If that's the case you'll need to install something like xDebug to get some decent error reporting. This will let you find the exact code that's throwing the error, at which point you can trace it back to where it's getting it's connection information.
Good luck.
Just came across this when I had a similar issue. Followed Alan Storm's suggestion of dumping the config file names and found the problem. I had done a fresh install before copying the db and config files in from another instance, and had renamed the existing local.xml to localorig.xml. This was being loaded after local.xml and setting the db configuration fields back to the wrong values.
Moral: if you're backing up any of the config files in the same folder, change the extension.
Thanks Alan.
Try installing Alan Storm's Configviewer and check the generated XML to confirm the connection details point to the local.xml specifications. It's possible that one of the modules is using a non-default resource or some other oddity.
Can you post some of the stack trace in your question (obfuscated if you need) to show which module is calling that erroneous DB?
I had a similar problem just now. I double checked the local.xml file and that was definitely correct, however. Magento was still using an old user to access the database.
The problem was instantly resolved with: rm -rf var/cache/* - immediately this was done, the site came up.
It appears that Magento is caching the contents of local.xml in the cache area. Not so helpful.
Obviously, also recommend double checking the local.xml file but in this case it was 100% correct.
Just to try to help. Can you check your apache configuration? Something like "apache2 -S" to see which virtualhosts are used (and note especially the first default one).
You could test that all your virtualhosts (if you work with virtualhosts) are using the right documentRoot. Don't you have an other copy of the sources on your dev server?
I mean are you sure you get the right magento instance running on the url you're using on your browser? In the same way are you sure of the cache directories used on your installation - do you see any change in theses directories since the wipe out?

PHP file_put_contents() error

Everytime I try to modify a file, I get this error and I don't know what it means:
A PHP Error was encountered
Severity: Warning
Message: file_put_contents() [function.file-put-contents]: Only 0 of 19463 bytes written, possibly out of free disk space
Filename: Template/String.php
Line Number: 369
I tried looking for solutions and so far none of them made sense, well, in my opinion.
Any thoughts? A little help here please. Thank you very much.
This is an old question but it comes up when Googling for the error message. Here is another possible cause for this error message.
The ext2/3/4 filesystems can reserve disk space for root. Often it is 5% of the drive. df shows the drive is not entirely used. Root can write to the drive. Non-root users will only be able to create files but not write any data to them. See dumpe2fs and tune2fs for more details.
This probably means that PHP is able to get a valid file descriptor, but is hitting a wall (such as a quota, sticky bit, etc) when actually trying to write the data.
It is also conceivable that you are writing (perhaps unwittingly) to a network file system that is having a problem with its peer.
More information regarding your platform would help (I've seen SELinux do strange things when improperly configured), but I think you get the gist of what to check.
It's just a permission to where you wanted to save the content, e.g. readonly or just like the error itself, no disk space.
You may need to increase the quota for that user on the server. You can confirm this by deleting a file and seeing if it will let you re-upload that file, but nothing further.
If you have Webmin, go to System > Disk Quota. (For a detailed explanation, see this wiki.)
If you do not have Webmin or a similar interface, you will need to look up how to manually edit the user quota settings depending on which Linux distro you are using.
If you do not have access to the server you will need to contact the person who does and ask what your disk quota is and if it can be increased.
For me I was also having the same set of errors on my login page. While exploring I found that the storage/logs/laravel.log file has grown up to the size of 24G. And clearing it solved the issue. To find out the size of directory use linux command du -sh * or du -sh <filename> . To clear up the log file using truncate command is the best option. Because oping with vim and deleting could be difficult because of Heavy size of the file. For truncating use the command truncate -s 0 <filename>
I went to the root directory
cd /
and searched for the folder that had the biggest space usage with
du -sh *
from there I was able to trace the file giving the headache, pluto.log in /var/log. this could be any file.
Maybe you have a previous lock on your target file, try to:
$fp = fopen('yourfile.etc', 'r+');
if (!flock($fp, LOCK_EX | LOCK_NB)) {
//this file is actually being used from another script / user, that's the problem.
} else {
//ok, there wasn't lock on it, must be something else
fclose($fp);
}

PHP Wamp is not finding a file which exists

I'm having a critical issue where my WAMP installation for PHP 5.3.0 is not finding a file which exists within my computer. Does anyone know anything about this? Possibly a PHP Bug?
Any help would be much appreciated.
Here is the variable which creates the file:
$baseNewsUrl = "C:/reviews/reviews/$platform/$fullname";
And here is the code which grabs the contents:
if(is_file($baseNewsUrl)){
$contents = file_get_contents($baseNewsUrl);
} else {
echo "File not found. " . "\r\n";
continue;
}
Here is the output of $baseNewsUrl: C:/reviews/reviews/GBA/r20107_GBA.htm
And the file does exist.
Check that the entire path leading up to your file is readable by the user PHP is running as (if you are using IIS, this might be something like "Network Service," although I am not particularly experienced with PHP on Windows). Also, check whether the INI directives "open_basedir" or perhaps "safe_mode" are set--these would give PHP self-imposed limits on which files are accessible.
Do a var_dump (not an echo) on your variable.
var_dump($baseNewsUrl);
and look at the actual contents. You may have some invisible garbage characters in there that's preventing Windows if you're doing this in a browser to make sure there's no empty tags (or other browser-render-invisible) characters.
If that doesn't reveal anything, remove the is_file check and try to open the file with file_get_contents (or any file related function) and var_dump it's contents. You'll either open the file, or PHP will spit out an error/warning/notice (either to your browser or to your error log) that should let you know why it can't open the file.
I'm gonna say this, and it very well might not be your problem but it is a recurring one for me. If you use skype on your computer, it has a somewhat known compatibility issue with WAMP. It cause's WAMP to be unstable, not load files properly.. everything.
on windows
$baseNewsUrl = "C:\\reviews\\reviews\\$platform\\$fullname";
It's due to Windows Vista and WAMP.

Categories