search
HomeBackend DevelopmentPHP TutorialPHP basic learning: PHP file system

PHP basic learning: PHP file system

May 22, 2018 pm 01:55 PM
phpdocumentsystem

在学习中会经常遇到文件系统,本文将将讲解php文件系统的操作。

 

<?php 
    readfile("/home/paul/text.txt"); 
    $filename = &#39;NoAlike.txt&#39;; 
    $filestring = file_get_contents($filename); 
    echo $filestring; 
//     fopen\fread\fclose操作读取文件 
    $fp = fopen(&#39;NoAlike.txt&#39;, "r");//r、r+、w、w+ 
    $contents = fread($fp, 1024); 
    fclose($fp); 
    var_dump($fp); 
       
    $date = "在PHP中文网学好PHP,妹子票子不在话下!"; 
    $numbyte = file_put_contents(&#39;binggege.txt&#39;, $data); 
    if ($numbyte) { 
        echo &#39;写入成功,我们读取看看结果试试:&#39;; 
        echo file_get_contents(&#39;binggege.txt&#39;); 
    }else{ 
        echo &#39;写入失败或者没有权限,注意检查&#39;; 
    } 
       
//     fwrite配合fopen进行写入操作 
    $filename = &#39;test.txt&#39;; 
    $fp = fopen($filename, "r+");//x、a 
    $len = fwrite($fp, &#39;我是一只来自南方的狼,一直在&#39;); 
       
    //创建临时文件 
    $handle = tmpfile(); 
    $numbytes = fwrite($handle, &#39;写入临时文件&#39;); 
    fclose($handle); 
    echo &#39;向临时文件中写入了&#39;.$numbytes.&#39;个字节&#39;; 
       
    //移动、拷贝和删除文件 
    rename($oldname, $newname); 
    $filename = &#39;test.txt&#39;; 
    $filename2 = $filename.&#39;old&#39;; 
    rename($oldname, $oldname2); 
    copy($oldname, $oldname2); 
    if (unlink($filename)) { 
        echo  "删除文件成功$filename!\n"; 
    }else { 
        echo "sc $filename失败!\n"; 
    } 
       
    //检测文件属性函数 
    file_exists($filename);//文件是否存在 
    is_readable($filename);//文件是否可读 
    is_writable($filename);//文件是否可写 
    is_executable($filename);//文件是否可执行 
    is_file($filename);//是否是文件 
    is_dir($filename);//是否是目录 
    clearstatcache();//清楚文件的状态缓存 
    if (file_exists(&#39;install.lock&#39;)) { 
        echo &#39;已安装,请不要再次安装&#39;; 
        exit; 
    } 
       
    //文件常用函数和常量 
    $_current_file = str_replace( 
        array(&#39;/&#39;,&#39;\\&#39;), DIRECTORY_SEPARATOR, __FILE___); 
    define(&#39;_CUR_FILE_&#39;, $_current_file); 
    echo _CUR_FILE_; 
    rewind($handle);//指针回到开始处 
    fseek($handle, $offset);//文件指针向后移动指定字符 
    $fp = fopen(&#39;demo2.txt&#39;, &#39;r+&#39;); 
    echo fread($fp, 10); 
    rewind($fp); 
    echo &#39;<br>&#39;; 
    echo fread($fp, 10); 
    echo &#39;<br>&#39;; 
    echo fseek($fp, 10); 
    echo &#39;<br>&#39;; 
    echo fread($fp, 10); 
    echo &#39;<br>&#39;; 
    fclose($fp); 
    $filename = &#39;demo.txt&#39;; 
    echo $filename . &#39;文件大小为:&#39;. 
        filesize($filename).&#39;bytes&#39;; 
    filectime($filename);//文件创建时间 
    filemtime($filename);//文件修改时间 
    fileatime($filename);//文件上次访问时间 
    $filename = &#39;demo.txt&#39;; 
    if (file_exists($filename)) { 
        echo &#39;$filename文件的上次访问时间是:&#39;.date("Y-m-d H:i:s" 
            ,filectime($filename)); 
        echo &#39;$filename文件的上创建时间是:&#39;.date("Y-m-d H:i:s" 
            ,filectime($filename)); 
        echo &#39;$filename文件的上次修改时间是:&#39;.date("Y-m-d H:i:s" 
            ,filemtime($filename)); 
    } 
       
    //文件锁处理机制 
    $fp = fopen("demo.txt", "r+"); 
    if (flock($fp, LOCK_EX)) { 
        fwrite($fp, "文件这个时候被我占用了哟\n"); 
        flock($fp, LOCK_UN); 
    }else { 
        echo "锁失败,可能有人在操作,这个时候不能将文件上锁"; 
    } 
    fclose($fp); 
       
    //目录处理函数 
    $dir = "d:/"; 
    if (is_dir($dir)) { 
        if ($dh = opendir($dir)) { 
            echo readdir($dh).&#39;<br />&#39;; 
            echo readdir($dh).&#39;<br />&#39;; 
            echo readdir($dh).&#39;<br />&#39;; 
            echo readdir($dh).&#39;<br />&#39;; 
            closedir($dh); 
        }; 
    } 
    $dir = "d:/"; 
    if (is_dir($dir)) { 
        if ($dh = opendir($dir)) { 
            while (($file = readdir($dh)) !== false){ 
                echo "文件名为:$file : 
                文件的类型是:".filetype($dir.$file).&#39;<br />&#39;; 
            } 
            closedir($dh); 
        } 
    }     
    //文件权限设置 
    chmod("/var/wwwroot/index.html", 755); 
    chmod("/var/wwwroot/index.html", "u+rwx,go+rx"); 
    chmod("/somedir/somefile", 0755); 
    //文件路径函数 
    pathinfo($path);//返回文件的各个组成部分 
    basename($path);//返回文件名 
    dirname($path);//文件目录部分 
    parse_url($url);//网址拆解成各部分 
    http_build_query($query_data);//生成url中的query字符串 
    http_build_url();//生成一个url 
    $date = [ 
        &#39;username&#39;=>&#39;php&#39;, 
        &#39;area&#39;=>&#39;hubei&#39; 
    ]; 
    echo http_build_query($date); 
    $path_parts = pathinfo(&#39;d:/www/index.inc.php&#39;); 
    echo &#39;文件目录名:&#39;.$path_parts[&#39;dirname&#39;]."<br />"; 
    echo &#39;文件全名:&#39;.$path_parts[&#39;basename&#39;]."<br />"; 
    echo &#39;文件扩展名:&#39;.$path_parts[&#39;extension&#39;]."<br />"; 
    echo &#39;不包含扩展的文件名:&#39;.$path_parts[&#39;filename&#39;]."<br />"; 
    echo "1: ".basename("d:/www/index.d",".d").PHP_EOL; 
    echo "2: ".basename("d:/www/index.php").PHP_EOL; 
    echo "3: ".basename("d:/www/passwd").PHP_EOL; 
    $url = &#39;https://username:password@hostname:9090/path?arg=value#anchor&#39;; 
    var_dump(parse_url($url));   
    //文件留言本 
//     date_default_timezone_set(&#39;PRC&#39;); 
    @$string = file_get_contents(&#39;message.txt&#39;); 
    if (!empty($string)) { 
        $string = rtrim($string, &#39;&^&#39;); 
        $arr = explode(&#39;&^&#39;, $string); 
        foreach ($arr as $value){ 
            list($username, $content, $time) = explode(&#39;$#&#39;, $value); 
            echo &#39;用户名为<font color="gree">&#39;.$username.&#39;</font>&#39;; 
            echo &#39;<hr />&#39;; 
        } 
    } 
    $fp=fopen(&#39;message.txt&#39;, &#39;a&#39;); 
    $time=time(); 
    $username=trim(@$_POST[&#39;username&#39;]); 
    $content=trim(@$_POST[&#39;content&#39;]); 
    if ($username & $content) { 
        $string=$username.&#39;$#&#39;.$content.&#39;$#&#39;.$time.&#39;&^&#39;; 
        fwrite($fp, $string); 
        fclose($fp); 
    }  
?> 
<h1 id="基于文本的留言本演示">基于文本的留言本演示</h1> 
<form action="write.php" method="post"> 
    用户名:<input type="text" name="username" /><br /> 
    留言内容:<textarea name="content"></textarea><br /> 
  <input type="submit" value="提交" /> 
</form> 
<!-- 实现修改配置文件的实例 --> 
<?php 
    include &#39;config.php&#39;; 
?> 
<form action="edit.php" method="post"> 
    <input type="text" name="DB_HOST" value="<?php echo DB_HOST;?>" /><br /> 
    <input type="text" name="DB_USER" value="<?php echo DB_USER;?>" /><br /> 
    <input type="text" name="DB_PWD" value="<?php echo DB_PWD;?>" /><br /> 
    <input type="text" name="DB_NAME" value="<?php echo DB_NAME;?>" /><br /> 
    <input type="submit" value="修改" /> 
</form> 
   
<!-- edit.php --> 
<?php 
    $string=file_get_contents(&#39;config.php&#39;); 
    foreach ($_POST as $key=>$val){ 
        $yx="/define′$key′,′.∗?′′$key′,′.∗?′;/"; 
        $re="define(&#39;$key&#39;,&#39;$val&#39;);"; 
        $string=preg_replace($yx, $re, $string); 
    } 
       
    file_put_contents(&#39;config.php&#39;, $string); 
    echo &#39;修改成功&#39;; 
?> 
<!-- config.php --> 
<?php 
    define(&#39;DB_HOST&#39;, &#39;localhost1&#39;); 
    define(&#39;DB_USER&#39;, &#39;root1&#39;); 
    define(&#39;DB_PWD&#39;, &#39;root1&#39;); 
    define(&#39;DB_NAME&#39;, &#39;neirong1&#39;); 
?>

本文讲解了php文件系统的操作,更多相关知识请关注php中文网。

相关推荐:

php基础学习:图像处理

通过cURL来做小偷程序

php会话管理和控制

The above is the detailed content of PHP basic learning: PHP file system. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment