php FILES not getting inserted into database

Hello so I am currently trying to build an ecommerce website as a project but when I try to insert a product into my database everything but the image gets inserted anybody who could give me any advice
in this problem will be a huge help. Below I posted the entire code in case there are any underlying problems but I think the problem is mostly in the product

image part of the code again thank you for any help because I have been stuck in this problem for a long time.

<?php

        include('../includes/connect.php');
 
        if(isset($_POST['insert_product'])){ 
            

        $product_tile=$_POST['product_title'];
        $product_description=$_POST['product_description'];
        $product_keyword=$_POST['product_keyword'];
        $product_categories=$_POST['product_categories'];
        $product_brands=$_POST['product_brands'];
        $product_price=$_POST['product_price'];
        $product_status='true';



 This is the php code:
$product_image = " ";
$tmp_image = " ";
if(!empty($_FILES["product_image"]["name"])){ 
 $product_image = mysql_real_escape_string($_FILES["product_image"]["name"]);
 $tmp_image = mysql_real_escape_string(move_uploaded_file($_FILES["product_image"]["tmp_name"]));
}


         if($product_tile=='' or $product_description=='' or $product_keyword=='' or    $product_categories=='' or $product_brands=='' or $product_image=='' or $product_price==''  ){
         echo"alert('Please fill all the available fields')";
         exit();
         }else{
              
            move_uploaded_file($tmp_image,"./product_image/$product_image");

        $insert_product="insert into `products`  (product_name,product_description,product_keyword,category_id,brand_id,product_image,product_price,date,status) values ('$product_tile','$product_description','$product_keyword','$product_categories','$product_brands','$productt_image','$product_price',
        NOW(),'$product_status')";
        $result_query=mysqli_query($con,$insert_product);}}
        if($result_query){
         echo"alert('Successfully inserted the product')";
        }

?>

-----------------------------------------------------------------------------------------------------------

This is the html code:

 
                Product Name
                <input type="text" name="product_title" id="product_title" class="form-control"
                    placeholder="Enter product name" autocomplete="off" required>
        

        <!-- description -->
    
            <form action="" method="post" enctype="multipartform-data">
                <label for="product_description" class="form-label">Product Description</label>
                <input type="text" name="product_description" id="product_description" class="form-control"
                    placeholder="Enter product description" autocomplete="off" required>
        </div>
    
        <!-- keyword -->
    
            <form action="" method="post" enctype="multipartform-data">
                <label for="product_keyword" class="form-label">Product Keyword</label>
                <input type="text" name="product_keyword" id="product_keyword" class="form-control"
                    placeholder="Enter product keyword" autocomplete="off" required>
    
    
        <!-- categories -->
            <select name="product_categories" class="form-select" id="">
                <option value="">Select Categories</option>
    
                <?php
               $select_categories="Select * from `categories`";
               $result_categories = mysqli_query($con,$select_categories);
               while($row_data=mysqli_fetch_assoc($result_categories)){
                $category_name=$row_data['category_name'];
                $category_id=$row_data['category_id'];
                echo " <option value='$category_id'>$category_name</option> ";
               }
                ?>
    
            </select>
     
    
        <!-- brands -->
    
            <select name="product_brands" class="form-select" id="">
                <option value="">Select Brands</option>
                <?php
               $select_brands="Select * from `brands`";
               $result_brands = mysqli_query($con,$select_brands);
               while($row_data=mysqli_fetch_assoc($result_brands)){
                $brand_name=$row_data['brand_name'];
                $brand_id=$row_data['brand_id'];
                echo " <option value='$brand_id'>$brand_name</option> ";
               }
                ?>
            </select>
      
    
        <!-- Image -->
    
            <form action="" method="post" enctype="multipartform-data">
                <label for="product_image" class="form-label">Product Image</label>
                <input type="file" name="product_image" id="product_image" class="form-control" autocomplete="off"
                    required>
     
    
        <!-- price -->
    
            <form action="" method="post" enctype="multipartform-data">
                <label for="product_price" class="form-label">Product Price</label>
                <input type="text" name="product_price" id="product_price" class="form-control"
                    placeholder="Enter product price" autocomplete="off" required>
       
    
        <!-- submit -->
            <form action="" method="post" enctype="multipartform-data">
        <input type="submit" value="Insert Product" name="insert_product" class="btn btn-info mb-3 px-3">

Retrieve URL parts after rewrite in WordPress

I am trying to retrieve parts oft an URL in a WordPress installation after paths have been rewritten.
The Parameter I would like to get is a 13 digit number added to the post/page.
E.g. the user is requesting this URL: https://www.example.com/service/1234567892468/ and the path gets rewritten to https://www.example.com/service/. How may I restore the 13 digit parameter.
I am using PHP-snippets in the destination page.

I already tried to use Server-Variables. Maybe the rewrite rules could be adopted for those paths to rewrite to GET parameters that will be kept in the path and be retrieved by the destimation page. Or every URL is checked for the “service/0000000000000” pattern and the parameter is stored in a glonbal or session variable.

HTTP 500 error when submit a html/php form [closed]

Im trying to send from the form.html the “email” and “importe” imput value fields to pay.php via POST. But when I send the form it throws an HTTP error 500.

This is the code.

form.html

<form method="post" action="pay.php">
   <input name="importe" id="importe" required/>
   <input type="email" id="email" name="email" required/>
   <input type="submit" value="Submit">
</form>

pay.php

$key $secret and API_URL have other values of course, I have censored it with ****

<?php

private $key = "******************";
private $secret = "******************";

const API_URL = '***********************';
const API_VERSION = 'v2';



$timestamp = date("YmdHis");


try {
  $endPoint = 'invoices/create';
            
  $postData = json_encode([
    'timer' => false,
    'title' => 'Orden ' . $timestamp,
    'currency' => 'EUR',
    'amount' => $_POST["importe"],
    'foreign_id' => $timestamp . rand(),
    'url_success' => "https://sample.com",
    'url_failed' => "https://sample2.com",
    'email_user' => $_POST["email"],
  ]);
  
  $signature = hash_hmac('sha512', $postData, $this->secret);

  $url = self::API_URL . self::API_VERSION . '/' . $endPoint;
  $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246';
            
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-Processing-Key: ' . $this->key,
    'X-Processing-Signature: ' . $signature,
    'Content-Type: application/json'
  ]);
  
  $result = curl_exec($ch);
  curl_close($ch);
  
  $result = json_decode($result);
  var_dump($result):

} catch (Exception $e) {
  var_dump($e);
}

print "Result = ".$result;

exit;

?>

Thanks for the help!

How to put numbers in table using php

I have a list of TMDB ID then Season numbers and episodes number..

I want data to display like this

Is it possible to put them in table like that..?
The way to repeating listing tmdbid in that table till episodes reach it end..

Then list another tmdb id.. repeating till episode number reach it end..

And when season numbers and episodes numbers rich it end

it should go to new tmdbid.. then list it seasons and episodes..

Is it possible..?

I have variable

$tmdbidlist = it list tmdb ids

$seasonslist = it list seasons numbers from $tmdblist

$episodeslist = it list episodes numbers from $seasonslist

Thanks in Advance

I have tried to list tmdbids, seasons and episodes numbers

I expect it to repeating listing tmdbid in that table till episodes reach it end..

Then list another tmdb id.. repeating till episode number reach it end..

And when season numbers and episodes numbers rich it end

it should go to new tmdbid.. then list it seasons and episodes..

PHP and Bootstrap compiler for local development of web app [closed]

Looking for a ParcelJS type Bootstrap 5 compiler.

I am developing a web app, usually I do it on the server working remotely, save, and refresh the browser on the iOS simulator. I am looking for something I can do this locally faster. I have MAMP that handles the PHP server locally but I am trying to get BS5 compiled scss files into .php pages.

Is there a build tool that can handle this type of development?

I tried ParcelJS and it does a great job of compiling the scss, sass, and html pages but it does not recognize the .php extension on files. I need to include some php scripts into the app to access $_SESSION variables on the index page.

Show ONLY the first PARENT taxonomy and its CHILDREN

I need to foreach loop the first parent taxonomy and its children ONLY.

I’ve managed to get all the parents and their children to loop out, but can’t restrict it to just the first set, in this case the summer taxonomies only.

<?php 
// Taxonomy
$taxonomyName = "classification";

// Parent Taxonomy
$parent_terms = get_terms(

$taxonomyName, array(
    'parent' => 0, 
    'orderby' => 'slug', 
    'hide_empty' => true
    ));   

