2011-09-09 66 views
1

我下面的方法使用數據$FDFData數組創建FDF文件:PHP的fopen成功的一個劇本,但不是另一個

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; 
    } 

我的一個腳本運行的精絕:

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(); 
} 

但我不能讓我的測試代碼運行,因爲我得到:

Unexpected PHP error [fopen(1315558352.fdf) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Permission denied] 

錯誤拋出:

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); 
     } 
    } 
} 

這兩個腳本都在具有正確權限的目錄中運行。我通過瀏覽器運行我的測試腳本,所以並不是我有一個不同的環境。

我一直在堅持如何着手尋找問題。

我的目錄結構:

HOME - PDFPrinter.php 
    | 
    -----tests - PDFPrinterTest.php 
     | 
     ------simpletest - autorun.php 

任何建議,我怎麼能找到這個問題?

非常感謝

更新

我試圖改變我的測試類,以便在那裏唯一的測試功能是:

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"); 
    } 

} 

但異常仍然警告拋出。

然而,從同一目錄中運行一個非常簡單的腳本能正常工作:

$name = "Test.txt"; 
if($fp=fopen($name, 'w')) { 
    fwrite($fp, "Working"); 
} else { 
    throw new Exception("Nope."); 
} 
fclose($fp); 

實際上將創建並寫入文件。

+0

如何safe_mode設置設置?它通常會出錯,因爲出於安全原因,它只能上傳到自己創建的文件夾中。 –

+0

嗨SAFE_MODE對於本地值是'off',對於主值是'on'。當你說「它只能上傳到自己創建的文件夾」時,你指的是什麼?此外,我試圖將我的測試代碼移至與工作代碼相同的文件夾,但仍然出現相同的錯誤。 – Joe

+0

嗨!公寓爲目錄權限,我沒有看到測試失敗的原因。你在運行你的腳本的操作系統是什麼?你有沒有試過從測試目錄運行你的工作? –

回答

1

終於找到了解決方案,即文件名需要是完整的絕對地址,以便由於某種原因在兩個腳本中都能正常工作。這建議in one of the answers for this SO question,我引用下面:

使用fopen($ _ SERVER ['DOCUMENT_ROOT']。'test.txt','a +');

所以我的代碼,我用:

if($fp=fopen($_SERVER['DOCUMENT_ROOT'].$name, 'w')) { 
    fwrite($fp, "Working"); 
} 
0

在您的測試

fwrite("Blah"); 

應該

fwrite($fp, "Blah"); 

我不知道在原來的代碼是什麼問題,但。

+0

這是真的謝謝,但它之前的行失敗,原來的代碼是正確的。我會更新帖子。 – Joe

0

未能打開流:權限被拒絕

有一個重要的程序員的技能每個開發人員應該掌握。
這就是:

要相信自己的眼睛

如果你的PHP告訴你權限被拒絕的 - 所以它是。只需確認一下。這不是什麼大事,但沒有人能爲你做。

+0

我不懷疑它。但我找不到原因。 – Joe

+0

原因顯然不在PHP代碼中。 –

相關問題