【解決方法】PHP 内に Python コードを実装する方法は?

プログラミングQA


ユーザーが画像をアップロードできる e コマース Web サイトを作成しました。 Web サイトは、アップロードされた画像内のオブジェクトを認識し、キーワードを生成するように設計されています。 ただし、Python コードを PHP コードと統合するという課題に直面しています。 PHP ページは現在、localhost ポート 8080 で実行されていますが、Python コードはポート 127.0.0.1.5000 で実行されており、両方とも異なるポートで実行されています。 Python と PHP のコードを統合するのに助けが必要です。

Pythonコードを実行するために、cmdを介していくつかのパッケージをインストールしました-
1.pip installフラスコ
2. pip インストール numpy
3. pip インストール テンソルフロー
4. ピップ ハード インストール
5.ピップインストールピロー

私が試したこと:

# Python Code -

import os
from flask import Flask, render_template, request
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from keras.applications.resnet_v2 import preprocess_input as resnet152v2_preprocess_input
from keras.applications.resnet_v2 import ResNet152V2
from keras.applications.imagenet_utils import decode_predictions

# Load the pre-trained ResNet152V2 model
model = ResNet152V2(weights='imagenet')

# Define a dictionary to map the original class names to new class names
class_dict = {
    'notebook': 'laptop',
    'cellular_telephone': 'Smartphone',
    'hand-held_computer': 'Smartphone',
    'remote_control': 'Smartphone',
    'iPod': 'Smartphone',
    'microphone': 'Headphone',
    'espresso_maker': 'Headphone',
    'washer': 'Washing Machine',
    'analog_clock': 'Watch',
    'digital_watch': 'Watch',
    'reflex_camera': 'Camera',
    'vending_machine': 'Fridge',
    'pill_bottle': 'Water Bottle',
    'water_bottle': 'Water Bottle',
    'ashcan': 'Fridge'
    
}

app = Flask(__name__)

# Define the upload folder
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Define the allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS


