-2

I have the following code

<?php   
    $token = '';
    if(!empty($_POST['token'])) $token = $_POST['token'];

    $url = '';
    if(!empty($_REQUEST['url'])) $url = Sanitize($_REQUEST['url']);

    if(!filter_var($url, FILTER_VALIDATE_URL)) return 'erro1';
?>

This page is supposed to be executed by AJAX so I'm coding error codes, now if the URL is not valid, I expect it to return erro1

The problem is, it never returns erro1. I tried dumping the result of the filter_var and it was false as expected! The page simply executes and return nothing even though the URL is not valid, but if I switch return with an echo, it works.

Why is that? Why is echo working but not return?

Ali
  • 3,479
  • 4
  • 16
  • 31

2 Answers2

4

You need to use echo instead of return. Your Web server executes the PHP code and serve its output, which you produce using echo and other printing functions.

Outside of a function, return interrupts the script.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
3

return will return a value from a function to the the code that called that function. It can only be used internally within PHP.

Your return statement is not in a function.

To write data to the HTTP response where JavaScript can read it, you need to use echo, print or similar.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335