Is it possible in PHP?
I have a website with form + captcha on domain A -> there the captcha worked well.
It generates 1 session with the captcha code.
explanation -> https://postimg.cc/Wdzcw8vB
-> no problem so far

Now the server on which the domain A is hosted disabled sendmail - PHP mail() function so no PHP mail() function and no phpmailer with smtp on google works.
This way I can't send forms anymore.
Since it's impossible (for personal reason!) to move the website from domain A on server A to domain B on server B , I decided to use 2 domains on different servers.
I keep domain A on server A for the website and domain B on server B to send the forms -> works good except the captcha.
explanation -> https://postimg.cc/hhsRHvKb
My problem is when I call the form with captcha in iframe on domain B it generates 2 sessions in the /temp folder of server B: one with the captcha code and one empty! Now It always choose the empty session so the captcha is always wrong.

What I don't understand is ...
I open the domain A on server A with an iframe with contents which is on domain B on server B -> no session has been sent at all. Just opening a page from another server B in an iframe on server A.
Now from that page (normal page) which is on domain B on server B, I call a new page with form in the iframe with the captcha -> session_start(); -> so session is sent from domain B on server B
look again for explanation here -> https://postimg.cc/hhsRHvKb
So I call the session on domain B on server B -> why does it create 2 sessions instead of 1
What PHP code do I have to add so it takes the right session with the captcha code?
I hope someone can help me with my problem (if it's possible of course)
Thanks in advance
Best regards.

Dani AI

Generated

Short diagnosis (what's actually happening)
When you embed domain B inside an iframe on domain A the browser treats domain B cookies as third‑party. If those cookies are not sent on every request (the form page, the captcha image request, the final submit) PHP will create a fresh session for each request — hence two files in /tmp, one with the captcha and one empty. was right to flag cross‑origin issues, and 's session hints are useful, but the root cause is browser cookie policy in a cross‑site context.

Practical, reliable fixes (ordered by reliability)

  1. Avoid depending on cross‑site cookies: generate a short random token on the form page, store the captcha value server‑side keyed by that token, then use the token in the image URL and as a hidden form field. That way no session cookie is required:
<?php
$token = bin2hex(random_bytes(16));
file_put_contents(sys_get_temp_dir()."/captcha_$token", $captchaText);
// In the HTML:
?>
<img src="captcha.php?token=<?php echo $token; ?>">
<input type="hidden" name="captcha_token" value="<?php echo $token; ?>">

In captcha.php read the token, load the stored value and render the image. On submit, validate against the stored token. Expire/delete tokens and use secure random bytes.

  1. If you must use PHP sessions across origins, set the cookie attributes before session_start() so the cookie is allowed in third‑party contexts (note: many browsers or privacy settings still block third‑party cookies):
<?php
session_set_cookie_params([
  'lifetime'=>0,'path'=>'/','domain'=>'your-domain-b.com',
  'secure'=>true,'httponly'=>true,'samesite'=>'None'
]);
session_start();

Troubleshooting checklist

  • Use DevTools Network to inspect the captcha image request and the form submit: compare Request Cookie and Response Set‑Cookie headers and the session ids.
  • Log session_id() on each request to confirm mismatches.
  • Prefer the token approach if you cannot rely on third‑party cookies or server config changes.

Security notes
Never trust a visible session id passed without validation. Tokens should be unpredictable, short‑lived, and removed after use. This avoids session fixation and is the most robust solution for cross‑domain iframes.

Recommended Answers

All 13 Replies

Hi Code runner

You have two questions here -> one about sessions and one about email, not knowing your exact configs I can suggest the following:

1.) Sessions

Naming your sessions using session_name can help in seeing if the server settings have been configured to auto start the PHP session. (session_name is called before session_start!) Any character output before your PHP code will result in a session being started automatically. I have found this to be a common cause of session woes.
See if you can turn off the session auto start and control the sessions in your code.

2.) Getting phpmailer (recommended for sending email) to work on an unknown server can be a daunting task, however I have found the debug mode to be very useful in this case. The config I have below can assist in your efforts. The SSL certs can cause problems as well and default disabling of their validation could help your things to work.

                        $phpMailer->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_LOWLEVEL;                      // Enable verbose debug output
                        $phpMailer->isSMTP();                                            // Send using SMTP
                        $phpMailer->Host = "mail.gmail.com";                   // Set the SMTP server to send through
                        $phpMailer->SMTPAuth = true;                                   // Enable SMTP authentication
                        $phpMailer->Username = "someuser";                     // SMTP username
                        $phpMailer->Password = "somepassword";                               // SMTP password
                        $phpMailer->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
                        $phpMailer->Port = 485; //or whatever other port                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
                        $phpMailer->SMTPOptions = [
                            'ssl' => [
                                'verify_peer' => false,
                                'verify_peer_name' => false,
                                'allow_self_signed' => true
                            ]
                        ];