foreach ( $parent_terms as $parent_term ) { 
    echo '<a class="category-tile" href="' . get_term_link( $parent_term ) . '">' . $parent_term->name . '</a>';

// Child Taxonomies
$child_terms = get_terms(
    
$taxonomyName, array(
    'parent' => $parent_term->term_id, 
    'orderby' => 'ASC', 
    'hide_empty' => true
    ));      

foreach ($child_terms as $child_term) {
    echo '<a class="category-tile" href="' . get_term_link( $child_term ) . '">' . $child_term->name . '</a>'; 
}
} ?>

See screen grab of the results and what i’d like to exclude.

Combining numbers with letters of a string [closed]

I have random string from DB in form: city street_name number or street_name number.
Ex: Olsztyn 3 Maja 51, Kraków Dworcowa 12, Gdańska 11 a.

I need convert this string to form:

  • Olsztyn%3%Maja 51
  • Kraków%Dworcowa 12
  • Gdańska 11a

My code:

$addres = $this->getAddress();
$street = str_replace(" ", "%", $street);

My code is wrong because i have in result:

  • Olsztyn%3%Maja%51
  • Kraków%Dworcowa%12
  • Gdańska%11%a

How can i repair it?

Please help me

the attribute “autocomplete” not working in Symfony

I had installed symfony/ux-autocomplete, and then i create this form

class RechercheType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('nom', EntityType::class, [
                'class' => Serveurs::class,
                'autocomplete' => true,
            ])
            ->add('Rechercher', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Serveurs::class,
        ]);
    }
}

but the Autocomplete is not working, i can’t write in my form field, i can just select the choices.
can you help me please.

I tried many things that I found in many forums but I did not find a solution

the form refresh the page after the second submit

I’m having trouble with the send message form, but the issue is strange since when I initially submitted it, the page didn’t refresh; yet, when I submitted it again, the form refreshed and the sent data was added to the url as a querystring.

Form

 <form id="form">
                    @csrf
                    <input type="text" id="inputMessage" class="w-full bg-gray-300 p-4 outline-none border border-t-2 focus:bg-white">
                    <input type="text" id="touserId" name="touserId" value="{{$user->user_id}}" hidden>
                    <input type="text" hidden id="room-id" name="roomid" value="{{$room_id}}">
                    <button type="submit" id="submit-button" class="absolute left-0 ml-3 mt-3 bg-blue-400 text-white rounded-full text-center w-10 h-10"><i class="fa-solid fa-paper-plane mt-2 mr-1"></i></button>
                </form>

javascript

    let form = document.getElementById('form');

form.addEventListener('submit',function(event){
    event.preventDefault();
    const userInput = inputMessage.value;
    

        $.ajax({
            method: "POST",
            url: "/send",
            data: {
            message: userInput,
            roomid:roomId,
            touserId:toUserId,
            _token: token
            },
        });
      
        let message = {
            id:{{auth()->id()}},
            name:"{{auth()->user()->display_name}}",
            message:userInput
        };
        create_message(message)

        inputMessage.value="";
       
})

How to delete a single record from pivot table

I have made my own Access Control List with Laravel 9 and basically, I made also a Many To Many relationships between User & Role:

User Model:

public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

Role Model:

public function users()
    {
        return $this->belongsToMany(User::class);
    }

Then I created a page to see the current roles of user admins:

$roles = Role::latest()->with('users')->paginate(20);
return view('Admin.levelAdmins.all' , compact('roles'));

And in the Blade, I put this as <tbody>:

@foreach($roles as $role)
    @if(count($role->users))
        @foreach($role->users as $user)
            <tr>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td>{{ $role->name }} - {{ $role->label }}</td>
                <td>
                    <form action="{{ route('adm.level.destroy'  , ['user' => $user->id]) }}" method="post">
                        {{ method_field('delete') }}
                        {{ csrf_field() }}
                        <div class="btn-group btn-group-xs">
                            <a href="{{ route('adm.level.edit' , ['user' => $user->id]) }}"  class="btn btn-primary">Edit</a>
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </div>
                    </form>
                </td>
            </tr>
        @endforeach
    @endif
@endforeach

And it properly shows the results like this:

enter image description here

But my problem is with the DELETE button which should delete the related role. But because the pivot table does not have primary table id, I don’t know how to do that!

Firsly I put this as the action:

public function destroy(User $user)
    {
        $user->roles()->detach();
        return redirect()->route('adm.level.index');
    }

But this is wrong since it deletes all the roles of the user and not just one of them.

So how can I delete a role of a user from this table with Eloquent relationships?

Here is also my role_user table structures:

Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->primary(['role_id','user_id']);
        });

I would really appreciate any idea or suggestion coming from you guys…

Thanks in advance.

Invalid csrf token after log out – PHP Symfony

When remember me token lifetime value expired, my app will automatically log me out and the login page will be displayed. When I attempt to log back in, I receive an error message stating “invalid csrf token”. Subsequently, the page refreshes and takes me back to the login page. However, upon my second attempt to log in, it works fine. Can you please tell me what is the default lifetime value of a CSRF token in PHP Symfony, and if it’s possible to adjust this value?
Should the new csrf token be generated automatically when we open the login page? Any ideas for resolving this issue

By using php agi getting an error not found can anyone help me to resolve the issue

Here is my call.php file (Not working with the script). by getting value directly from database

• How to get extension number from database dynamically (without storing the value manually in extension.conf file). write the script for extension.conf file.

• How to add destination number from database dynamically (without storing the value manually in extension.conf file). write the script for extension.conf file.

#!/usr/bin/php -q
<?php
$dbusername = "asterisk";
$dbname     = "myphonesystems";
$dbpass     = "Asterisk@123";
$dbhost     = "127.0.0.1";

// Connect to the database
$conn = mysqli_connect("$dbhost", "$dbusername", "$dbpass", "$dbname");

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

// Import the PHPAGI library
require_once('/var/lib/asterisk/agi-bin/phpagi.php');

// Create an instance of the AGI class
$agi      = new AGI();
$userName = $agi->request['agi_arg_1'];
$ext      = $agi->request['agi_arg_2'];
$user_id  = $agi->request['agi_arg_3'];
$sip_file = "/etc/asterisk/sip.conf";
$file     = fopen($sip_file, 'r');
// $user_id = null;

// Read the file line by line
while (($line = fgets($file)) !== false) {
Check if the line starts with the user's name in square brackets
    if (preg_match('/^[' . preg_quote($userName) . ']/', $line)) {
        // If it does, set the $user_data variable
        $user_data = $line;
        // Extract the user ID from the SIP configuration
        if (preg_match('/^user_id=(d+)/', $line, $matches)) {
            $user_id = $matches[1];
        }
    }
}

fclose($file);

