![](/img/trans.png)
[英]how to upload an image file from a PC (localhost) to a directory located on server (eg. godaddy.com) in PHP?
[英]Delete image file from directory in PHP on remote server and localhost
我試圖弄清楚,如何從遠程服務器和本地主機上的目錄文件夾中正確刪除帶有summernote的圖像文件。
因此,圖像從 Summernote 編輯器成功上傳並按目錄路徑定位:
C:/xampp/htdocs/user/blog/uploads/img-uploads/154_20220702.png
和C:\xampp\htdocs\user\blog\admin\editor-delete.php
代碼:
<?php
$src = $_POST['src'];
$path = "../uploads/img-uploads/";
$dir = basename($path);
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
?>
或者
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
警告:unlink(): http 不允許在 C:\xampp\htdocs\user\blog\admin\editor-delete.ZE1BFD762321E409CEE364AC0B6E8491 中取消鏈接
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($_SERVER['DOCUMENT_ROOT'] . $file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
本地主機正確路徑必須是C:/xampp/htdocs/blog/uploads/img-uploads/154_20220702.png
,但使用unlink($_SERVER['DOCUMENT_ROOT'].'/'. $file_name);
該路徑包含額外的http://localhost/user/
在C:/xampp/htdocs/http://localhost/user/blog/uploads/img-uploads/154_20220702.png
警告:取消鏈接(C:/xampp/htdocshttp://localhost/user/blog/uploads/img-uploads/154_20220702.png):C:\xampp\htdocs\user\blog\admin\editor 中沒有這樣的文件或目錄-delete.php
文件刪除成功
jquery-3.6.0.min.js:5177 XHR 完成加載:POST “http://localhost/user/blog/admin/editor-delete.php”。
我無法完全測試這一點,但我認為您可以像這樣更改editor-delete.php
腳本。 從問題中引用的路徑來看,您需要通過將遍歷文件結構的管理目錄留給uploads/img-uploads
來構建絕對路徑,因此chdir
和getcwd
是兩個有用的功能。 代碼中的注釋說明了我的意思。
顯示File Delete Successfully
的代碼段基於始終為真(有效)的變量,而不是實際unlink
操作的更有意義的結果,因此您應該使用該返回值來分叉您的程序邏輯。
<?php
/*
C:\xampp\htdocs\user\blog\admin\editor-delete.php
so:
chdir('../') leads to C:\xampp\htdocs\user\blog\
chdir('../uploads/img-uploads') should lead to C:\xampp\htdocs\user\blog\uploads\img-uploads
*/
if( isset( $_POST['src'] ) ){
# Change working directory for current script operations
# - go up one level out of "admin" and into the uploads folder.
chdir('../uploads/img-uploads');
# default value for use later in output message
$status=false;
# construct the full path to local file using getcwd() to find working directory.
$path=sprintf( '%s/%s', getcwd(), basename( $_POST['src'] ) );
# if the file exists - delete it or warn ( inspect the path! )
if( file_exists( $path ) )$status=@unlink( $path );
else exit( sprintf( 'Unable to find file: "%s"', $path ) );
# prevent cached results tainting file checks
clearstatcache();
echo $status ? 'File deleted successfully' : 'Sorry, that file could not be deleted';
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.