使用从表单中获取的指定名称创建一个全新的 html 页面,并使用 PHP 向其添加特定内容

问题描述 投票:0回答:1

我希望我的页面允许我填写一个表单,然后按下提交按钮启动另一个 PHP 文件,该文件首先将数据插入数据库,然后使用从表单中获取的给定 pageName 创建一个全新的页面并添加使用 PHP 向其指定内容。

我的代码是: 数据库连接:

<?php
    
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $dbname = 'hm';
    // Create connection
    $conn = mysqli_connect($servername, $username, $password , $dbname);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
      }      
    echo "Connected successfully";

?>

形式:

<form action="add_recipe_script.php" method="post" enctype=”multipart/form-data”  >
   
    <label>Page Name <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="pageName"  placeholder="Page name" required>
    </div><br/>
    <label>Recipe Name <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rName"  placeholder="Recipe name" required>
    </div><br/>
    
    <label>Recipe Discription:<span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rDisc" placeholder="Recipe Description" required>
    </div><br/>

    <label>Recipe Image:<span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rImg" placeholder="Recipe Image" required>
    </div><br/>
    
    <label >Recipe Category: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rCategory"  placeholder="Recipe Category" required>
    </div><br/>

    <label>No. of Calories: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rTotalCalories"  placeholder="Recipe Calorie" required>
    </div><br/>

    <label>No. of Servings: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rServing"  placeholder="Recipe Servings" required>
    </div><br/>

    <label>Cook time: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rTime"  placeholder="Cook time" required>
    </div><br/>

    <label>Recipe Ingredients: <span style="color: #FF0000">*</span></label>
    <div>
        <textarea name="rIngre"  placeholder="Recipe Ingredients" required></textarea>
    </div><br/>

    <label>Recipe Instructions: <span style="color: #FF0000">*</span></label>
    <div>
        <textarea name="rSteps"  placeholder="Recipe Instructions" required> </textarea>
    </div><br/>

    <label>Fat: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rFat"  placeholder="Recipe fat" required>
    </div><br/>

    <label>Carbs: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rCarb"  placeholder="Recipe carbs" required>
    </div><br/>

    <label>Protein: <span style="color: #FF0000">*</span></label>
    <div>
        <input type="text" name="rPro"  placeholder="Recipe protein" required>
    </div><br/>
    <button type="submit" name="addRecipe">Add Recipe</button>
</form>

PHP文件:

<?php

    include 'connect.php'; 
    if(isset($_POST['addRecipe']))
    {    
        $rName  = $_POST['rName'];
        $rDisc  = $_POST['rDisc'];
        $rImg   = $_POST['rImg'];
        $rCategory  = $_POST['rCategory'];
        $rTotalCalories = $_POST['rTotalCalories'];
        $rServing   = $_POST['rServing'];
        $rTime  = $_POST['rTime'];
        $rIngre = $_POST['rIngre'];
        $rSteps = $_POST['rSteps'];
        $rFat = $_POST['rFat'];
        $rCarb = $_POST['rCarb'];
        $rPro = $_POST['rPro'];
        $pageName = $_POST['pageName'];
        
         $sql = "INSERT INTO recipes ( rName, rDisc, rImg,  rFat, rCarb, rPro, rTotalCalories, rTime, rIngre,
                                        rSteps, rCategory, rServing, pageName)
         VALUES ('$rName', '$rDisc', '$rImg', '$rFat', '$rCarb', '$rPro', '$rTotalCalories', 
                '$rTime', '$rIngre ', '$rSteps', '$rCategory', '$rServing', '$pageName')";
         if (mysqli_query($conn, $sql)) {
            echo "New record has been added successfully !";
         } else {
            echo "Error: " . $sql . ":-" . mysqli_error($conn);
         }
         mysqli_close($conn);
    }
?>

<?php
    $pageName = $_POST['pageName'];
    $newpagecontent = '<html><head><title></title></head><body><p>J</p></body></html>';
    $file = fopen($pageName . '.php', "x");
    fwrite($file, $newpagecontent);
?>

它确实有效并创建了一个新页面,但内容不会显示并且 URL 栏没有 .php 扩展名它只是给出了这个错误: 未找到 在此服务器上找不到请求的 URL。 请帮忙?

php html fopen fwrite
1个回答
0
投票

为了减轻 SQL 注入攻击,您应该 always 在使用任何可能由用户编辑的数据时使用 Prepared Statement,在这种情况下,它是来自 POSTed

form
.

的内容

以下阶段是为了在创建基本 SQL 命令之前首先确保所有必需的变量都存在于 POST 数组中。这些变量用于构造一个值数组,该数组又用于帮助构建在

types
步骤中使用的
bind_param
字符串。然后在调用
bind_param
方法之前将两者提供给
execute

要生成 HTML 页面,可以推断出文件系统(绝对)路径和 Web 路径,并将其用于编写新的 HTML 页面,然后重定向到该新页面。

如果数据库任务和新页面创建是在同一个脚本中完成的,从上面的 PHP 中不清楚。在此代码中,它都是一个脚本/页面——数据库任务未经过测试,但新页面已生成。