if ($user_id) {
    if ($ext == "get_number") {
        $extension_query = "SELECT extension_name FROM extensionmps WHERE user_id=?";
        $stmt            = mysqli_prepare($conn, $extension_query);
        mysqli_stmt_bind_param($stmt, "i", $user_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        if ($row = mysqli_fetch_assoc($result)) {
            $cuser = $row['extension_name'];
            $agi->verbose($cuser);
            $agi->set_variable("CALLERID(num)", $userName);
            $agi->set_variable("CALLERID(name)", $userName);
            $agi->set_variable('call_number', $cuser);
        }
        mysqli_stmt_close($stmt);
    }
} else {
    $agi->verbose("User with username $userName is not registered");
}

Dial the extension number
$dial = $agi->exec("Dial", "SIP/${call_number}");

// Hang up the call
$agi->exec("Hangup", "");
?>

extension.conf file:::

[phones]
exten => _X.,1,AGI(call.php?userName=${CALLERID(num)})
exten => _X.,2,Dial(${call_number})

I need help for my mailing system(PHP, JS, HTML)

I am currently working on a mailing/messaging system. Now I want to send a message, but I want to add more recipients, but I can’t do this. It would be kind if one of you would like to help me.

I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.
(My English is not so good, so sorry if there are spelling mistakes).

// JS for the to-tags.

function parse() {
    var tag_input = document.getElementById("tags_input");
    var tags = document.getElementById("tags");
    //
    var input_val = tag_input.value.trim();
    var no_comma_val = input_val.replace(/,/g, "");
    //
    if (input_val.slice(-1) === "," && no_comma_val.length > 0) {
        var new_tag = compile_tag(no_comma_val);
        tags.appendChild(new_tag);
        tag_input.value = "";
    }
}

function compile_tag(tag_content) {

    let a = -3;
    var tag = document.createElement("p");
    //
    var text = document.createElement("span");
    text.setAttribute("class", "badge badge-success");
    text.setAttribute("id", tag_content);
    text.innerHTML = tag_content;
    //
    var remove = document.createElement("i");
    remove.setAttribute("class", "fa fa-remove");
    remove.setAttribute("id", "remove");
    remove.onclick = function() {this.parentNode.remove();};
    //
    tag.appendChild(remove);
    tag.appendChild(text);
    //
    return tag;
}

// HTML AND PHP

<?php
    session_start();
    include_once("error.php");
    include "db.php";
    if (isset($_SESSION['login'])){
?>

<?php 
 
    $functions = array('newMessage');
    if (isset($_GET['action'])){
        if (in_array($_GET['action'], $functions)){
        
            function newMessage(){

// when on the button press

                if (isset($_POST['button_send'])) {
                    
                    global $conn;

// take the user id
                    $from = $_SESSION['id'];

// create table one
                
                    $create = "INSERT INTO `messages` SET 
                    `messageFrom` = '$from', 
                    `messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."', 
                    `messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."' 
                    
                    ";
// when table one is created make table to. **This is where things go wrong**
                          if (mysqli_query($conn, $create)){
                    if ($create = true){
                        $read = mysqli_query($conn, "SELECT * FROM `blog` WHERE `messageSubject` = '$_POST['inp_subject']' AND `messageFrom` = '$from' ");
                        $data = mysqli_fetch_assoc($read);
                      
                        $id = $data['messageId'];

                    $create = "INSERT INTO `receivers` SET 
                    `messageId` = '$id', 
                    `messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."', 
                    `messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."' 
                    
                    "; if (mysqli_query($conn, $create)){
                        echo "fine";

                    }else{
                        echo 'Sorry, '.mysqli_error($conn);
                    }

                     }else{
                        echo 'Sorry, '.mysqli_error($conn);
                    }
                    }else{
                        echo 'Sorry, '.mysqli_error($conn);
                    }
                
            
                }

                
                ?>
                    <form method="post">
                        <div class="from_group">
                            <input type="text" name="inp_to" id="inp_to" placeholder="Give the name(s)..." required>
                            <label>To:</label>
                        </div>

// The TO-input

                        <div class="container">
    <div class="col-sm-6">
        <input onkeyup="parse();" type="text" id="tags_input" placeholder="comma-separated tags" maxlength="100" class="form-control">
    </div>
// the to tags
    <div class="col-sm-6" id="tags" name="tags">
    </div>
</div>
<script src="js/input_comma.js"></script>
                        <div class="from_group">
                            <input type="text" placeholder="Give the subject..."  name="inp_subject" required>
                            <label>Subject: </label>
                        </div>

                        <div class="from_group">
                        <textarea name="textarea_body" rows="10" cols="30">
                        </textarea>
                        </div>

                        <button name="button_send"> Send </button>
                    </form>
           
               
           
</div>
            
                <?php
            }
                   
        echo $_GET['action'] ();

        }else{
         functionNotfound();
        }   

    }
?>
<?php
}else{
   notLoggedin();
}
?>

Already thanks for the help.

I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.

Complex object validation with Symfony Validator

I have an object (a person) which is being edited (and validated) over several forms:

  • personal data form
    • first name
    • last name
    • file input for photo upload
  • account data form
    • email
  • publishing form
    • can publish only if all required fields have been filled

What I need is to have validations that I can use per-form and also for the whole person, e.g the errors would be:

  • personal data form – “please fill your first name”, …
  • whole person – “please fill your personal data”, …

If I define validations in Entity, there might still be some rules that are form-only (file upload, password repeat); it seems kinda wrong anyway because I might have different rules for web form and for API. Then again if I define validations in Form classes, then the rules are scattered around, also how can I initiate validation without form submission (which seems a hackish thing to do anyway).

Most elegant solution seems to me a separate validator which I can divide into validation groups and call it per-form and for whole object. How to do that using compound validator so that I can use other validators?

Or is there another way? Thank you.

Symfony verson is 6.