Notice: Array to string conversion in /home/... on line 38

Php Whizzes,

The following code spits this error:

Notice: Array to string conversion in /home/… on line 38

What does it mean ?


<?php

/*
ERROR HANDLING
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

//For All Error, Warning and Notice
error_reporting(E_ALL) OR error_reporting(-1);
//For All Errors
error_reporting(E_ERROR);
//For All Warnings
error_reporting(E_WARNING);
//For All Notice
error_reporting(E_NOTICE);

error_reporting(E_ALL);

$conn = mysqli_connect("localhost", "root", "", "id");

if(isset($_GET["url_to_proxify"]) === TRUE)
   {
		$url_to_proxify = filter_input(INPUT_GET, 'url_to_proxify', FILTER_VALIDATE_URL);
		echo $url_to_proxify;
		?>	

		<?php
		
		$page = file($url_to_proxify);
		$domain = parse_url($url_to_proxify, PHP_URL_HOST);
		echo $domain;
    	
		//eg: $pattern = array("localhost", "./", "https://", "http://");
		$phrase = preg_replace('/src="/', 'src="'.$url_to_proxify, $page);
		$phrase = preg_replace('/action="/', 'action="proxy.php?url_to_proxify='.$domain.$url_to_proxify.'"', $page);
		echo $phrase;
	}
else
	{
		echo 'The "else" got triggered in the "if" condition!';
	}
?>

<html>
   <body>   
      <form action = "<?php $_PHP_SELF ?>" method = "GET">
         Url: <input type = "text" name = "url_to_proxify" />
              <input type = "submit" />
      </form>      
   </body>
</html>

I’ve never seen $_PHP_SELF before. Maybe use it correctly?

http://php.net/manual/en/reserved.variables.server.php

4 Likes

I actually copy pasted that form from somewhere.
Thanks for pointing the error out.
So, it should be like this ?


<html>
   <body>   
      <form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "GET">
         Url: <input type = "text" name = "url_to_proxify" />
              <input type = "submit" />
      </form>      
   </body>
</html>

Yes ?
Nevertheless, making the change and fixing it did not solve my current problem.

Problem is here
echo $url_to_proxify; this variable is an array, you can’t just echo it, loop through it or access it ‘manualy’ like this:
echo $url_to_proxy[0];
Or use print_r function if you want to debug.

I prefer using the following function instead of echo because:

  1. displays variable type
  2. displays boolean, integers, floats, strings, arrays, objects
  3. only requires one hand to type, apart from the round brackets and variable name:
//=====================================
# usage: 
#   fred( $anyVariableType ); 
//=====================================
function fred($val="NOTHING DECLARED???")
{
  $type = gettype($val);
  echo '<h1 style="background-color:red; color:#000; ">';
    echo '$type ==> ' .$type;
  echo '</h1>';

  echo '<pre>';
    print_r($val);
  echo '</pre>';
}///

Thanks everyone for your suggestions but what does the error mean and how to solve it ?

I’ve posted answer above.That error means that you are trying to convert array to string which can’t be done that way and that happened because you are outputing it like a string.

1 Like

Actually, I don’t believe that to be true. I believe $phrase is the array. As $page is definitely an array, and when given to preg_replace, it will return an array.

Change echo $phrase; to print_r($phrase);

2 Likes

Trouble actually started as soon as I took-out the foreach at someone’s advice. But, I reckon his advice was sound.
I had actually got 2 different scripts and was combining codes and one of them had the foreach. For some reason, that did not sound right to the person. Can’t remember who the person was.
Anyway, I did as you suggested cpradio and the error is gone. However, not without a little hiccup. I am tending to this. Will keep you all updated very soon. If not immediate! :wink:

Just one question though. How come echo did not work but print_r did ? Aren’t they the same ? In C, you got the printf, right ? :wink:

No. They are not the same.

1 Like

I have an interest in your idea so decided to rewrite the code using my JB-TEMPLATE.php

<?php
  // https://www.sitepoint.com/community/t/notice-array-to-string-conversion-in-home-on-line-38/268035

  declare(strict_types=1);

  $title   = 'JUST TESTING';
  $doctype = 5; // STRICT
  $sp      = 'https://www.sitepoint.com/community/t/curl-experiments/264321/48';

  # require $_SERVER['DOCUMENT_ROOT'] .'/JB-TEMPLATE.php';
  require 'JB-TEMPLATE.php';


  if( isset($_GET['reset']) ) :
    $_GET = array();
  endif;

  $url_to_proxify = $_GET['url_to_proxify'] ?? NULL;
  if( $url_to_proxify )
  {
    $url_to_proxify = filter_input(INPUT_GET, 'url_to_proxify', FILTER_VALIDATE_URL);
    # $result = getProxifiedUrl( $url_to_proxify );
  }
  $decode = $_GET['decode'] ?? 'array';
  $aChkd  = 'array' ===$decode ? 'checked' : NULL;
  $sChkd  = 'string'===$decode ? 'checked' : NULL;

?>
<style type="text/css">
 .posB {position:fixed; bottom:0; left:0; width:100%;}
 .fgr  {color:#f00;}
 .flr  {float:right;}
 .ooo  {margin:0; padding:0;}
</style> 
</head>  
<body class="bge">

  <div class="w88 mg1 bd1 p42 bgs">
    <h4 class="flr ooo"> <a href="<?= $sp; ?>">SitePoint Forum </a> </h4>
    <h1> <?= $title ?> </h1>
  
    <form action = "?" method = "get">
      <label> URL: <?= $url_to_proxify ?> </label>
      <br>
      <label> Result: &nbsp; </label>
      <label> string </label>
      <input type="radio" name="decode"  value="string" <?= $sChkd ?>  />
      <label> array </label>
      <input type="radio" name="decode"  value="array"  <?= $aChkd ?> />
      <br>

      <label> Url: </label>
      <input type="text"   name="url_to_proxify"  size="42" value="<?= $url_to_proxify; ?>" />
      <input type="submit" name="submit" value="Submit" />
      &nbsp;
      <input type="submit" name="reset" value="Reset" class="fwb fgr"/>
    </form>      
    <?php # fred($_GET, '$_POST'); ?>
  </div>  

  <?php 
    echo '<div class="w88 mg1 bgs p42 bd1">';
      if ( $url_to_proxify )
      {
        $result = getProxifiedUrl( $url_to_proxify );
        if( is_array($result) ):
          $decode = $_GET['decode'] ?? 'array';
          fred( $result, '$result', 'array'===$decode ); 
        else:
          fred( 'YES WE HAVE NO $result' );
        endif;
      }else{
        echo '<h3 class="ooo">Source File:</h3>';
        echo '<hr>';
        fred( highlight_file(__FILE__) );
      }
      echo '</div>';  
  ?>  

  <p class="mg1">
    &nbsp;
  </p>
    
  <div class="posB tac bgy bd1">
    <a class="flr" href="JB-TEMPLATE-SOURCE.php"> 
      <b>JB-TEMPLATE-SOURCE.php</b> &nbsp;
    </a> 
    Wonderful place for a footer
  </div>  

</body>
</html>
<?php 
//==================================================================================
function getProxifiedUrl($url_to_proxify=NULL)
{    
  $result = 'The "else" got triggered in the "if" condition!';

  # uses @ to eliminate URL not found
  try{
    error_reporting(0);
      $aPage  = file($url_to_proxify);
    error_reporting(-1);
  }catch( Exception $e) {     
    fred('Sorry, there is no:  ' .$url_to_proxify );
  }//endtry;

  $domain = parse_url( $url_to_proxify, PHP_URL_HOST);

  # if( $domain ):
  if( is_array($aPage) ):
    # eg: $pattern = array("localhost", "./", "https://", "http://");
    $result = array();
    foreach( $aPage as $line ):
      $line = preg_replace
      (
        '/src="/', 
        'src="' .$url_to_proxify, 
        $line
      );
      # $aPhrase = preg_replace
      $line = preg_replace
      (
        '/action="/', 
        'action="proxy.php?url_to_proxify=' .$domain .$url_to_proxify .'"', 
        $line
      );
      $result[] = $line;
    endforeach; // ( $aPage as $line ):
  endif;  

  return $result;
}//


Online version

3 Likes

I didn’t understand much from it. Especially, about all the “return 1”. And you know very well, if you miss 1 link in the chain then every link that comes after it becomes useless to you.
But, I am sure, I will understand it once I am a bit more learned in php. At the site, I had a feeling as if they were talking about c. After-all, php derives it’s syntax from it or whatever.

–superfluous–

1 Like

So, I should output it like Array. Like this:

echo $url_to_proxy[0];
echo $url_to_proxy[1];

And so on ?

Or, I should use print_r instead of echo then I won’t have to echo each array and can just echo it like a string or all in one go (like a big file with lots of lines of outputs) ?

You have an interest in my idea ? What idea, may I ask ? :wink:
What exactly do you think I am upto with all these cURL and web scraping, may I ask ? :lol: Lol!

Thanks for the code sample. I have checked it out now. I am glad you bother to show code samples. Most appreciated !!! I mean it! It is saving me a lot of time from wondering what to do next!

:slight_smile::smiley::smile:

Anyway, have you noticed that, when you type “google.com” on your web proxy and do a keyword search, you are shown an error page ? Do a search for “cars” and see for yourself.
The SERP google presents, it’s url is this:

http://localhost/search?ie=ISO-8859-1&hl=en&source=hp&biw=&bih=&q=cars&btnG=Google+Search&gbv=2

I was testing your script on my xampp.
Anyway, I see this same error on my own codes. If you manually replace “localhost” with “google” then it works. We can’t hard code “gogole.com” in our codes because we don;t know on which sites our users would use our web proxies on. Therefore, I tried grabbing the proxified site’s domain name ($domain) and then replacing the “localhost” with that on all links present on the proxified page. But for some reason it works on some places but not on the rest.

Eg.


$domain = parse_url($url_to_proxify, PHP_URL_HOST);

//eg: $pattern = array("localhost", "./", "https://", "http://");
	$phrase = preg_replace('/src="/', 'src="'.$url_to_proxify, $page);
	$phrase = preg_replace('/action="/', 'action="proxy.php?url_to_proxify='.$domain.$url_to_proxify.'"', $page);
	echo $phrase;

Your code would work, once you fix this issue for “localhost” to be replaced by “domain name”.
Anyway, I uploaded your 2 files to my site but I see http 500 error. Strange!

What do you mean ?

This topic “array to string conversion” and your problem with understanding “return 1” suggests that you have not yet gained an understanding of “data types”. AFAIK most languages have more in common than they have differences.

In the PHP documentation when you see “mixed” it means “more than one data type”.

Various functions can have stricter or looser requirements as to what’s allowed for parameter data types, and some functions can return different data types. An example would be a query that when successful returns a result set (array data type) but when it fails returns false (boolean data type).

Booleans can be a bit tricky because different languages can evaluate “truthiness” differently. There is a table that lays out how PHP does it here:

http://php.net/manual/en/types.comparisons.php

1 Like

I did finish the Data Types. Integers, Floats/Doubles, Strings, etc. But I don’t remember coming across this RETURN 1 thing.
Anyway, this thread might seem interesting to you as you’ll know how much I know and how much I can really ask:

I hope you like the thread’s name.
I don’t prowl in that forum anymore. The guys had a problem of me asking the same questions on more than one forum without telling them and decided to go quiet. Who gives a damn anyway. I got 2 better forums, like this one, to attend to.

Here’s the duplicate I created in this forum:

6 months from now, whenever I had a question, I opened 10 tabs and opened 10 threads (with same name) on all 10 forums. Only 8 were responsive. Slowly, some stopped responding as members were leaving. Some (about 2-3) found-out I was asking same questions on more than one forum and went silent. Now, I only get response from 2 (inc. this one). The other is getting unresponsive too. Maybe, they think I ask too many questions. Some mods have a problem with that but most not. :slight_smile:

Now compare the answers I got from both forums (see both links above) and you will see they vary. Now, you know why I ask questions on more than one forum. Good for work experience. If you stick to a single forum then there is no guarantee you will get answers from it. Best to ask on as many as you can and then see which ones yielded results and which ones not or which ones gave what responses.

Out of about 6-8 forums. Only this one proved to have mature contributors. Some of the others have down-right impatient and very rude ones aswell as good ones (a mixture) but on this forum I have yet to come across a rude one. Too much programming gets members frustrated in some forums and then they take it out on each other. Best to avoid these kinds of forums. Stick to this one, instead, where you won’t get sarcastic replies but worthy ones.

Btw, you’re not gonna like this. I just went through the link of the other forum (mentioned above) and found myself telling over there I know this and that about boolean etc. but guess what ? When I read all that (my own post) it seemed like I was reading someone else’s because to tell you the truth I can’t remember anything about what I claim to know about boolean over there. This proves, I have forgotten fast what I learnt. More reason for me to teach my php bot the notes of what I learn so it can remember it and remind me things I have forgotten. Good idea. :wink:
You see, if you read and learn something but don’t get the chance to practice then you forget it. Good thing cpradio suggested codeacademy.com because on each chapter they test you by getting you to code. I’m also thinking of building another .exe bot that will force me to type codes rapidly as an exercise and then check my answers if there is any errors. It will time me to see how long I take to write the code. Do I fumble or not and then give scores.
10 yrs back, I could type about 40 words per minute with my eyes closed without making hardly any typoes. Now, I’d probably manage 20 words with 50% typos, since I don’t practice. But, I am a fast typer still with my eyes open. My point is:
I think the best way for me not to forget things is by rapid typing as a form of memorizing the codes, etc…
The point of me mentioning that other forum (Dani Web) is that if you read my thread over there, then you will realize I know about the fact that different programming languages have different definition of the TRUE & FALSE. Replying to your statement:
“Booleans can be a bit tricky because different languages can evaluate “truthiness” differently.”
Whatever proves to be TRUE on one may not be TRUE on another language. Since I already know all this then I don’t want you bothering wasting your time telling me this or showing me code samples.
But still saying all this, yeah, you are sort of correct, I don’t have yet much knowledge of the basics of php or any language for that matter. Still learning. And it is taking time to finish learning because this time round I am trying to remember what I am learning. This is my 2nd or 3rd round/attempt to learn php. On my 1st round, back in sep 2015, I finished learning the basics of php from Tizag (old site) in 2wks (of what they had to offer) and in 1 wk I forgot 3 quarters of what I learnt.vAnd, that is due to not practicing by typing any codes. No exercises. Only reading. I want this round to be different. Taking it slowly and steady. Not gonna run (before I can walk) and trip over this time in the “forgetful lake”. :wink:
Saying all this, I’m not gonna quit trying to build my own member-reg-login site and web proxy (90% complete) and quit on the idea to start building my own searchengine very soon. And ofcourse, you guys will be a part of the help now and then. Lol! :wink:

Thanks cpradio for the codeacademy.com link. :slight_smile:

If outputting just certain, specific keys from an array you may do it this way.
But if outputting all of the array in order, you would use a foreach loop.
Or you may use other kinds of loop with conditions, depending on your needs.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.