-3

I have a button that when clicks plays a song. What I am trying to do is when the button is clicked an images displays "now playing" while the song plays and then the page reloads when finished.

What is happening is that when the button is click the song plays and then the image displays "now playing" as the page reloads.

How can I get it to display the "now playing" graphic before playing the song?

The code

<?php

if (isset($_POST['PlaySong']))

{

echo ("<img src='/images/nowplaying.png'>");
exec ("/usr/bin/sudo /home/pi/scripts/song.sh");
header ('Location: '.$_SERVER['REQUEST_URI']);

?>

2 Answers2

0

This is what I had to do to get this to work. Note it takes 50 seconds to play song.

<?php

if (isset($_POST['PlaySong']))

{
echo ("<img src='/images/nowplaying.png'>");
shell_exec ("/usr/bin/sudo /home/pi/scripts/song.sh > /dev/null 2>/dev/null &");
header ('Refresh: 50; URL=http://myurl');
}

?>
-1

When setting the Location header, the browser makes a GET request to the page (in your case, the same one). So that's normal that the $_POST array is empty after your redirect.

Instead, use a GET parameter.

Replace header ('Location: '.$_SERVER['REQUEST_URI']);

with

header ('Location: '.$_SERVER['REQUEST_URI']."?PlaySong=1");

and

isset($_POST['PlaySong'])

with

isset($_GET['PlaySong'])

and you should be fine.

EDIT: corrected syntax errors.

Marco
  • 118
  • 2
  • 9
  • You've copy-pastaed some syntax errors. (Not the voter) – Alexander O'Mara Apr 23 '16 at 15:57
  • Thank you Alexander, I didn't notice that. Fixed – Marco Apr 23 '16 at 16:00
  • I think his problem is bigger than that. Looking at his code, this would create an infinite redirect loop. – Magnus Eriksson Apr 23 '16 at 16:05
  • I agree with you. My point was only underlining the type of the request after the header instruction, didn't follow the logic. – Marco Apr 23 '16 at 16:08
  • Sure, but you're assuming that he wants to redirect the page again with "PlaySong" set. I think his question in its current state is unanswerable. – Magnus Eriksson Apr 23 '16 at 16:15
  • Code works but nowplaying.png is shown after song.sh executes, is there a way to display the png right after the button is clicked and before the song.sh executes? – Cooper Pedigo Apr 23 '16 at 16:36
  • That's right, after all. exec() returns only after the generated process terminates. If you need to return from exec immediately, see [this](http://stackoverflow.com/questions/1019867/is-there-a-way-to-use-shell-exec-without-waiting-for-the-command-to-complete) as an example to let the process run in the background. – Marco Apr 23 '16 at 16:41
  • Is there a way to get the now playing image to show up before the exec() even runs but after the button is clicked – Cooper Pedigo Apr 23 '16 at 16:59