<?php
    if( isset(
        $_POST['addRecipe'],
        $_POST['rName'],
        $_POST['rDisc'],
        $_POST['rImg'],
        $_POST['rCategory'],
        $_POST['rTotalCalories'],
        $_POST['rServing'],
        $_POST['rTime'],
        $_POST['rIngre'],
        $_POST['rSteps'],
        $_POST['rFat'],
        $_POST['rCarb'],
        $_POST['rPro'],
        $_POST['pageName']
    )) {
    
        require 'connect.php'; 
        
        # prepare data for insert - in same order as columns in sql below.
        $args=array(
            $_POST['rName'],
            $_POST['rDisc'],
            $_POST['rImg'],
            $_POST['rFat'],
            $_POST['rCarb'],
            $_POST['rPro'],
            $_POST['rTotalCalories'],
            $_POST['rTime'],
            $_POST['rIngre'],
            $_POST['rSteps'],
            $_POST['rCategory'],
            $_POST['rServing'],
            $_POST['pageName']
        );
        # create a string of variable type identifiers for the prepared statement.
        $types=str_repeat( 's', count( $args ) );
        
        # prepare the sql command with placeholders
        $sql='INSERT INTO recipes 
            ( rName, rDisc, rImg, rFat, rCarb, rPro, rTotalCalories, rTime, rIngre, rSteps, rCategory, rServing, pageName )
            VALUES
            ( ?,?,?,?,?,?,?,?,?,?,?,?,? )';
            
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param( $types, ...$args );
        $stmt->execute();
        $stmt->close();
        $conn->close();
        
        #---------------------------------
        # basic HTML template for new page
        $template='
        <html>
            <head>
                <title>%s</title>
            </head>
            <body>
                %s
            </body>
        </html>';
        
        # Find current url & remove filename
        $script=explode( '/', $_SERVER['SCRIPT_NAME'] );
        array_pop( $script );
        
        # What is the newly generated HTML / PHP page to actually contain???
        $content=implode('<br />',$_POST );
        
        # Create suitable filepath to save HTML to
        $html=sprintf( $template, $_POST['pageName'], $content );
        $file=sprintf( '%s/%s.php', __DIR__, $_POST['pageName'] );
        
        # Create suitable webpath for browser to navigate to
        $url=sprintf('%s/%s.php', implode('/',$script), $_POST['pageName'] );
        
        # write the content and redirect to new page
        file_put_contents( $file, $html );
        exit( header( sprintf( 'Location: %s', $url ) ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>POST & Build HTML</title>
        <style>
            label > span{ color:#FF0000 }
            label > span + input,
            label > span + textarea{ display:block; clear:left; }
            form > div{ margin:0.5rem 0; }
        </style>
    </head>
    <body>
    

    <form method='post' enctype='multipart/form-data'>
        <div>
            <label>Page Name <span>*</span>
                <input type='text' name='pageName' placeholder='Page name' required />
            </label>
        </div>
        <div>
            <label>Recipe Name <span>*</span>
                <input type='text' name='rName' placeholder='Recipe name' required />
            </label>
        </div>
        <div>
            <label>Recipe Discription:<span>*</span>
                <input type='text' name='rDisc' placeholder='Recipe Description' required />
            </label>
        </div>
        <div>
            <label>Recipe Image:<span>*</span>
                <input type='text' name='rImg' placeholder='Recipe Image' required />
            </label>
        </div>
        <div>
            <label >Recipe Category: <span>*</span>
                <input type='text' name='rCategory' placeholder='Recipe Category' required />
            </label>
        </div>
        <div>
            <label>No. of Calories: <span>*</span>
                <input type='text' name='rTotalCalories' placeholder='Recipe Calorie' required />
            </label>
        </div>
        <div>
            <label>No. of Servings: <span>*</span>
                <input type='text' name='rServing' placeholder='Recipe Servings' required />
            </label>
        </div>
        <div>
            <label>Cook time: <span>*</span>
                <input type='text' name='rTime' placeholder='Cook time' required />
            </label>
        </div>
        <div>
            <label>Recipe Ingredients: <span>*</span>
                <textarea name='rIngre' placeholder='Recipe Ingredients' required></textarea>
            </label>
        </div>
        <div>
            <label>Recipe Instructions: <span>*</span>
                <textarea name='rSteps' placeholder='Recipe Instructions' required></textarea>
            </label>
        </div>
        <div>
            <label>Fat: <span>*</span>
                <input type='text' name='rFat' placeholder='Recipe fat' required />
            </label>
        </div>
        <div>
            <label>Carbs: <span>*</span>
                <input type='text' name='rCarb' placeholder='Recipe carbs' required />
            </label>
        </div>
        <div>
            <label>Protein: <span>*</span>
                <input type='text' name='rPro' placeholder='Recipe protein' required />
            </label>
        </div>
        
        <button type='submit' name='addRecipe'>Add Recipe</button>
    </form>
    
    
    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.