PHP fopen succeeding for one script but not another - php

My following method uses an array of data $FDFData to create an FDF file:
public function writeFDFFile($FDFData) {
$fdf_file = time().'.fdf';
$fdf = $this->createFDF(PDF_FORM, $FDFData);
// write the file out
if($fp=fopen($fdf_file,'w')) {
fwrite($fp,$fdf,strlen($fdf));
} else {
throw new Exception('Unable to create file: '.$fdf_file);
}
fclose($fp);
return $fdf_file;
}
One of my scripts runs absolutely fine:
require_once('PDFPrinter.php');
try {
$printer = new PDFPrinter();
$FDFData = $printer->assembleFDFData(9);
$fdf_file = $printer->writeFDFFile($FDFData);
$printer->downloadFile($fdf_file);
}catch(Exception $e) {
echo $e->getMessage();
}
but I can't get my test code to run because I get a:
Unexpected PHP error [fopen(1315558352.fdf) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Permission denied]
error thrown:
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once(dirname(__FILE__) . '/../PDFPrinter.php');
class PDFPrinterTest extends UnitTestCase {
private $printer;
private $FDFData;
function setUp() {
$this->printer = new PDFPrinter();
$this->FDFData = $this->printer->assembleFDFData(5);
}
function testException() {
try {
$this->printer->writeFDFFile($this->FDFData);
$this-assertTrue(true);
} catch(Exception $e) {
$this->assertTrue(false);
}
}
}
Both scripts are run in directories with the correct permissions. I am running my test scripts through the browser as well, so it's not that I have a different environment.
I'm stuck as to how to proceed to find the issue really.
My directory structure:
HOME - PDFPrinter.php
|
-----tests - PDFPrinterTest.php
|
------simpletest - autorun.php
Any suggestions as to how I could find the issue?
Many thanks
Update
I have tried changing my test class so that the only test function in there is:
function testWrite() {
try {
$name = "testing.txt";
if($fp=fopen($name, 'w')) {
fwrite($fp, "Blah");
} else {
throw new Exception("Nope.");
}
$this->pass("All good");
} catch(Exception $e) {
$this->fail("Not good");
}
}
but the exception is still thrown with the warning.
Yet a very simple script run from the same directory works fine:
$name = "Test.txt";
if($fp=fopen($name, 'w')) {
fwrite($fp, "Working");
} else {
throw new Exception("Nope.");
}
fclose($fp);
that will actually create and write to the file.

Finally found the solution which was that the file name needed to be the full absolute address in order for it to work in both scripts for some reason. This was suggested in one of the answers for this SO question which I quote below:
Use fopen($_SERVER['DOCUMENT_ROOT'].'test.txt','a+');
so for my code, I have used:
if($fp=fopen($_SERVER['DOCUMENT_ROOT'].$name, 'w')) {
fwrite($fp, "Working");
}

In your test
fwrite("Blah");
should be
fwrite($fp, "Blah");
I'm not sure what the problem in the original code is though.

failed to open stream: Permission denied
There is one important programmer's skill every developer ought to master.
Here it is:
To trust your eyes
If your PHP telling you that permission is denied - so it is. Just doble-check it. It is not a big deal yet noone can do it for you.

Related

error in getting the fetching path

I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error
Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8
and here is my code to set & get the path (root.php)
<?php
error_reporting( E_ALL );
define("setRealpath", realpath("../"));
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";
try
{
$getPath = array(setRealpath, get_include_path());
if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}
function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}
spl_autoload_register('GetClassFile');
}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}
?>
here is the file where my connection (SqlHandler.php).
<?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";
protected $db = null;
public function __construct()
{
$this->db = $this->getConnection();
}
public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>
and lastly here in this file where i'm trying to check the connection(checkconnection.php)
<?php
error_reporting(E_ALL);
include "./root/root.php";
use \obj\database_connection\SqlHandler;
$checkConnection = new SqlHandler;
echo $checkConnection->checkConnection();
?>
now i found my mistake, the only mistake is that i'm using the old version of php, instead of using php 7.1 version , i'm using php 5. so i change it and it works.

php code like transaction in database?

I have certain code that I want to be run by only one user at a time. I don't want to make son complex lock/session relied system, I just wish to delay the users request our to return some message to try again.
The code is actually ssh/powershell connection so I want to isolate it.
It's there any handy way to do that??
I forgot mention it's laravel/php code.
You need to acquire a "lock" of some sort. If there is no lock, no one is accessing anything. If there is a lock, someone is accessing something and the rest should wait. The easiest way is to implement this using files and acquiring an exclusive lock. I'll post an example class (untested) and example usage. You can derive a working example using the sample code that follows:
class MyLockClass
{
protected $fh = null;
protected $file_path = '';
public function __construct($file_path)
{
$this->file_path = $file_path;
}
public function acquire()
{
$handler = $this->getFileHandler();
return flock($handler, LOCK_EX);
}
public function release($close = false)
{
$handler = $this->getFileHandler();
return flock($handler, LOCK_UN);
if($close)
{
fclose($handler);
$this->fh = null;
}
}
protected function acquireLock($handler)
{
return flock($handler, LOCK_EX);
}
protected function getFileHandler()
{
if(is_null($this->fh))
{
$this->fh = fopen($this->file_path, 'c');
if($this->fh === false)
{
throw new \Exception(sprintf("Unable to open the specified file: %s", $this->file_path));
}
}
return $this->fh;
}
}
Usage:
$lock = new MyLockClass('/my/file/path');
try
{
if($lock->acquire())
{
// Do stuff
$lock->release(true);
}
else
{
// Someone is working, either wait or disconnect the user
}
}
catch(\Exception $e)
{
echo "An error occurred!<br />";
echo $e->getMessage();
}

Warning Error: ftp_get(): Transfer complete. in cakePHP

i am trying to download a zip file from server and save it. i get the following error.
the project is in cakePHP
Downloading /server/biruhxml20140925.zip ...
Warning Error: ftp_get(): Transfer complete. in [(pathprefix)/app/Console/Command/Task/ImportUtilityTask.php, line 214]
//server/biruhxml20140925.zip could not be downloaded to (pathprefix)/files/downloaded_files/bild/biruhxml20140925.zip
biruhxml20140925.zip could not be downloaded as the file is not there yet.
this is the function which makes the call.
public function downloadFTPFile ($remoteFile, $localFile) {
$connection = $this->ftpConnection;
ftp_pasv($this->ftpConnection, true);
$this->out(__('Downloading %s ... ', $remoteFile));
try {
if (ftp_get($connection, $localFile, $remoteFile, FTP_BINARY)) {
$this->out(__('Saved %s', $localFile));
return true;
} else {
$this->out(__('%s could not be downloaded to %s', $remoteFile, $localFile));
return false;
}
} catch (Exception $e) {
#unlink($localFile);
$this->out($e->getMessage());
}
$this->nl();
return false;
}
can anyone suggest a work around to get rid of the warning other then setting debug level 0 in core.php
Have you considered, based on the error message, that the file you try to download is not present on the server?
Your code doesn't do a check if the file is there, I would add that and handle that case accordingly.

Error Handling with files in PHP

Error Handling with files in PHP
$path = '/home/test/files/test.csv';
fopen($path, 'w')
Here I want add an error handling by throwing exceptions, on 'No file or directory is found' and 'No permission to create a file'.
I am using Zend Framework.
By using fopen with write mode, I can create a file. But how to handle it when corresponding folder is not there?
i.e if files folder is not present in root structure.
How to throw an exception when no permission is permitted for creating a file?
Something like this should get you started.
function createFile($filePath)
{
$basePath = dirname($filePath);
if (!is_dir($basePath)) {
throw new Exception($basePath.' is an existing directory');
}
if (!is_writeable($filePath) {
throw new Exception('can not write file to '.$filePath);
}
touch($filePath);
}
Then to call
try {
createFile('path/to/file.csv');
} catch(Exception $e) {
echo $e->getMessage();
}
I suggest, you take a look at this link: http://www.w3schools.com/php/php_ref_filesystem.asp
especially the methods file_exists and is_writable
Like this:
try
{
$path = '/home/test/files/test.csv';
fopen($path, 'w')
}
catch (Exception $e)
{
echo $e;
}
PHP will echo whatever error would arise there.
Though you can also use is_dir or is_writable functions to see if folder exists and has permission respectively:
is_dir(dirname($path)) or die('folder doesnt exist');
is_writable(dirname($path)) or die('folder doesnt have write permission set');
// your rest of the code here now...
But how to handle it when corresponding folder is not there?
When a folder does not exist .. try to create it!
$dir = dirname($file);
if (!is_dir($dir)) {
if (false === #mkdir($dir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
}
} elseif (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to write in the %s directory', $dir));
}
// ... using file_put_contents!

php: autoload exception handling

I'm extending my previous question (Handling exceptions within exception handle) to address my bad coding practice.
I'm trying to delegate autoload errors to a exception handler.
<?php
function __autoload($class_name) {
$file = $class_name.'.php';
try {
if (file_exists($file)) {
include $file;
}else{
throw new loadException("File $file is missing");
}
if(!class_exists($class_name,false)){
throw new loadException("Class $class_name missing in $file");
}
}catch(loadException $e){
header("HTTP/1.0 500 Internal Server Error");
$e->loadErrorPage('500');
exit;
}
return true;
}
class loadException extends Exception {
public function __toString()
{
return get_class($this) . " in {$this->file}({$this->line})".PHP_EOL
."'{$this->message}'".PHP_EOL
. "{$this->getTraceAsString()}";
}
public function loadErrorPage($code){
try {
$page = new pageClass();
echo $page->showPage($code);
}catch(Exception $e){
echo 'fatal error: ', $code;
}
}
}
$test = new testClass();
?>
the above script is supposed to load a 404 page if the testClass.php file is missing, and it works fine, UNLESS the pageClass.php file is missing as well, in which case I see a
"Fatal error: Class 'pageClass' not found in D:\xampp\htdocs\Test\PHP\errorhandle\index.php on line 29" instead of the "fatal error: 500" message
I do not want to add a try/catch block to each and every class autoload (object creation), so i tried this.
What is the proper way of handling this?
Have you tried checking for pageClass early on in the process, since it seems to be necessary even to get the error page out? If it doesn't exist, and if you don't want to write the 404 page w/o any objects (e.g. just HTML), bombing out of execution where that class doesn't exist would seem to be a good path.
Hope that helps.
Thanks,
Joe

Categories