I am working with a client on getting a gzip from their webservice. I am able to get a response with my following call:
$response = $client->call('branchzipdata', $param);
$filename = "test.gzip";
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $response) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
Now when I attempt to write that a file, such as 'test.gzip', I am unable to open it afterwards... most likely because I am doing something horrible wrong. Any insight would be appreciated.
EDIT:
For some reason I was saving the file as '.gzip' instead of '.gz'... So in order to have it work I now have:
$response = $client->call('call', $param);
$content = base64_decode($response);
$filename = "output_zip.gz";
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $content) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
echo system("gzip -d $filename");
(Edited based on the comments)
If the return value is base64-encoded, you need to base64-decode it before you write it to the file. Alternatively you could write it out to a file which you then base64-decode to another file before trying to open it, but that seems a bit pointless compared with just decoding it when you first get it.
Related
I have a file manager and I want to add an option of editing files (html,php,css), but if I try with fgets() it displays the page and its graphic. How to get only lines from file and then send them as response to ajax request.
This is what I tried so far:
<?php
$handle = fopen('/location/', "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
} else {
// error opening the file.
}
?>
Use
show_source("/location/file.php"); to get the source code.
You can refer it from W3School - PHP show_source() Function
If the file is on the same server you can use
$content = #file_get_contents($filename);
if($content){
echo $content;
}else{
echo 'File:"'.$filename.'" couldn\'t be found.';
}
I am new to php so I was trying to make a simple multiple choice quiz app , one question at a time so when the user click the submit button it goes to the next question so the questions are in different php files , so I was trying to store the answers in a simple answers.txt file using the fopen , fwrite functions , but the problem is that when I tried to answer the quiz questions myself .. it doesnt create the answers.txt file , so I created it manually but it remains empty and here is the first questions' php code :
<?php
if (isset($_GET['q1']) && !empty($_GET['q1'])) {
$answer1 = $_GET['q1'];
$heranswers = fopen("Nanswers.txt ", "a+");
fwrite($heranswers, $answer1);
}
?>
so what's wrong with this ?
Add the following code in the if loop
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
die(error_get_last());
}
// Write $answer1 to our opened file.
if (fwrite($handle, $answer1) === FALSE) {
echo "Cannot write to file ($filename)";
die(error_get_last());
}
echo "Success, wrote ($answer1) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
Atleast you will find the error
make sure file permission .. it should be writable...
<?php
$answer1 = 10;
$filename = "Nanswers.txt";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a+')) {
echo "Cannot open file ($filename)";
die(error_get_last());
}
// Write $answer1 to our opened file.
if (fwrite($handle, $answer1) === FALSE) {
echo "Cannot write to file ($filename)";
die(error_get_last());
}
echo "Success, wrote ($answer1) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
I do fetch a file with
$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
and then the method gives it back as image. But when fopen() fails, because the file did not exists, it throws an error:
[{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\...
This is coming back as json, obviously.
The Question is now: How can i catch the error and prevent the method from throwing this error directly to the client?
You should first test the existence of a file by file_exists().
try
{
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( !file_exists($fileName) ) {
throw new Exception('File not found.');
}
$fp = fopen($fileName, "rb");
if ( !$fp ) {
throw new Exception('File open failed.');
}
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
} catch ( Exception $e ) {
// send error message if you can
}
or simple solution without exceptions:
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ) {
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
}
else
{
// send error message if you can
}
You can use the file_exists() function before calling fopen().
if(file_exists('uploads/Team/img/'.$team_id.'.png')
{
$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
}
[{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\...
the error is clear: you've put the wrong directory, you can try what you whant but it'll not work. you can make it work with this:
take your file and put it in the same folder of your php file
(you'll be able to move it after don't worry, it's about your error)
or on a folder "higher" of your script (just not outside of your www
folder)
change the fopen to ('./$team_id.'png',"rb");
rerun your script file
don't forget this : you can't access a file that is'nt in your "www" folder
(he doesn't found your file because he give you her name: the name come from the $team_id variable)
Generically - This is probably the best way to do file-io in php (as mentioned by #Cendak here)
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ){
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
}else{
// send an error message if you can
}
But it does not work with PHP 7.3, these modifications do,
if(file_exists($filename) && ($fp = fopen($filename,"r") !== false)){
$fp = fopen($filename,"r");
$filedata = fread($fp,filesize($filename));
fclose($fp);
}else{
$filedata = "default-string";
}
I have a basic php script that will write/log to a text document
<?php
$filename = 'php_log.log';
$somecontent = 'writing with fwrite!'.PHP_EOL;
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
error_log('logging with error_log!'.PHP_EOL,3,'php_log.log');
?>
From CLI, if i do php test.php and check php_log.log, I see both writes.
But when I try php test.php &, there is nothing written to php_log.log
Is there some php setting I am unaware of?
Thanks!
Possibly the absence of locking.
Why are writing to the file manually and then with error_log?
Consider file_put_contents() with FILE_APPEND|FILE_LOCK instead. That appends just to the end of the file and takes care of locking.
Enable error_reporting and redirect stderr to a separate file to find out more.
php test.php 2> php_errors.txt &
I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.