PHP header function not triggering? - php

I'm getting some fairly odd behavior here... I noticed that only localhost, a header statement I have worked just fine, but when copied over (SAME EXACT CODE) to my live site, the header statement no longer triggers.
I added some echos to help debug. This if statement will only trigger if the URL variable id is NOT set. So with this same exact code on localhost, I never see these debug statements. On the live site, I do... which I shouldn't. I should get redirected instead. Anyone know why a header statement would be ignored?
if((!isset($_GET['id'])) && $rows != 0) {
$result = mysql_query('SELECT videoinfo FROM videos where game_id=' . $gameid . ' LIMIT 1');
$row = mysql_fetch_array($result);
$tubeID = $row['videoinfo'];
echo '<script type="text/javascript">';
echo 'window.location = "videos.php?id=' . $tubeID . '&awayid=' . $awayid . '&homeid=' . $homeid . '&date=' . $date . '&time=' . $time . '&gameid=' . $gameid . '&play=0"';
echo '</script>';
}
EDIT 4 people have told me already that I can't have any echo calls before my header function. This code WORKS on localhost and the header function DOES trigger. Regardless, REMOVING the echo statements DOES NOT fix it.

AFAIK
Can't send header() after some echo.

You cannot output ANYTHING before you call header(), i.e. echo etc...

I don't think you can have a header after any sort of output. I just came up with that.

You need to enable output buffering. This is probably enabled on your localhost but not on your live system (or the value on the live system is too small).
This will keep your output buffered, and then the Header will work fine.
Your debug statements are making the problem worse.

header statements will not work if there is any output before they are called. In this case, your echos are killing it. Also, make sure there is no other output before this is called (white space, HTML, etc.).

at start of script, add
ob_start();
and just before calling header();, use
ob_clean();
ob_clean();
header('Location: videos.php?id=' . $tubeID . '&awayid=' . $awayid . '&homeid=' . $homeid . '&date=' . $date . '&time=' . $time . '&gameid=' . $gameid . '&play=0');

Edit
Check to ensure that your files are encoded correctly. For instance, if you are encoding in UTF-8, make sure you encode in UTF-8 without BOM (Byte Order Mark).
How to check depends on what you use to edit and save your file. For instance, I use Notepad++ so I just go to the 'Encoding' menu and select 'Encode in UTF-8 without BOM' and then save the file.

function goto_url($url) {
// must not have output anything prior to calling this function
if (!headers_sent()){
header('Location: '.$url); exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
};
};
http://www.w3schools.com/php/func_http_headers_sent.asp

Related

Getting console output in Laravel

I need to capture the output of a console command to be sent by email as well when requested. How can I do this?
How do I get the output generated from the following $this->info() calls?
$r = processData();
$this->info("\nSubmitted data:");
$this->info("SubmissionId: " . $r['submission_id']);
$this->info("Status: " . $r['status']);
Decided to just replace the $this->info() calls with a simple echo command and output buffer control. Looks good enough in the console and catches the data requested for emailing.
Example:
$r = processData();
if ($this->option('email-results'))
ob_start();
echo "\nSubmitted data:";
echo "\nSubmissionId: " . $r['submission_id'];
echo "\nStatus: " . $r['status'];
if ($this->option('email-results')) {
mail(
$this->option('email-results'),
'Results on ' . $start_time->toDateTimeString(),
ob_get_contents()
);
ob_end_flush();
}
an Artisan method could help:
\Illuminate\Support\Facades\Artisan::output()

Is it a good practice to use "die()" when dealing with custom PHP Exceptions?

I've wrote a custom exception class in PHP:
<?php
class Custom_Exception extends Exception {
public function __construct( $title, $message, $code = 0, Exception $previous = null ) {
parent::__construct( $message, $code, $previous );
echo '<html>';
echo '<head>';
echo '<title>Custom Exception: ' . $title . '</title>';
echo '</head>';
echo '<body>';
echo '<h1>Custom Exception</h1>';
echo '<hr />';
echo '<p><strong>Error: </strong>' . $title . '</p>';
echo '<p><strong>Message: </strong><em>' . $message . '</em></p>';
echo '<hr />';
echo '<p>This Exception was raised on: ' . date( 'Y-m-d' ) . ' at ' . date( 'H:i:s' ) . '.';
echo '</body>';
echo '</html>';
http_response_code( $code );
die();
}
}
Is it a good practice to end my __construct overriden method with die(), to prevent outputing any parent class "Exception" messages?
As you see it outputs an HTML response into the browser. I've never dealed with custom PHP exceptions before, so I would like to know does this bother any conventions, etc?
DCoder has a good point about sending the error to you or login it in a file so you can analyse it later, but about your question, die could be a bit drastic, it's much better to redirect the flow of the application to a page that informs, in plain language, that an error has happened and that the administrator will try to solve it. You can reword that in many ways.
But, the important part, is that the client should not be bothered or discouraged by the error. If you can explain the reason of the error and tell the user how to solve it, or not make it again and redirect to the last good step, that's the best way. If you can't, then you should try to explain and redirect to a safe but useful page, like the home page or a page with the error explanation and resources, like a search bot, the site map, the navigation tools or any other thing that may help.
I'd say, never just kill the application.
Bye

Echo entire pre-compiled php page

For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

PHP variable-infused link not writing to a variable?

http://www.reecemcmillin.com/albums/
<?php
$uncut = file_get_contents('http://www.google.com/#sclient=psy-ab&hl=en&safe=active&source=hp&q=' . $_POST['band'] . '+' . $_POST['album'] . '+zip+inurl:mediafire');
$strip1 = strstr($uncut, 'www.mediafire.com/?');
$link = substr($strip1, 0, 30);
echo $link;
?>
It doesn't seem to be writing the website content to $uncut. Can somebody help me figure out what's wrong? Thanks.<3
Clients are not supposed to send URI-fragments (the portion of the URI following #) to servers when they retrieve a document. PHP is probably sending a request for the google homepage, effectively: file_get_contents('http://www.google.com/');. If you echo $uncut, that's probably what you'll see you're getting back.
Try a querystring-based URI instead.
<?php
$uncut = file_get_contents('http://www.google.com/search?sclient=psy-ab&hl=en&safe=active&source=hp&q=' . urlencode($_POST['band']) . '+' . urlencode($_POST['album']) . '+zip+inurl:mediafire');

Get redirected from URL in php

I want to know how to get the original URL from php
For example:
example.php
<?php
header('location:test.php');
?>
I want to get test.php from example.php.
example.php
<?php
header('location:' . $_SERVER['HTTP_REFERER']);
?>
This should work fine.
Redirection with some delay say after 5 sec wait.
function js_redirect($url, $seconds)
{
echo "<script language=\"JavaScript\">\n";
echo "<!-- hide code from displaying on browsers with JS turned off\n\n";
echo "function redirect() {\n";
echo "window.parent.location = \"" . $url . "\";\n";
echo "}\n\n";
echo "timer = setTimeout('redirect()', '" . ($seconds*1000) . "');\n\n";
echo "-->\n";
echo "</script>\n";
return true;
}
js_redirect("http://www.exapmle.com",5); // Redirect after 5 sec
you forget to use
ob_start();
in first of your code :D
elsewhere you can use js in this case , for example :
echo 'javascript:window.location="http://example.com";';

Categories