0

I am a beginner in PHP programming. I have this script in which I'm trying to get a string multiple times, each time with different "login" data, from an external website. I am using PHP, cURL, DOM and XPath. The fact is that my code seems to work only if I don't use a foreach construct to loop the entire operation. But I don't know how else I could repeat this operation changing the data from time to time.

The situation is: I have just logged in, and now the site ask me to fill two more fields that are necessary to proceed to the next page where I can get the string that I need. The next portion of code is contained in a if block.

// A function to automatically select the form fields:

function form_fields($xpath, $query) {
    $inputs = $xpath->query($query);
    $fields = array();
    foreach ($inputs as $input) {
        $key = $input->attributes->getNamedItem('name')->nodeValue;
        $type = $input->nodeName;
        $value = $input->attributes->getNamedItem('value')->nodeValue;
        $fields[$key] = $value;
    }
    return $fields;
}


// Executing the XPath queries to fill the fields:

$opzutenza = 'incarichi';
$action = $xpath->query("//form[@name='fm_$opzutenza']")->item(0)->attributes->getNamedItem('action')->nodeValue;
curl_setopt($ch, CURLOPT_URL, $action);
$fields = form_fields($xpath, "//form[@name='fm_$opzutenza']/input");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
$html = curl_exec($ch);

$dom = new DomDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);


// The strings that I need to get depend on each value contained in this select element:

$options = $xpath->query("//select[@name='sceltaincarico']/option");

$partiteiva = array();
    foreach($options as $option){
    $partiteiva[] = $option->nodeValue;
    unset($partiteiva[0]);
    }
} // -----------> END OF 'IF' BLOCK

$queriesNA = array();
foreach ($partiteiva as $piv) {
    $queryNA = ".//select[@name='sceltaincarico']/option[text()='$piv']";
    $queriesNA[] = $queryNA;
}


// And this is the problematic loop:

foreach($queriesNA as $querypiv){
        $form = $xpath->query("//form[@name='fm_scelta_tipo_incarico']")->item(0);
        $action = $form->attributes->getNamedItem('action')->nodeValue;
        @$option = $xpath->query($querypiv, $form);
        curl_setopt($ch, CURLOPT_URL, $action);
        $fields = [
            'sceltaincarico' => $option->item(0)->attributes->getNamedItem('value')->nodeValue,
            'tipoincaricante' => 'incDiretto'
        ];
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); // ----> Filling the last field
        curl_exec($ch);


    curl_setopt($ch, CURLOPT_URL, 'https://website.com/dp/api');
    curl_exec($ch);

    curl_setopt($ch, CURLOPT_URL, 'https://website.com/cons/cons-services/sc/tokenB2BCookie/get');
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    $http = curl_exec($ch);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);

            function parse_headers($http) {
    $headers = explode("\r\n", $http);
    $hdrs = array();
    foreach($headers as $h) {
        @list($k, $v) = explode(':', $h);
        $hdrs[trim($k)] = trim($v);
    }
    return $hdrs;
        }

    $hdrs = parse_headers($http);
    $tokens = array(
        "x-token: ".$hdrs['x-token'],
        "x-b2bcookie: ".$hdrs['x-b2bcookie']
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $tokens);


    curl_setopt($ch, CURLOPT_URL, "https://website.com/cons/cons-services/rs/disclaimer/accetta"); // Accepting the disclaimer...
    curl_exec($ch);

    curl_setopt($ch, CURLOPT_URL, "https://website.com/portale/web/guest/home");
    $html = curl_exec($ch); // Finally got to the page that I need

    $dom = new DomDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);


 // Selecting the string:

    $string = $xpath->query("//div[@class='informativa']/strong[2]");

            $nomeazienda = array();
    foreach ($string as $str) {
        $nomeazienda[] = $str->childNodes->item(0)->nodeValue;
    }
     
      
 // Going back to the initial page so the loop can start again from the beginning:

    $piva_page = 'https://website.com/portale/scelta-utenza-lavoro?....';

    curl_setopt($ch, CURLOPT_URL, $piva_page);
    $html = curl_exec($ch);

    $dom = new DomDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
}

curl_close($ch);

These are the error messages:

Notice: Trying to get property 'attributes' of non-object...

Fatal error: Uncaught Error: Call to a member function getNamedItem() on null...

Error: Call to a member function getNamedItem() on null...

The function getNamedItem() is the first one just after the malfunctioning loop, and so are the 'attributes'.

Community
  • 1
  • 1
smarmolena
  • 11
  • 5
  • Which is the line where your error occurs? – Lajos Arpad Oct 08 '19 at 09:03
  • `var_dump($form)` data and post it here – PHP Ninja Oct 08 '19 at 09:15
  • These are the lines in which the error occurs: $form = $xpath->query("//form[@name='fm_scelta_tipo_incarico']")->item(0); $action = $form->attributes->getNamedItem('action')->nodeValue; This is the "var_dump($form)": object(DOMElement)[10] public 'tagName' => string 'form' (length=4) public 'schemaTypeInfo' => null public 'nodeName' => string 'form' (length=4) public 'nodeValue' => string (too long to write here!) public 'nodeType' => int 1 public 'parentNode' => string '(object value omitted)' (length=22) ... – smarmolena Oct 08 '19 at 09:22
  • ...public 'childNodes' => string '(object value omitted)' (length=22) public 'firstChild' => string '(object value omitted)' (length=22) public 'lastChild' => string '(object value omitted)' (length=22) public 'previousSibling' => string '(object value omitted)' (length=22) public 'nextSibling' => string '(object value omitted)' (length=22) public 'attributes' => string '(object value omitted)' (length=22) public 'ownerDocument' => string '(object value omitted)' (length=22) public 'namespaceURI' => null public 'prefix' => string '' (length=0)... – smarmolena Oct 08 '19 at 09:27
  • ... public 'localName' => string 'form' (length=4) public 'baseURI' => null public 'textContent' => string (the same associated to 'nodeValue') – smarmolena Oct 08 '19 at 09:27
  • $form is not an object, so it doesn't have an attributes member and therefore, when a namedAttribute is attempted to be retrieved, it throws the error, because attributes is null. – Lajos Arpad Oct 08 '19 at 09:29
  • You have a cycle and on each step $form is retrieved and some operations are done with it. From what you say it seems that form is a non-object in some cases and is a valid object in other cases. You could wrap the loop block into an if to make sure that it only executes if a proper $form was found. – Lajos Arpad Oct 08 '19 at 09:31
  • About this - and I don't know if the problem is related to what I'm going to say - I've just remembered that I forgot to add a portion of code at the end of the loop that serves to go back to the initial page, so that the operations could start again and the form could be found (I've just added the code in the post). The fact is that it doesn't work anyway. – smarmolena Oct 08 '19 at 09:44
  • Probably the selection of the $form is only valid in the initial page. – Lajos Arpad Oct 08 '19 at 09:48
  • It is, but it doesn't work even if I go back to that page, with the lines of code that I've just added. Maybe they are wrong? Maybe I just can't go back this way to that page? Its URL is something like this: https://website.com/portale/scelta-utenza-lavoro?p_auth=gXzJ5hte&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=incarichiAction' – smarmolena Oct 08 '19 at 09:52
  • Is it possible that the issue in that case is that since the redirection, your objects gathered earlier no longer reference the items in the page where you have navigated away from? – Lajos Arpad Oct 08 '19 at 12:15
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – miken32 Oct 09 '19 at 13:04

0 Answers0