IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

envoyer recevoir json array depuis bouton submit formulaire


Sujet :

Langage PHP

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    conducteur autocar
    Inscrit en
    Janvier 2020
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : conducteur autocar
    Secteur : Transports

    Informations forums :
    Inscription : Janvier 2020
    Messages : 67
    Points : 34
    Points
    34
    Par défaut envoyer recevoir json array depuis bouton submit formulaire
    Bonjour a tous et toutes

    Je souhaite envoyer 1 tableau json depuis 1 bouton soumettre qui se trouve ds 1 formulaire

    j'ai bien mon tab json, voici le code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    foreach ($tabNomProduitsFruits as $k => $v) {
                            echo $k." - ".$v;
                            echo "<br>";
                            echo "montant: ".($tabPrixProduitsFruits[$k] * $tabQuantiteDeProduitsFruitsCommandes[$k]);
                            $tabJsonFruits[] = array(
                                'nom' => $v,
                                'montant' => ($tabPrixProduitsFruits[$k] * $tabQuantiteDeProduitsFruitsCommandes[$k])
                            );
                            echo "<br>";
                        }
                        //=================================================================================
                        echo json_encode($tabJsonFruits);
                        echo "<br>";
     
                        echo "<br>";
     
                        // ================================================================================
                        $pxTotalCommandeFruits = array_sum($tabPrixDetailsFruits);
                        echo "<br>";
                        echo "le prix de votre commande de fruits s'eleve à: ".$pxTotalCommandeFruits."€";
                        // ================================================================================
     
                        $tabJsonFruits[] = ['pxTotalCommandeFruits' => $pxTotalCommandeFruits];
                        $tabJsonFruits = json_encode($tabJsonFruits);
     
                        // ================================================================================
     
                        echo "<br>";
                        echo "le tab json composé de la commande fruits du client";
                        echo "<br>";
                        print_r($tabJsonFruits);
    le retour de print_r()
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    le tab json composé de la commande fruits du client
    [{"nom":"Abricots","montant":11.5},{"nom":"Fraises","montant":5.5},{"nom":"Figues","montant":15.5},{"pxTotalCommandeFruits":32.5}]
    Ensuite je crée les options de la requêtes pour envoyer le tableau json et je crée aussi le contexte
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // creation des options de la requete pr envoyer le tab json
                        // et ajout du tabJsonFruits
                        $optionsFruits = array(
                            'http' => array(
                                'method' => 'POST',
                                'header' => "content-type: application/json",
                                'content' => $tabJsonFruits,
                            ),
                        );
     
                        // creation du context avec la fonct° PHP prevue a cet effet
                        $contextCommandeFruits = stream_context_create($optionsFruits);
    Ensuite j'ai 1 condition qui si elle est satisfaite crée 1 formulaire avec le bouton soumettre
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    if($pxTotalCommandeFruits != 0 && $pxTotalCommandeFruits != null) {
                            echo "<form method='POST' action='reception_commande.php'>";
     
                                // envoi de la requete pr le tabJsonFruits
                                $curl = curl_init();
                                curl_setopt($curl, CURLOPT_URL, "https://localhost/test_php/test04_carrousel/reception_commande.php");
                                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                                curl_setopt($curl, CURLOPT_POST, true);
                                curl_setopt($curl, CURLOPT_POSTFIELDS, $tabJsonFruits);
                                curl_exec($curl);
                                curl_close($curl);
     
                                echo "<br>";
                                echo "<input type='submit' />";
                                echo "</form>";
     
                        } else {
                            echo "on a pas de montant de commande";
                        }
    et puis pour finir j'essaye de réceptionner le tableau json dans 1 nouvelle page (reception_commande.php)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    <?php
    echo "test";
     
    echo "<br>";
     
    /*
    $test = $_POST[$tabAssociatifCommandeFruits];
    print_r($test);
     */
     
    /*
        print_r($_GET[$tabAssociatifCommandeFruits['prixTotal']]);
     */
     
    /*
    $test = $_GET['test'];
    print_r($test);
    
    echo "<br>";
    
    $tabCommandeFruits= $_GET['tabAssociatifCommandeFruits'];
    // print_r($tabCommandeFruits);
    echo "<br>";
    echo "le prix total pr la commande de fruits pr le client est de : ". $tabCommandeFruits[0];
    echo "<br>";
     */
     
    // $jsonData = file_get_contents("php://input");
    /*
        $jsonData = json_decode(file_get_contents('php://input'), true);
    print_r($jsonData);
    echo "<br>";
    $tabJsonFruits= json_decode($jsonData, true);
    print_r($tabJsonFruits);
    echo "<br>";
    echo file_get_contents('php://input');
     */
     
    // takes raw data from the request 
    $json = file_get_contents('php://input');
    // Converts it into a PHP object 
    $data = json_decode($json, true);
     
    echo $data['nom'];
     
    echo "<br>";
     
    var_dump($data);
     
    echo "<br>";
     
    var_dump($_POST);
    ?>
    comme vous le voyez, j'ai essayé plusieurs choses ms là j'ai pas de résultat
    Voici le retour de la page reception_commande.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    test
     
    NULL
    array(0) { }
    Je ne sais pas ou se situe mon problème.
    QQu'un aurait il (elle) 1 piste s'il vous plait.

    Merci a vous
    grub

  2. #2
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 393
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 393
    Points : 15 754
    Points
    15 754
    Par défaut
    essayez les fichiers que j'ai mis en pièce jointe en mettant le bon url du fichier reception.php.
    Fichiers attachés Fichiers attachés

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    conducteur autocar
    Inscrit en
    Janvier 2020
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : conducteur autocar
    Secteur : Transports

    Informations forums :
    Inscription : Janvier 2020
    Messages : 67
    Points : 34
    Points
    34
    Par défaut
    slt mathieu, j'ai essayé ton code et cela ne fonctionne pas.

    voici tt ce que j'ai fait avec ton code et ensuite des tests que j'ai fait

    ton code

    envoi.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $tabJsonFruits = "[{\"nom\":\"Abricots\",\"montant\":11.5},{\"nom\":\"Fraises\",\"montant\":5.5},{\"nom\":\"Figues\",\"montant\":15.5},{\"pxTotalCommandeFruits\":32.5}]";
     
     
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://localhost/test_php/test14_essai_json/reception.php");
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $tabJsonFruits);
     
    curl_exec($curl);
     
    curl_close($curl);
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    $i = file_get_contents('php://input');
     
    echo mb_strlen($i);
    echo "|$i";
    renvoie:
    par la page envoi.php
    152|"[{\"nom\":\"Abricots\",\"montant\":11.5},{\"nom\":\"Fraises\",\"montant\":5.5},{\"nom\":\"Figues\",\"montant\":15.5},{\"pxTotalCommandeFruits\":32.5}]"
    donc le json est construit

    par la page reception.php
    0|
    ==================================

    mes test a partir de ton code ou carrement autre chose

    page envoi.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    $tabJsonFruits = "[{\"nom\":\"Abricots\",\"montant\":11.5},{\"nom\":\"Fraises\",\"montant\":5.5},{\"nom\":\"Figues\",\"montant\":15.5},{\"pxTotalCommandeFruits\":32.5}]";
     
    $ch = curl_init();
     
    curl_setopt($ch, CURLOPT_URL, "http://localhost/test_php/test14_essai_json/reception.php");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($tabJsonFruits));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
     
    $response = curl_exec($ch);
     
    if (curl_errno($ch)) {
        printf("cURL error (%d): %s\n", curl_errno($ch), curl_error($ch));
    } else {
        // Successful response
        echo $response;
        echo "<br>";
    }
     
    curl_close($ch);
    par la page reception.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    $i = file_get_contents('php://input');
     
    echo mb_strlen($i);
    echo "|$i";
     
    // maniere $_POST etape 02, ne fonctionne pas
    // retrieve the json string from the request body
        $json_data = file_get_contents("php://input");
        // convert the json string to an associative array
        $tabJsonFruits1 = json_decode($json_data, true);
        // check if the conversion was successful
        if ($tabJsonFruits1 === null && json_last_error() !== JSON_ERROR_NONE) {
            echo "Error decoding the JSON object";
        } else {
            // access the properties of the array
     
            echo "Name: " . $tabJsonFruits1['name'] . "<br>";
        }
    renvoie
    par la page envoi.php
    152|"[{\"nom\":\"Abricots\",\"montant\":11.5},{\"nom\":\"Fraises\",\"montant\":5.5},{\"nom\":\"Figues\",\"montant\":15.5},{\"pxTotalCommandeFruits\":32.5}]"
    par la page reception.php
    0|

    donc par le moment c'est la même chose
    ================================

    des tests ms pas avec des fruits (désolé, c’a demande une gymnastique de ta part)

    la page envoi.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    require_once 'Wizard.php';
    $w1 = new Wizard("W01");
     
    // maniere $_GET etape 02
    // fonctionne
    echo "<br>";
    echo "methode S_GET";
    echo "<br>";
    $jsonW1 = json_encode($w1);
    echo $jsonW1;
    echo "<br>";
    echo "<a href='meeting.php?w1=".urlencode($jsonW1)."'>test</a>";
    // fin maniere $_GET etape 02
    la page qui réceptionne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // maniere $_GET etape 03
    // fonctionne    
    // Get the form data
    // nom du perso principal
    $jsonData = $_GET['w1'];
    $w1 = json_decode($jsonData, true);
     
    // check if the conversion was successful
        if ($w1 === null && json_last_error() !== JSON_ERROR_NONE) {
            echo "Error decoding the JSON object";
        } else {
            // access the properties of the array
            echo "Name: " . $w1['name'] . "<br>";
            echo "PV: " . $w1['PV'] . "<br>";
            echo "XP: " . $w1['XP'] . "<br>";
            echo "Sexe: " . $w1['sexe'] . "<br>";
        }
    // fin maniere $_GET etape 03
    retourne
    page envoi.php
    methode S_GET
    {"name":"W01","PV":56,"XP":0,"sexe":"1"}
    donc l'objet json est construit

    page qui réceptionne
    Name: W01
    PV: 56
    XP: 0
    Sexe: 1

    donc en GET cela fonctionne

    ================================

    même code avec méthode de variable de session

    par la page envoie.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // start the session
    session_start();
     
    // create an associative array
        $wizard2 = [
            "name" => "GandalfX",
            "PV" => 11100,
            "XP" => 10,
            "damages" => 50,
        ];
        // convert the array to a json string
        $wizard2_json = json_encode($wizard2);
        // store the json string in a session variable
        $_SESSION['wizard2'] = $wizard2_json;
        // create the hyperlink
        echo '<a href="meeting.php">Click here to continue</a>';
        echo "<br>";
        echo $_SESSION['wizard2'];
        echo "<br>";
    par la page qui réceptionne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // maniere par S_SESSION etape 02
    // FONCTIONNNE
    // start the session
     
    session_start();
    echo "test par S_SESSION";
    echo "<br>";
     
        // check if the session variable exists
        if (isset($_SESSION['wizard2'])) {
            // retrieve the json string from the session variable
            $wizard2_json = $_SESSION['wizard2'];
            // convert the json string back to an associative array
            $wizard2 = json_decode($wizard2_json, true);
            // check if the conversion was successful
            if ($wizard2 === null && json_last_error() !== JSON_ERROR_NONE) {
                echo "Error decoding the JSON object";
            } else {
                // access the properties of the array
                echo "Name: " . $wizard2['name'] . "<br>";
            echo "PV: " . $wizard2['PV'] . "<br>";
            echo "XP: " . $wizard2['XP'] . "<br>";
            echo "Damages: " . $wizard2['damages'] . "<br>";
            }
        }
    retour de la page qui envoie
    {"name":"GandalfX","PV":11100,"XP":10,"damages":50}

    donc l'objet json est construit

    retour de la page qui réceptionne
    test par S_SESSION
    Name: GandalfX
    PV: 11100
    XP: 10
    Damages: 50

    donc je réceptionne bien par les variables de session

    ================================

    le problème avec la méthode POST
    (sans curl, c'est ce que je souhaiterai si possible)

    page qui envoie
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    // maniere $_POST, etape 01, fonctionne
    // create an associative array
        $wizard1 = [
            "name" => "Gandalf",
            "PV" => 100,
            "XP" => 1100,
            "damages" => 50,
        ];
        // convert the array to a json string
        $wizard_json = json_encode($wizard1);
        // create a context for the post request
        $options = [
            'http' => [
                'header'  => "Content-type: application/json\r\n",
                'method'  => 'POST',
                'content' => $wizard_json
            ]
        ];
        $context  = stream_context_create($options);
        // send the post request to the second webpage
        $result = file_get_contents('http://localhost/test_php/test13_jeuSorcier/meeting.php', false, $context);
        // check if the post request was successful
        if ($result === false) {
            echo "Error sending the request";
        } else {
            echo "Request sent successfully";
            echo "<br>";
            print_r($wizard_json);
        }
        // fin maniere $_POST etape 01

    code de la page qui réceptionne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // maniere $_POST etape 02, ne fonctionne pas
    // retrieve the json string from the request body
        $json_data = file_get_contents("php://input");
        // convert the json string to an associative array
        $wizard1 = json_decode($json_data, true);
        // check if the conversion was successful
        if ($wizard1 === null && json_last_error() !== JSON_ERROR_NONE) {
            echo "<br>";
            echo "<br>";
            echo "Error decoding the JSON object";
        } else {
            // access the properties of the array
            echo "<br>";
            echo "<br>";
            echo "Name: " . $wizard1['name'] . "<br>";
            echo "PV: " . $wizard1['PV'] . "<br>";
            echo "XP: " . $wizard1['XP'] . "<br>";
            echo "Damages: " . $wizard1['damages'] . "<br>";
        }
     
    // fin maniere $_POST etape 02
    retour de la page qui envoie
    Request sent successfully
    {"name":"Gandalf","PV":100,"XP":1100,"damages":50}

    donc là aussi, l'objet json est construit

    retour de la page qui réceptionne
    Error decoding the JSON object

    donc problème a la réception et/ou décodage de l'objet Json

    Voilà ou j'en suis,
    désolé par le temps de réponse, je suis en formation et ça prend du temps.

    a+,
    passe 1 bonne journée et merci pour ton aide.
    grub

  4. #4
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 393
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 393
    Points : 15 754
    Points
    15 754
    Par défaut
    je viens d'essayer les 2 derniers morceaux de code de votre message avec "stream_context_create" et chez moi le 2e code arrive bien à analyser les données envoyées par le 1er code.
    affichez le contenu des variables pour voir ce que vous récupérez

    ou alors vous avez peut-être un problème de configuration de php.
    quel version de php utilisez vous ?
    avez vous activé l'affichage des erreurs ?
    https://www.php.net/manual/fr/errorf...display-errors
    https://www.php.net/manual/fr/errorf...rror-reporting

  5. #5
    Nouveau membre du Club
    Homme Profil pro
    conducteur autocar
    Inscrit en
    Janvier 2020
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : conducteur autocar
    Secteur : Transports

    Informations forums :
    Inscription : Janvier 2020
    Messages : 67
    Points : 34
    Points
    34
    Par défaut
    Bonjour mathieu,

    désolé pour le tutoiement.

    alors j'ai regardé ce que vous avez dit.

    je suis en php8.2. Pour en etre sur, je suis passé en manuellement avec la commande
    update-alternatives --config php

    Il existe 4 choix pour l'alternative php (qui fournit /usr/bin/php).

    Sélection Chemin Priorité État
    ------------------------------------------------------------
    0 /usr/bin/php.default 100 mode automatique
    1 /usr/bin/php.default 100 mode manuel
    2 /usr/bin/php7.4 74 mode manuel
    3 /usr/bin/php8.1 81 mode manuel
    * 4 /usr/bin/php8.2 82 mode manuel
    avec PHP8.2, il semble y avoir 2 php.ini
    le 1° ds /etc/php/8.2/cli/phph.ini
    le 2° ds /etc/php/8.2/phpdbg/php.ini

    étant donné que je ne savais pas lequel modifier, j'ai modifié les 2 de la manière suivante

    /etc/php/8.2/cli/php.ini
    ; display_errors
    ; Default Value: On
    ; Development Value: On
    ; Production Value: Off

    Default Value: On
    Development Value: On
    Production Value: On

    ; display_startup_errors
    ; Default Value: On
    ; Development Value: On
    ; Production Value: Off

    Default Value: On
    Development Value: On
    Production Value: On

    ; error_reporting
    ; Default Value: E_ALL
    ; Development Value: E_ALL
    ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

    Default Value: E_ALL
    Development Value: E_ALL
    Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

    ; log_errors
    ; Default Value: Off
    ; Development Value: On
    ; Production Value: On

    Default Value: On
    Development Value: On
    Production Value: On
    par le /etc/php/8.2/phpdbg/php.ini
    ; display_errors
    ; Default Value: On
    ; Development Value: On
    ; Production Value: Off

    Default Value: On
    Development Value: On
    Production Value: On

    ; display_startup_errors
    ; Default Value: On
    ; Development Value: On
    ; Production Value: Off

    Default Value: On
    Development Value: On
    Production Value: On

    ; error_reporting
    ; Default Value: E_ALL
    ; Development Value: E_ALL
    ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

    Default Value: E_ALL
    Development Value: E_ALL
    Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

    ; log_errors
    ; Default Value: Off
    ; Development Value: On
    ; Production Value: On

    Default Value: On
    Development Value: On
    Production Value: On
    et ensuite j'ai redémarré le server apache2

    systemctl restart apache2

    Maintenant voici le code de mes 2 pages

    page qui envoie le json
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    // create a json object
    $wizard1 = [
        "name" => "GandalfY",
        "PV" => rand(10, 100),
        "XP" => 1100,
        "damages" => 50,
    ];
     
    // convert the json object to a json string
    $wizard_json = json_encode($wizard1);
    echo "<br>";
    echo "valeur de Swizard_json: ".$wizard_json;
    echo "<br>";
     
    // prepare the post data
    $postdata = http_build_query(
        array(
            'wizard_json' => $wizard_json
        )
    );
     
    echo "<br>";
    echo "valeur de Spostdata: ".$postdata;
    echo "<br>";
     
    // create a context for the post request
    $options = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/json\r\n',
            'content' => $postdata
        )
    );
     
    echo "<br>";
    echo "- 1: ".$options['http']['method'];
    echo "<br>";
    echo "- 2: ".$options['http']['header'];
    echo "<br>";
    echo "- 3: ".$options['http']['content'];
    echo "<br>";
    echo "<br>";
     
    $context  = stream_context_create($options);
    echo "valeur de Scontext: ".$context;
    echo "<br>";
    echo "<br>";
     
    // send the post request to the second webpage
    $result = file_get_contents('http://localhost/test_php/test13_essai_json01/meeting.php', false, $context);
    echo "valeur de Sresult: ".$result;
    echo "<br>";
    echo "<br>";
     
    if ($result === false) {
        echo "01 Error sending the request";
        exit;
    }
     
    $http_response_code = explode(' ', $http_response_header[0])[1];
    echo "-- valeur de Shttp_response_code: ";
    echo "<br>";
    echo $http_response_code;
     
    if($http_response_code != 200) {
        echo "<br>";
        echo "02 Error sending the request. Response code: " . $http_response_code;
        exit;
    }
     
    echo "<br>";
    echo "<br>";
    echo "Request sent successfully";
    echo "<br>";
    echo '<a href="meeting.php">Click here to continue</a>';
    echo "<br>";
    page qui reçoit le json
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // retrieve the json string from the request body
    $json_data = file_get_contents('php://input');
    echo "<br>";
    var_dump($json_data); // renvoie: string(0) "" 
    echo "<br>";
     
    if($json_data === false) {
        echo "01 Error: Unable to read data from the request body";
        exit;
    }
     
    // convert the json string to an associative array
    $wizard1 = json_decode($json_data);
     
    // check if the conversion was successful
    if ($wizard1 === null && json_last_error() !== JSON_ERROR_NONE) {
        echo "02 Error decoding the JSON object. Error Code: " . json_last_error(); // renvoie: 02 Error decoding the JSON object. Error Code: 4
        echo "<br>";
        var_dump($wizard1); // renvoie NULL
        exit;
    }
    le retour de la page qui envoie le json:
    valeur de Swizard_json: {"name":"GandalfY","PV":57,"XP":1100,"damages":50}

    valeur de Spostdata: wizard_json=%7B%22name%22%3A%22GandalfY%22%2C%22PV%22%3A57%2C%22XP%22%3A1100%2C%22damages%22%3A50%7D

    - 1: POST
    - 2: Content-type: application/json\r\n
    - 3: wizard_json=%7B%22name%22%3A%22GandalfY%22%2C%22PV%22%3A57%2C%22XP%22%3A1100%2C%22damages%22%3A50%7D

    valeur de Scontext: Resource id #1

    valeur de Sresult: page meeting.php

    string(100) "wizard_json=%7B%22name%22%3A%22GandalfY%22%2C%22PV%22%3A57%2C%22XP%22%3A1100%2C%22damages%22%3A50%7D"
    02 Error decoding the JSON object. Error Code: 4
    NULL

    -- valeur de Shttp_response_code:
    200

    Request sent successfully
    Click here to continue
    je ne m'explique pas l'affichage de string(100)...........
    je ne sais pas d’où ça vient

    le retour de la page qui reçoit le json
    page meeting.php

    string(0) ""
    02 Error decoding the JSON object. Error Code: 4
    NULL
    Voilà, je suis bien perdu, surtout a cause de ce fameux retour string(100) que je n'explique pas. Je ne sais plus si j'envoie ou pas le json

    Dans la page qui reçoit le json, le code erreur 4 est a priori une erreur de syntaxe dans le json. mais comme je ne reçois que chose de NULL, je ne sais pas trop quoi en penser.

    Je vais arrêter pour aujourd'hui, j'y suis depuis ce matin et j'ai d'autres choses a voir.
    Si vous avez 1 idée, tant mieux, sinon je verrai bien un peu plus tard.

    Merci bien de votre temps et de votre aide
    grub

    Désolé pour la cette réponse a rallonge, mais comme je souhaite être le plus précis possible, histoire que l'on soit sur les mêmes bases.

  6. #6
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 393
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 393
    Points : 15 754
    Points
    15 754
    Par défaut
    il n'y a pas de problème pour le tutoiement, il y a un mélange des 2 sur les forums c'est pour ça que depuis quelques années j'ai décidé de rester sur du vouvoiement mais avec les personnes qui ont l'habitude de tutoyer.

    par contre là où ça ne vas pas, c'est que vous modifiez beaucoup trop de chose sans tester et donc vous vous emmêlez les pinceaux.
    la fonction "http_build_query" crée un contenu au format "application/x-www-form-urlencoded" c'est à dire var1=contenu1&var2=contenu2.

    mais vous voulez envoyer les données au format json donc laissez ce que vous aviez dans le code précédent, c'est à dire ça
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        $wizard_json = json_encode($wizard1);
        // create a context for the post request
        $options = [
            'http' => [
                'header'  => "Content-type: application/json\r\n",
                'method'  => 'POST',
                'content' => $wizard_json
            ]
        ];
        $context  = stream_context_create($options);

    et je viens de me rendre compte que j'ai n'ai pas compris pourquoi vous passez par ce format. est ce que vous préparez un client pour une API qui accepte seulement du json ?

  7. #7
    Nouveau membre du Club
    Homme Profil pro
    conducteur autocar
    Inscrit en
    Janvier 2020
    Messages
    67
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : conducteur autocar
    Secteur : Transports

    Informations forums :
    Inscription : Janvier 2020
    Messages : 67
    Points : 34
    Points
    34
    Par défaut
    Bonjour,

    Pourquoi je souhaite utiliser ce format? eh bien a priori j'y arrive en GET, j'y arrive par les SESSION et je souhaiterai y arriver en POST.
    Je ne sais pas qu'elle est la méthode optimisée.

    Voilà, sinon, ben je continue de chercher. J'ai remis ce que vous m'avez dit mais je n'arrive pas a decoder sur la page qui recoit le json.
    Merci a vous.

    grub

  8. #8
    Expert éminent sénior
    Avatar de mathieu
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    10 393
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 10 393
    Points : 15 754
    Points
    15 754
    Par défaut
    Citation Envoyé par grub_fr Voir le message
    je souhaiterai y arriver en POST.
    vous souhaitez arriver à quoi ? donner nous plus de détails si vous voulez qu'on vous propose notre aide.
    l'utilisation habituelle des requetes POST est dans un navigateur avec un formulaire qui envoie la requete POST et le code php récupère les données dans le tableau $_POST.

    là vous n'avez pas l'air dans ce cas général donc expliquez nous quels sont les différents utilisateurs et à quoi servent ces données.

Discussions similaires

  1. Formulaire: bouton "submit" avec image & texte parasite "Envoyer"
    Par steph68b dans le forum Balisage (X)HTML et validation W3C
    Réponses: 6
    Dernier message: 26/07/2013, 14h52
  2. envoyer/recevoir fichier vers/depuis servlet
    Par Ikki dans le forum Servlets/JSP
    Réponses: 1
    Dernier message: 07/09/2008, 21h24
  3. Réponses: 3
    Dernier message: 02/07/2008, 19h08
  4. Réponses: 4
    Dernier message: 15/05/2006, 12h38
  5. Formulaire et bouton submit avec image mapée
    Par dody dans le forum Général JavaScript
    Réponses: 7
    Dernier message: 06/12/2004, 16h00

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo