Visualizzazione dei risultati da 1 a 6 su 6

Discussione: Json con Post

  1. #1
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132

    Json con Post

    Buongiorno, ho una pagina1 php 7.0 che invia una richiesta per ricevere un JSON da una pagina2 php sul server che a sua volta legge dal database. La pagina1 che invia la richiesta deve inviare anche un post con la query. Le pagine sono caricate su un server Windows con php 7.2. Ho provato sia con "file_get_contents" che con "curl", entrambe le soluzioni leggono correttamente il json ma la pagina2 sul server non riceve il post con la query.
    codice:
    function queryws()
        {
            $postdata = http_build_query(
                array(
                    'var1' => 'some content1',
                    'var2' => 'some content2'
                )
            );      
            $opts = array('http' =>
                array(
                    'follow_location' => 1,
                    'ignore_errors' => TRUE,
                    'method'  => 'POST',
                    'header'  => "Content-type: application/x-www-form-urlencoded", 
                    // testato anche 'Content-Type: application/json'              
                    'content' => $postdata
                )
            );
            $context  = stream_context_create($opts);
            $json = file_get_contents($url, false, $context);       
            echo $json;echo "<br>";
    codice pagina1 che invia la richiesta con "file_get_contents" :
    codice:
    function queryws()
        {
            $query= "TEST QUERY POST";        
            $query_post= "{\"message\":\"" . $query . "\"}";
            $message=array( 'message'=>$query_post);
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
            curl_setopt($ch,CURLOPT_POSTFIELDS,$message);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
            curl_setopt($ch,CURLOPT_TIMEOUT, 20);
            $json = curl_exec($ch);
            curl_close ($ch);
            echo $json;echo "<br>";
    codice pagina1 che invia la richiesta con "curl" :
    codice:
    $post1= "test POST";
                $post2=$_GET['message'];          
                $myObj->post1 = "--p.1 :".$post1;
                $myObj->post2 = "--p.2 :".$post2;
                $myJSON = json_encode($myObj);
                echo $myJSON;
    codice pagina2 sul server :


    json :{"post1":"--p.1 :test POST","post2":"--p.2 :"}


    Grazie a tutti.

  2. #2
    ma tu mandi i dati in post e poi li leggi con $_GET?

    forse è li l'errore.
    prova con $_POST.

  3. #3
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132
    Buongiorno, grazie per la risposta. Chiedo scusa, per brevità ho postato solo un esempio della pagina2 sul server, in realtà ho fatto molte prove per cercare di leggere il post :
    $_GET, $_GET[con ', con ", vari tipi di indice], $_POST, $_POST[con ', con ", vari tipi di indice], $_SERVER['REQUEST_METHOD'], $HTTP_RAW_POST_DATA.


    Ho incrociato tutte queste prove con i metodi di invio "file_get_contents" e "curl", ma in nessun caso riesco a leggere il post.


    Se può essere utile posto il risultato della richiesta "$http_response_header" effettuata dalla pagina1 che invia il post :
    { [0]=> string(30) "HTTP/1.1 301 Moved Permanently"
    [1]=> string(38) "Content-Type: text/html; charset=UTF-8"
    [3]=> string(21) "Server: Microsoft-IIS"
    [4]=> string(21) "X-Powered-By: ASP.NET"
    [5]=> string(116) "Set-Cookie:
    [6]=> string(21) "X-Powered-By: ARR/3.0"
    [8]=> string(17) "Connection: close"
    [9]=> string(19) "Content-Length: 166"
    [10]=> string(15) "HTTP/1.1 200 OK"
    [11]=> string(38) "Content-Type: text/html; charset=UTF-8"
    [12]=> string(26) "Server: Microsoft-IIS/10.0"
    [14]=> string(23) "X-Powered-By: PHP/7.2.8"
    [15]=> string(21) "X-Powered-By: ASP.NET"
    [16]=> string(21) "X-Powered-By: ARR/3.0"
    [18]=> string(17) "Connection: close"
    [19]=> string(19) "Content-Length: 181" }




    Grazie ancora.

  4. #4
    Utente di HTML.it
    Registrato dal
    Oct 2011
    Messaggi
    189
    Se il metodo POST è per inviare una stringa json (non il valore di un semplice form html) devi impostare il campo intestazione appropriato.
    Puoi recuperare i dati POST grezzi , la variabile superglobale $_POST non esiste in questo caso.
    https://www.codexworld.com/post-rece...EADER%20option.
    Senza redirect ti funziona come un fascino?

  5. #5
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132
    Grazie a tutti, scusate il ritardo ma ho fatto alcune prove. Credo che il problema dipenda dall'host windows, cerco di spiegare :


    Ho una pagina php "PagServer" che dovrebbe ricevere una richiesta json contenente la query, estrarre i dati dal db e restituire i dati come json.
    Ho provato a caricare la pagina su un server Linux, e il server Windows.
    Poi ho una pagina php "TestJson" caricata sul server Windows che invia il json (con la query) alla pagina "PagServer" e visualizza i dati.
    Se la pagina "TestJson" invia la richiesta alla pagina "PagServer" su Linux, tutto va bene (sia con Curl che con file_get_contents).
    Se la pagina "TestJson" invia la richiesta alla pagina "PagServer" su Windows :
    Con il Curl, da "Syntax error, malformed JSON" e con "file_get_contents($url, false, $query);" riceve un json corretto, ma non invia la query.
    Il codice suggerito da darbula per esempio :
    - se punta alla pagina "PagServer" su server Linux funziona sia da Xampp sia da server Windows.
    - se punta alla pagina "PagServer" su server Windows da Xampp funziona con l'aggiunta di "curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);".
    - se punta alla pagina "PagServer" su server Windows da server Windows non funziona e da "Syntax error, malformed JSON".


    Codice della pagina "PagServer"
    codice:
    $post1= $_POST['message'];
    $myObj->post1 = "post.1 :".$post1;
    $myJSON = json_encode($myObj);
    echo $myJSON;
    Visualizza (quando funziona) = p.2 :{"message":"TEST QUERY POST"}


    Non riesco a capire, sto valutando di cambiare servizio di host.


    Grazie.

  6. #6
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132
    Ciao ancora, ho risolto il "Syntax error, malformed JSON" su server Windows provocato da curl aggiungendo :
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);


    Il codice della pagina "TestJson" caricata sul server Windows che invia la richiesta di un file json e la query alla pagina "PagServer" :
    codice:
    $query= "TEST QUERY POST";        
    $query_post= "{\"message\":\"" . $query . "\"}";
    $message=array( 'message'=>$query_post);
            
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$message);
    
    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
    curl_setopt($ch,CURLOPT_TIMEOUT, 20);
    $json = curl_exec($ch);
    curl_close ($ch); 
    $jsonDecode = json_decode($json);
    Come detto prima :
    - se l'$url ovvero la pagina "PagServer" è su server Linux, funziona e visualizza "post.1 :{"message":"TEST QUERY POST"}"
    - se l'$url ovvero la pagina "PagServer" è su server Windows non funziona e visualizza "post.1 :"


    Qualcuno ci capisce qualcosa ? Grazie per l'aiuto

  7. #7
    Utente di HTML.it
    Registrato dal
    Oct 2011
    Messaggi
    189
    In realtà con l'ultimo codice su "TestJson" stai inviando un array e non dovrebbe esistere $_POST['message'] ma i dati POST grezzi su
    Codice PHP:
    $data file_get_contents('php://input'); 
    (anche al messaggio precedente avvisavo che non esiste purtroppo)
    CURLOPT_POSTFIELDS:
    If value is an array, the Content-Type header will be set to multipart/form-data

    converti l'array message (con testo semplice no oggetto json) usando https://www.php.net/manual/en/functi...uild-query.php poi su "PagServer" recuperi la stringa $_POST['message']; e la converti in oggetto json.
    Se invece devi inviare un'oggetto json (stringa via POST) anche da "TestJson" leggi nuovamente il $payload, Content-Type e il relativo json_decode del codice proposto al messaggio precedente.
    Ultima modifica di darbula; 16-10-2020 a 02:32

  8. #8
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132
    Grazie a tutti, ancora non capisco, ringrazio darbula per l'interesse. Non capisco perchè $_POST['message'] funziona su Linux.
    Provo a postare questi dati sperando che possiate aiutarmi.
    Ho caricato il file "ws_test1.php" (file che legge la query, legge il database, e invia il Json) sia su un server Windows che su uno Linux.


    ws_test1.php
    Codice PHP:
    $lettura["COD1"] = "test POST";$lettura["COD2"] = " --2) POST['message'] :".$_POST['message'];$lettura["COD3"]  = " --3) INPUT_POST['message'] :".filter_input(INPUT_POST'message');$lettura["COD4"]  = " --4) GET['message'] :".$_GET['message'];$lettura["COD5"]  = " --5) file_get_contents :".file_get_contents('php://input');$lettura["COD6"]  = " --6) INPUT_POST :".filter_input(INPUT_POST);$lettura["COD7"]  = " --7) INPUT_POST, 'message' :".filter_input(INPUT_POST'message'FILTER_DEFAULT FILTER_REQUIRE_ARRAY);$num=8;$postIserverfilter_input_array(INPUT_SERVER);foreach ( $postIserver as $b ) {   $lettura["COD".strval($num)] =$b;$num=$num+1;                }$myJSON json_encode($lettura);echo $myJSON

    Il file "PagServer.php" invia la query e riceve il Json (caricato su server Windows).


    PagServer.php
    Codice PHP:
    $query_post"TEST-QUERY-CURL";$messageArray=array( 'message'=>$query_post);       $message=http_build_query($messageArray);
    $ch curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($chCURLOPT_FOLLOWLOCATIONTRUE);curl_setopt($ch,CURLOPT_POST1); //0 for a get requestcurl_setopt($ch,CURLOPT_POSTFIELDS,$message);// ELIMINA ERRORE (Syntax error, malformed JSON) su server Wincurl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFERtrue);curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,30);$json curl_exec($ch);curl_close ($ch); $jsonDecode json_decode($json); 

    Output server Linux
    test POST
    --2) POST['message'] :TEST-QUERY-CURL
    --3) INPUT_POST['message'] :TEST-QUERY-CURL
    --4) GET['message'] :
    --5) file_get_contents :message=TEST-QUERY-CURL
    --6) INPUT_POST :
    --7) INPUT_POST, 'message' :
    application/x-www-form-urlencoded
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    Apache/2.4.7 (Ubuntu) Server at *** Port 80
    45502
    CGI/1.1
    HTTP/1.1
    POST
    /ws_red/ws_test1.php


    Output server Windows
    test POST
    --2) POST['message'] :
    --3) INPUT_POST['message'] :
    --4) GET['message'] :
    --5) file_get_contents :
    --6) INPUT_POST :
    --7) INPUT_POST, 'message' :
    /JsonTest1/ws/ws_test1.php
    Microsoft-IIS/8.5
    HTTP/1.1
    GET
    28388
    CN=*.***.it
    C=GB, ..., CN=Sectigo RSA Domain Validation Secure Server CA
    2048
    256
    on
    CGI/1.1
    https
    2048|256|C=GB, ..., CN=Sectigo RSA Domain Validation Secure Server CA|CN=*.***
    /JsonTest1/ws/ws_test1.php
    Keep-Alive
    RESPONDER
    /JsonTest1/ws/ws_test1.php




    Grazie a tutti.

  9. #9
    Utente di HTML.it
    Registrato dal
    Nov 2010
    Messaggi
    132
    PagServer.php
    codice:
    $query_post= "TEST-QUERY-CURL";
    $messageArray=array( 'message'=>$query_post);       
    $message=http_build_query($messageArray);
    
    
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch,CURLOPT_POST, 0); //0 for a get request
    curl_setopt($ch,CURLOPT_POSTFIELDS,$message);
    
    
    // ELIMINA ERRORE (Syntax error, malformed JSON) su server Win
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,30);
    $json = curl_exec($ch);
    curl_close ($ch); 
    $jsonDecode = json_decode($json);

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.