(PHP) fwrite doesn't write but overwrite - php

I want to open the .xml file and write the content of the $xml_doc variable into the file. The problem is, when the file is empty, it refuses to write. It only writes when there is already some text (abc123 for example). I tried to change mode of fopen function to a, a+, w, w+, and w, w+ are simply erase the file content but write nothing.
if($telecharger) {
// Creation du fichier
$nom = "PRELEVEMENT";
$filename= "/home/alc/alcg_si/alcgroup/intranet/documents/prelevement_xml/".$nom."__".$date_prev.".xml";
try {
$file = fopen($filename, 'r+') or die("Error: can't open file.");
chmod($filename, 0777);
fwrite($file, '$xml_doc') or die("Error: can\'t write in file.");
fclose($file);
} catch (Exception $e) {
echo "MERDEEEE<br>";
echo 'Caught exception: ', $e->getMessage(), "\n";
}

File permissions are checked when opening the file. If the file permissions don't allow writing, you need to call chmod() before calling fopen().
You can also replace all the code that calls fopen, fwrite, and fclose with a single call to file_put_contents().
And don't put the variable $xml_doc in single quotes, that prevents expanding the variable. It will write the literal string $xml_doc to the file.
if($telecharger) {
// Creation du fichier
$nom = "PRELEVEMENT";
$filename= "/home/alc/alcg_si/alcgroup/intranet/documents/prelevement_xml/".$nom."__".$date_prev.".xml";
try {
if (file_exists($filename)) {
chmod($filename, 0644) or die("Error: can't change file permissions");
}
file_put_contents($filename, $xml_doc) or die("Error: can\'t write in file.");
} catch (Exception $e) {
echo "MERDEEEE<br>";
echo 'Caught exception: ', $e->getMessage(), "\n";
}

Related

Cannot upload wav file on an Azure blob container using PHP

I need to upload audio files in wav format to an Azure container using the Azure SDK for PHP but the content of the wav does not upload. Indeed, I only have a 0 bytes .wav file in my container so i'm not able to use it.
I have tested several codes but this is the best one I have. I am not an expert in PHP but I force him to use this language to integrate it into a CRM.
When I load a text file it also uploads empty so the problem doesn't come from the way I read the file.
Thanks a lot for your help.
<?php
require_once 'vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
$connectionString = "DefaultEndpointsProtocol=https;AccountName=".getenv('ACCOUNT_NAME').";AccountKey=".getenv('ACCOUNT_KEY');
// Create blob client.
$blobClient = BlobRestProxy::createBlobService($connectionString);
$fileToUpload = "audio.wav";
if (!isset($_GET["Cleanup"])) {
$containerName = "cs-blob-input";
try {
// Getting local file so that we can upload it to Azure
$myfile = fopen($fileToUpload, "w") or die("Unable to open file!");
fclose($myfile);
# Upload file as a block blob
echo "Uploading BlockBlob: ".PHP_EOL;
$content = fopen($fileToUpload, "r");
//Upload blob
$blobClient->createBlockBlob($containerName, $fileToUpload, $content);
// List blobs.
$listBlobsOptions = new ListBlobsOptions();
echo "These are the blobs present in the container: ".PHP_EOL;
do{
$result = $blobClient->listBlobs($containerName, $listBlobsOptions);
foreach ($result->getBlobs() as $blob)
{
echo $blob->getName().PHP_EOL;
}
$listBlobsOptions->setContinuationToken($result->getContinuationToken());
} while($result->getContinuationToken());
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
catch(InvalidArgumentTypeException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
else
{
try{
// Delete container.
echo "Deleting Container".PHP_EOL;
echo $_GET["containerName"].PHP_EOL;
echo "<br />";
$blobClient->deleteContainer($_GET["containerName"]);
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
?>
The problem is here:
// Getting local file so that we can upload it to Azure
$myfile = fopen($fileToUpload, "w") or die("Unable to open file!");
fclose($myfile);
What is happening is, you open a file "audio.wav" for writing.
Based on official docs (See the mode parameter 'w') your file will be created if it not exists. Then, if it exists, it will be truncated to zero size. Then you close the file.
After that you do:
$content = fopen($fileToUpload, "r");
Which reads an empty file. So the uploaded content is => 0 in size

PHP fopen, fwrite and fclose proceed without errors but no file created

I am running PHP 7.0.22, under LAMP, on two ubuntu 16.04.
The following code proceeds without throwing an exception and $tempFile has the value Resource id #4.
try {
// Open temp file for writing
$tempFile = fopen("/var/www/dropbox/temp.lst", "w");
echo "tempfile=" . $tempFile . "<br>";
// Write list of file names to file
for ($x = 0; $x <= $inputFileCount; $x++) {
fwrite($tempFile, $fileNames);
}
// Close temp file
fclose($tempFile);
} catch ( Exception $e ) {
// send error message if you can
echo 'Caught exception: ', $e->getMessage(), "\n";
}
However, no file, by the name of temp.lst, appears in the directory /var/www/dropbox/ which has full write permission.
ls -ld /var/www/dropbox/
drwxrwsrwx 2 ubuntu www 4096 Mar 25 18:13 /var/www/dropbox/
No errors, related to the code, are shown by
cat /var/log/apache2/error.log
fopen, fwrite, fclose don't throw Exceptions, they return errors
Try
try {
// Open temp file for writing
$tempFile = fopen("/var/www/dropbox/temp.lst", "w");
if (false === $tempFile) throw new \RuntimeException("Failed to open file");
echo "tempfile=" . $tempFile . "<br>";
// Write list of file names to file
for ($x = 0; $x <= $inputFileCount; $x++) {
if(false === fwrite($tempFile, $fileNames)) throw new \RuntimeException("Failed to write to file");
}
// Close temp file
if(false === fclose($tempFile)) throw new \RuntimeException("Failed to close file");
} catch ( Exception $e ) {
// send error message if you can
echo 'Caught exception: ', $e->getMessage(), "\n";
}
and you should get some exceptions

fopen(w+): failed to open stream

I'm currently creating a quote which has values that can be changed. It requires PDF conversion.
This conversion is done using wkhtmltopdf, unfortunately the old way I used did not convert the changed values and that is why my script is changed.
However it fails at line 7:
$fp = fopen('w+','/tmp/tmp.html');
The complete script:
<?php
try {
$content = $_REQUEST['content'];
if(!file_exists('/tmp') ){
mkdir('/tmp', 0777);
}
$fp = fopen('w+','/tmp/tmp.html');
if($fp){
fwrite($fp, $content);
fclose($fp);
$filename = '/tmp/out_' . time() .'.pdf'; // output filename
shell_exec('wkhtmltopdf /tmp/tmp.html ' . $filename);
//then eventually ask user for download the result
header("Content-type:application/pdf");
// It will be called output.pdf
header("Content-Disposition:attachment;filename='output.pdf'");
readfile($filename);
}else{
echo 'html file could not be created';
}
} catch (Exception $e) {
echo 'exception: ', $e->getMessage(), "\n";
}
//
I hope anyone could tell me what I'm doing wrong.
If more info is necessary, let me know.

php file download sometimes not working (gzopen, gzwrite, gzclose)

<?php
set_time_limit(0);
$myfile = gzopen($constpath . '.gz', 'w');
if (!$myfile){
throw new \UnexpectedValueException('could not open datafeed.gz file');
}
$mystream = gzopen($constURL, 'r');
if (!$mystream){
throw new \UnexpectedValueException('could not open gzip remote file');
}
echo '1<br>';
while (!gzeof($mystream)){
$data = gzread($mystream, 8096);
gzwrite($myfile, $data);
}
echo '4<br>';
gzclose($mystream);
gzclose($myfile);
echo '5<br>';
echo 'down done';
//begin ungzip
$fp = fopen($constpath . '.csv', 'w');
$gz = gzopen($constpath . '.gz', 'r');
if (!$gz){
throw new \UnexpectedValueException(
'could not open gzip file'
);
}
if (!$fp){
gzclose($gz);
throw new \UnexpectedValueException(
'could not open destination file'
);
}
while (!gzeof($gz)) {
fwrite($fp, gzread($gz, 8096));
}
gzclose($gz);
fclose($fp);
echo 'ungzip done';
?>
Hi,
guys so above is my code, it intermittently allows me to download the gz file then unzip it, however it does not seem to be doing this in any sort of pattern or anything else, is there anything i need to know about how to use these functions like maybe is there a limit on the URL length (it's currently about 2.5K characters) but unfortunately not something i can change. what would people recommend on how to debug if there're bugs? or what i can do?
thanks!
EDIT: something i've noticed is that it is taking an absolute age to create a 25kB file, and previous to that it is 0kB, it then stops at 25kB
when i open the file in nano i get
^_�^H^#^#^#^#^#^#^C^#^#^#��^C^#^#^#^#^#^#^#^#^#
but when i unzip and open in windows there is nothing there?

File from SOAP, how to save?

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.

Categories