def allowed_file(filename):
    """Function to check if the file extension is allowed"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    # Check if a file was submitted with the request
    if request.method == "POST":
        if 'file' not in request.files:
            return render_template('search_page.php', message='No file selected')
        file = request.files['file']

        # Check if the file is an allowed file type
        if not allowed_file(file.filename):
            return render_template('search_page.php', message='File type not allowed')

        # Save the file to the upload folder
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        # Load the input image
        img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        img = load_img(img_path, target_size=(224, 224))

        # Preprocess the input image
        img = img_to_array(img)
        img = np.expand_dims(img, axis=0)
        img = resnet152v2_preprocess_input(img)

        # Make a prediction
        preds = model.predict(img)

        # Decode the prediction and print the predicted class
        decoded_preds = decode_predictions(preds, top=1)[0]
        for pred in decoded_preds:
            # Replace the original class name with the new class name
            pred = (pred[0], class_dict.get(pred[1], pred[1]), pred[2])
            message = 'Predicted: {} with probability {}'.format(pred[1], pred[2])

        # Render the HTML template with the predicted class
        return render_template('search_page.php', message=message, filename=filename)

    # Render the HTML template for GET requests
    return render_template('search_page.php')


@app.route('/view/<filename>')
def view_image(filename):
    """Function to display an uploaded image"""
    return '<img src="https://www.codeproject.com/uploads/{}">'.format(filename)



if __name__ == '__main__':
    app.run(debug=True, port=8080)

<!-- PHP Code -->
<?php

include 'components/connect.php';

session_start();

if(isset($_SESSION['user_id'])){
   $user_id = $_SESSION['user_id'];
}else{
   $user_id = '';
};



?>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>search page</title>
   
   <!-- font awesome cdn link  -->
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

   <!-- custom css file link  -->
   <link rel="stylesheet" href="css/style.css">

</head>
<body>
   
<?php include 'components/user_header.php'; ?>


<section class="search-form">
   <form action="" method="post">
      <input type="text" name="search_box" placeholder="search here..." maxlength="100" class="box" required>
      <button type="submit" class="fas fa-search" name="search_btn"></button>
   </form>
</section>
<section class="search-form">
<form method="POST" enctype="multipart/form-data">

            <input type="file" name="file" id="file">
            <br><br>
            <button type="button" onclick="previewImage()">View</button>
            <br><br>
            <img src="" id="imgPreview" style="display:none;max-width:300px;max-height:300px;">
            <br><br>
            
        </form>
        <input type="submit" value="Upload">
   
     
        
        
   <script type="text/javascript">
      
            function previewImage() {
                var preview = document.getElementById("imgPreview");
                var file    = document.getElementById("file").files[0];
                var reader  = new FileReader();

                reader.onloadend = function () {
                    preview.src = reader.result;
                    preview.style.display = "block";
                }

                if (file) {
                    reader.readAsDataURL(file);
                } else {
                    preview.src = "";
                    preview.style.display = "none";
                }
            }
        </script>
</section>
</section>



<section class="products" style="padding-top: 0; min-height:100vh;">

   <div class="box-container">

   <?php
     if(isset($_POST['search_box']) OR isset($_POST['search_btn'])){
     $search_box = $_POST['search_box'];
     $select_products = $conn->prepare("SELECT * FROM `products` WHERE name LIKE '%{$search_box}%'"); 
     $select_products->execute();
     if($select_products->rowCount() > 0){
      while($fetch_product = $select_products->fetch(PDO::FETCH_ASSOC)){
   ?>
   <form action="" method="post" class="box">
      <input type="hidden" name="pid" value="<?= $fetch_product['id']; ?>">
      <input type="hidden" name="name" value="<?= $fetch_product['name']; ?>">
      <input type="hidden" name="price" value="<?= $fetch_product['price']; ?>">
      <input type="hidden" name="image" value="<?= $fetch_product['image_01']; ?>">
      
      <a href="quick_view.php?pid=<?= $fetch_product['id']; ?>" class="fas fa-eye"></a>
      <img src="uploaded_img/<?= $fetch_product['image_01']; ?>" alt="">
      <div class="name"><?= $fetch_product['name']; ?></div>
      <div class="flex">
         <div class="price"><span>Rs. </span><?= $fetch_product['price']; ?><span>/-</span></div>
         <input type="number" name="qty" class="qty" min="1" max="99" onkeypress="if(this.value.length == 2) return false;" value="1">
      </div>
      <input type="submit" value="add to cart" class="btn" name="add_to_cart">
   </form>
   <?php
         }
      }else{
         echo '<p class="empty">no products found!</p>';
      }
   }
   ?>

   </div>

</section>


<?php include 'components/footer.php'; ?>

<script src="js/script.js"></script>

</body>
</html>

解決策 1

そんなことしないで! 文字列を連結して SQL コマンドを作成しないでください。 データベース全体を破壊する可能性のある、偶発的または意図的な SQL インジェクション攻撃にさらされる可能性があります。 代わりに、常にパラメーター化されたクエリを使用してください。

文字列を連結すると、SQL が次のようなコマンドを受け取るため、問題が発生します。

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

ユーザーが追加した引用符は、SQL に関する限り文字列を終了させ、問題が発生します。 しかし、それはもっと悪いかもしれません。 代わりに「x’;DROP TABLE MyTable;–」と入力すると、SQL は非常に異なるコマンドを受け取ります。

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

どの SQL が 3 つの別個のコマンドとして認識されるか:

SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全に有効な SELECT

SQL
DROP TABLE MyTable;

完全に有効な「テーブルの削除」コマンド

SQL
--'

そして、それ以外はすべてコメントです。
一致する行を選択し、DB からテーブルを削除し、それ以外は無視します。

したがって、常にパラメーター化されたクエリを使用してください。 または、DB をバックアップから頻繁に復元する準備をしてください。 バックアップは定期的に取っていますよね?

コメント

タイトルとURLをコピーしました