0

I have issue to redirect another location after fopen() function in php. below is my function which i m using.

<?php
function create_file($filename){
    $my_file = 'folder/index.php';
    $fh = fopen($my_file, "wb");
    $data = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Some data</title>
   </head>
    <body>Here some data</body>
            </html>';
  fwrite($fh, $data);
        fclose($fh);
return true;
ob_end_clean(); 
exit();
}
$file = create_file(test);
if($file == true){
   $url = 'http://example.com';
   return $url;
}
else{
return 0;
}
?>

2 Answers2

0

If you want to redirect in PHP, you cannot send any output to the server before header("Location: http://example.com");.

This includes any HTML, text or white spaces that aren't wrapped in a PHP tag set.

Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
  • if i call create_file() after header location then file not created in backend :( – harpreet singh Feb 10 '16 at 17:28
  • have you tried using a `Javascript` redirect instead? – Derek Pollard Feb 10 '16 at 17:29
  • actually i m using ajax post method with json here in create_file() i m returing filename and in ajax after post submission i m redirect on file name. in ajax. – harpreet singh Feb 10 '16 at 17:31
  • Yep, you could use JS redirection. Or call the createfile function in an ajax call. Or also try calling ob_start( ); at the start of the page (before anything) and ob_end_flush( ); at the end (after anything) to control when the content is output (but I'm not 100% on that). – Matthew Lymer Feb 10 '16 at 17:34
  • its not working with ajax if i use it with direct php code only then its working well. i have problem with ajax code – harpreet singh Feb 10 '16 at 19:09
  • Check this out: http://stackoverflow.com/questions/282429/returning-redirect-as-response-to-xhr-request/2573589#2573589 – Derek Pollard Feb 10 '16 at 19:11
  • Also - are you trying to redirect to a link that is outside of your domain? – Derek Pollard Feb 10 '16 at 19:12
0

The header function must be called before any page output (if HTML has already been displayed, it's too late for your headers!).

Matthew Lymer
  • 992
  • 6
  • 10