ping test and command injection prevention

The following code is a PHP code that is vulnerable to injection. What I want is to prevent the injection but also be able to ping. I was able to prevent the vulnerability but it was not pinging at all.

<html>

<head>

</head>

<body>

<?php

$name = “”;

$ip = $_POST[“ip”];

$ping = “ping -w 3 “. $ip;

$output = shell_exec($ping);

?>

<h2>Use this website to ping anything you want</h2>

<form method=”post” action=”<?php echo $_SERVER[“PHP_SELF”];?>”>

Enter the ip address or the full url: <input type=”text” name=”ip”>

<br><br>

<input type=”submit” name=”submit” value=”Submit”>

</form>

<?php

echo “<h2>Your Result:</h2>”;

echo $ip;

echo “<pre>$output</pre>”;

?>

</body>

</html>