hi

So ive deployed a small website i worked on, and before deployemnt on Amazon web services, i was of course testing everything on localhost. after seeing that things are working on localhost, i changed the localhost to the deployment link provided on AWS and things looked fine and all except that some pages were giving me annoying slim application errors since yesterday.

of those errors is the "if (key_array_exists)" which i ended up commenting out in order to finally be logged in. then i tried viewing the "team documents" functionality i have and when it goes to that page, i got some slim errors regarding "file_get_contents".
I read up on this everywhere and people suggested to use urlencode/rawurlencode since online hosting doesnt interpret the url the same way as running on localhost. but the issue was that most examples were shown using it with spaces as special character problem, but my url doesnt have spaces so i didnt know where to even implmenet this in the url i have.

so i took on the other suggestions of using cURL. I even tested cURL on the localhost and it works...but again on the AWS server it doesnt!
I am getting this error for the AWS hosted version:

Message: Invalid argument supplied for foreach()

this is the code its talking about:

               <section>
                  <?php
/*                   $raw = file_get_contents("http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json");
                     $pages_response = json_decode($raw, true);
                     $pages_array = $pages_response["query"]["allpages"];
                     $page_titles = []; */

                     $raw = 'http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json';
                     $curl = curl_init();
                     curl_setopt($curl, CURLOPT_URL, $raw);
                     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                     //curl_setopt($curl, CURLOPT_HEADER, false);
                     $data = curl_exec($curl);
                     curl_close($curl);

                     $pages_response = json_decode($data, true);
                     $pages_array = $pages_response["query"]["allpages"];
                     $page_titles = [];

                     require_once("domainlogic/wiki_api.php");

                    // echo nl2br("the logged name is " .$loggedName. "\n");

                     foreach ($pages_array as $page)
                       {
                           // We have the User Id of the wiki doc ($wikiUserId);
                           // if the revision user field matches the userId, we'll show the doc. 
                           // otherwise, we won't.
                           $name = $page["title"];
                           $pageAuthor = WIKI_API::getRevisionIdForPage($name);
                           //echo nl2br("page title: ".$name." -- comparing pageAuthor: ".$pageAuthor." against teamId: ".$wikiUserId. "\n");

                            //echo  nl2br(" the pageAuthor is " .$pageAuthor. "\n");
                           //if ($pageAuthor == $loggedName) {
                              // we have a match. 

                             //echo "we have a match for ".$name. " it is ".$pageAuthor;
                           //echo " A " .$wikiUserId. " is the wikiuserID " .$loggedName. " is the logged name" .$teamName. "is the logged team name ";
                           //echo " The revision history includes " .$pageAuthor;
                           array_push($page_titles, $name);
                          // }

                       }

                       $baseUrl = './mywiki/index.php/'; 
                     if (count($pages_array) == 0 || is_null($pages_array)) {
                        echo "<h1 id='noDocMessage'>You have no documents</h1>";
                     }
                     ?>

                  <ul id="gallery">
                     <?php foreach( $page_titles as $title): ?>
                     <li class="documentLI">
                        <a href="<?= $baseUrl ?><?= $title ?>">
                           <img src="images/todoDoc.png" alt="Document Image" class="documentImage">
                        </a>
                           <div>
                              <a href="<?= $baseUrl ?><?= $title ?>"><p><?= $title ?></p></a>
                           </div>
                           <div>
                        <a href="./deletePage?title=<?= $title ?>">
                       <!--  <img src="images/delete.png" alt="delete" class="deleteImage"> -->
                        </a>
                        </div>
                     </li>
                     <?php endforeach; ?>
                  </ul>
               </section>

its talking specifically about this piece here: foreach ($pages_array as $page)
I dont know why its not giving issues with localhost but with the AWS it is?!

Im extremely tired of chasing around with these issues and I want this to work finally.
Any help is appreciated thanks

Dani AI

Generated

The foreach warning means the variable passed to foreach is not an array. ’s 404 result is the key clue: the Elastic Beanstalk endpoint is returning HTML/an error page (or nothing) instead of the JSON the code expects, so json_decode() returns null and the loop fails. Common causes on a deployed host are a wrong endpoint or query string, HTML-escaped ampersands (&amp;) in the URL, or a silent cURL failure.

Quick checklist to narrow it down

  • Log the raw response (write to a file or error_log) immediately after curl_exec to see if it is JSON or an HTML error page.
  • Check the HTTP status with curl_getinfo(..., CURLINFO_HTTP_CODE) and any curl errors with curl_errno()/curl_error().
  • After json_decode(..., true) call json_last_error_msg() to spot parse errors.
  • Ensure the query string uses literal & (or build it with http_build_query) instead of &amp; copied from rendered HTML.
  • Guard the foreach with a check like if (!empty($data['query']['allpages']) && is_array($data['query']['allpages'])) to avoid warnings.

Example pattern (safe fetch + checks)

$api = 'http://ELASTIC_HOST/cosoft/mywiki/api.php';
$url  = $api . '?' . http_build_query(['action'=>'query','list'=>'allpages','format'=>'json']);

$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_FOLLOWLOCATION=>true, CURLOPT_TIMEOUT=>10]);
$resp = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resp === false) error_log('curl error: '.curl_error($ch));
curl_close($ch);

$data = json_decode($resp, true);
if (json_last_error() !== JSON_ERROR_NONE) error_log('json error: '.json_last_error_msg());

$pages = $data['query']['allpages'] ?? null;
if (is_array($pages)) { foreach ($pages as $p) { /* process */ } }
else error_log("No pages array; HTTP={$http}; response begins: ".substr((string)$resp,0,200));

Notes and gotchas

  • Copying an href from rendered HTML often brings &amp; instead of & — that will break query parsing. Use http_build_query to be safe.
  • If the API is part of the same app, consider calling it internally (include or require) instead of doing an HTTP request for better reliability and performance.
  • Security groups, firewalls, or routing differences on Elastic Beanstalk can also change behavior compared to localhost; the HTTP status and raw response will reveal that.

Recommended Answers

All 2 Replies

Hi, is the curl request link correct? By testing I get a 404 page, not JSON data.

yes, instead of the elastic beanstalk link, i use localhost and it gives back json data fine. but for the elasticbeanstalk i get error

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.