Hello andrevanzuydam and thank you for your reply.
1.) Sessions
I don't understand what you mean with "using session_name". Can you give me an example and a php code with explanation?

2.) The host simply doesn’t allow external SMTP connection.
SMTP ERROR: Failed to connect to server: Network is unreachable

Regards,

Hi Code runner

Sorry to hear on the resolution of the SMTP - seems like it is blocked - you're left with using an email service which can accept API requests I suppose.

The idea behind naming sessions is to separate out the session variables for each php application you may run on your local machine or server especially if they are hosted under the same "instance" of the webserver ->

This needs to happen before session_start()

session_name("someSession");
session_start();

Have a look at the cookies in your browser you will the reference to "someSession". An easy way to check what is going on with session_name is to set session variables then print_r($_SESSION).

Thanks again andrevanzuydam but it doesn't seem to solve my problem.

I found this code on the internet and it seems to solve the problem for 90% ... but it accepts a fault captcha too!
But I don't know what the code exactly means or does ...

if ( !isset($_SESSION['captcha_code']) ) {
    // does not exist yet, so create with 0
    // you may want to initialize it to 1, thats up to you
    $_SESSION['captcha_code'] = 0;
} else {
    $_SESSION['captcha_code'] = $_SESSION['captcha_code'] == 0 ? 1 : 0;
}

Do you know what above code do?

Regards

The code above literally translated ->

  • if the session capture code is not set make the value to 0
  • else if the session capture is set and it equal to 0, set it to 1 otherwize set it to 0

I'm not sure exactly you want to do with the captcha code, I would question the else statement, surely you would want to see or validate the captcha ?

//Set a variable for if the captcha_code is valid
$captchaValid = false;
if (!isset($_SESSION["captcha_code"])) 
{
   //not valid
   $_SESSION["captcha_code"] = 0;
} else {
   if (!empty($_SESSION["captcha_code"]))
   {
      //some function to validate the captcha
      $captchaValid = validateCaptcha($_SESSION["captca_code"]);
   } else {
      //not valid
      $_SESSION["captcha_code"] = 0;
   }
}

if ($captchaValid)
{
   //What if valid
} else {
  //Not valid
}

Thank you for your clear "literally translation".

I'll try to explain ...
1.) It's a form that people have to fill in
2.) the captcha_code is to see if it's not a bot but a humain being.
3.) button send -> validate field + captcha_code -> no errors -> sending form

scheme ->
https://postimg.cc/hhsRHvKb
https://postimg.cc/rRrywXhv

Also read my above reply ...

The code you sent also accepts a wrong captcha_code ((the same as mine) ... not good ... :-(
How to avoid entering wrong captcha?

if ($captchaValid)
{
   //What if valid
   echo "valid";
} else {
  //Not valid
  echo "not valid";
}

I echo the -> if ($captchaValid) <- but always shows not valid ... ?? $captchaValid ?? doesn't even exist?
Something seems to be missing but what?

Thanks for helping me to find a solution for my problem!!
Regards

Nobody knows a solution?

Regards

First I do not have a solution outside of you fixing your first domain problems be whatever those are. It looks like you are trying to code around a badly configured server rather than fix the server/service issues.

So why am I writing at all? Because I see cross-origin brick walls looming and you as the developer must be conversant about what that is and why it is the way it is. If you don't know cross-origin issues, now is the time to research that. Plenty written so I'm glossing over what this is but in my reading above, it may apply if not now, in a bit.

However once you figure that out you may want to read https://en.wikipedia.org/wiki/Cross-origin_resource_sharing since it shows us that cross-origin work is possible but (surprise?) it's not just code but server configuration.

I'm not an expert in PHP, better call me a newbie and trying to get some help for my problem from experts.
So if I understand you well (English isn't my native language) then this is a server related problem and can't it get fixed at all.
I'm not the owner of the servers so I can't change settings, My websites are hosted by two different companies.
So it can't get fixed with a PHP code or with whatever pc language.
Thanks for your reply.

Regards

I'm not an expert in PHP, better call me a newbie and trying to get some help for my problem from experts.

Sometimes even a PHP expert has to admit that a server configuation issue can't be overcome with PHP code.

Since you have more than one choice of servers my answer is to host on the servers that work correctly.

That was my question I asked in my first post, first line -> "Is it possible in PHP?"
Final answer -> No, it's server related ... (settings)

Thanks for your reply.

Regards

While you lead with most of the information in your top post, more was revealed later plus I had time to ponder on your issue. This is why there would be a discussion and not a flat out No. Also, there may be someone with a workaround that hasn't been considered yet such as pushing this clientside with a chunk of javascript.

The more I thought about it the clearer it was to me that some server configuration would be required and apparently even that isn't possible.
As such I changed my mind on the answer or rather that any workaround would be too onerous for most to attempt.

PS. Onerous: Involving an amount of effort and difficulty that is oppressively burdensome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.