/    Sign up×
Community /Pin to ProfileBookmark

PHP Redirect Code Ok ?

Folks,

They say PHP redirect should be on top part of page above all code. They say similar with session_start(). So which one above the other if both in page ?
And how can you add them on the html header tags section when you got no HTML tags in the page like so …

[code]
<?php
session_start();

require(‘Error_Reporting_Template.php’);
require(‘Conn_Template.php’);

$url = $_GET[‘url’];

//DB Insert Record Into Logging Database.
$query = “INSERT into logs(domain,url,anchor,description,keywords) VALUES (?,?,?,?,?)”;

$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt,$query);
mysqli_stmt_bind_param($stmt,’sssss’,$_SESSION[‘domain’],$_SESSION[‘url’],$_SESSION[‘anchor’],$_SESSION[‘description’],$_SESSION[‘keywords’]);
mysqli_stmt_execute($stmt);

header(“Location: $url”);
die();

?>
[/code]

Is my code lines in right order ?
The code belongs to my tracker.php.
You see, I building Searchengine. Have you seen when Google presents you search results, the result links are not directly linked to the listed websites but to Google tracker ? This way, when you click a link after reading it’s description on the SERP, you first get sent to their tracker that logs the link click before redirecting you to the destination website. I building such a tracker.where the destination link gets logged before you are forwarded to the destination you chose to go by clicking the third party website’s link found on my SERP.

Is my tracker code ok ? Or need to add more security ? If so then what ?

to post a comment

9 Comments(s)

Copy linkTweet thisAlerts:
@developer_webauthorMar 06.2021 — This tutorial says if you write even a single whitespace before the 'header' part in the code "header("location: $url');

then you get error by PHP: "Header already sent".

Does that mean my above code is wrong ?

https://code.tutsplus.com/tutorials/how-to-redirect-with-php--cms-34680
Copy linkTweet thisAlerts:
@NogDogMar 07.2021 — The only problem would be white-space before the opening &lt;?php tag (as long as none of the PHP code that precedes that header() call might cause any output to the browser).

Both session_start() and header(), along with set_cookie() cause various HTTP headers to be be sent in the response back to the browser. Headers cannot be sent if output has already been generated from your script, as once output starts, any pending headers are sent first, and no more can be added.

Therefore those commands do not necessarily have to be the very first thing, and you can have other PHP code execute before either/both of them before they get executed, _as long as none of that code causes output to be sent._ Note that "output" is not just things that PHP might echo or otherwise cause to be output (including error output if enabled), but also anything not within &lt;?php ... ?&gt; tags. So anything before the first &lt;?php tag, _including white-space or non-printing characters,_ will cause HTTP headers to be sent and disable those functions that want to set/change headers. (This is also why it's generally good practice to _not_ put a trailing ?&gt; at the end of pure PHP files that might be included/required by other scripts, just in case any white space of any sort gets into that script after the closing tag.)
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — @NogDog#1628974

Thanks. You probably saved me countless hrs of debugging going crazy.

Did you just tell me the Php opening tag should be the first thing written on all my files to prevent headers being sent to the client's browser by my server ? No HTML tags, even the <!DOCTYPE html> ? Wait, I think this is what I read about last night. Need to check the article again!

So if I exclude the closing PHP tags on my files that get included, I won't get any errors ? Are you sure ?
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — Folks,

What's the TRUE part for ?
<i>
</i>&lt;?php
// index.php
header("Location: http://www.yoursite.com/new_index.php", TRUE, 301);
exit();
?&gt;
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — Folks,

Do write down all the different types of codes you use to redirect a visitor from one page to another. I want to see which one looks easier to learn. Memorise. So don't need notes anymore in future.
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — @NogDog,

I already mentioned why I building this link tracker.php. Even though tutorials say that, we should exit() or die() immediately after the redirection code, since I want to log the link click, must I not write the code to dump the url into the logging dB or must I write that part of the code before the redirection part of the code ? If I do latter then wouldn't it take time to load the page as logging to dB is getting done first before redirection to new URL ?

I wrote the logging code, then the redirection code then the exit code.

Maybe, I write the redirection part first then don't put exit() beneath it but the "logging link click to dB" part of the code and then finally at the end add the exit() ?

That way, as soon as the page loads the user is redirected (user no longer waits) and the "link click logging" code can be run In the background after the user has been redirected.

What do you say ?
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — @Sempervivum

Which order do you write your code ?

Check my op and my previous post to know what I am talking about.
Copy linkTweet thisAlerts:
@NogDogMar 07.2021 — > @developer_web#1628982 So if I exclude the closing PHP tags on my files that get included, I won't get any errors ? Are you sure ?

No, that just prevents one possible cause of a "headers already sent" error. It is not a cure-all.

> @developer_web#1628984 What's the TRUE part for ?

https://www.php.net/manual/en/header (Yep, that pesky old official PHP manual):

"The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in false as the second argument you can force multiple headers of the same type."

> @developer_web#1628988 That way, as soon as the page loads the user is redirected

The header won't actually be sent until either output is generated or you exit the script (and essentially empty output is sent). In any case, if your logging and such is taking long enough that any human user would notice the difference, there's something wrong with that logging code.
Copy linkTweet thisAlerts:
@developer_webauthorMar 07.2021 — @NogDog#1628990

Actually, in my previous years experiences the logging didn't take long. I just got spooked after I remembered I tried emailing and it took time for page to load.

Look at it this way.

My page is a high traffic article describing latest Mac.

I put a PHP script to notify 100 Mac sponsors when a visitor enters my article page so the sponsors can enter my article page and start a chat with my article reader. One chat board, 100 Mac sponsors and one article reader. Imagine the scenario. Ok. 100 sponsors would drive my reader crazy and drive him away but let's say I only allow 5 of them to engage in chat while the other 95 watch the chat (market research for them). Ofcourse, I charge all sponsors for that engagement single session.

Now as soon as the visitor or reader enters the page, the PHP needs to email alert 100 sponsors. I found the mail() really slowing down my page to load.

I was looping the mail() 100 times to email 100 recipients. On each loop, there was one email address on the "To" field.

That was around last Dec. I got disheartened.

So you see why the page loading took time ? It is because the PHP tried adding one email to the "To" field then mail out the mssg using mail(), then loop again the same mssg to the 2nd recipient. Likewise mail too 100 recipient in 100 loops.

The other day, a thought came into my mind. Why loop the mail() 100 times ? Why not just once but instead of getting PHP to insert 100 emails on the "To" field, is it not best to insert

all 100 emails in the "Bcc" in the first round ? That way, the mail() is not called 100 times per each visit to the page but once. Page loading should be a hundred times faster now. Would it not ?
×

Success!

Help @developer_web spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...