r/PHPhelp • • Feb 28 '26

Solved Problems with XAMPP opening the default browser

1 Upvotes

Hi everybody, I'm new to this sub and php in general, so I apologise if my question is dumb or not appropriate to this place.

I'm trying to run php for the first time on my linux mint xfce computer, and I have heard that a great place to start is with XAMPP. I am having some problems with that.

The main issue is that, when I run

sudo /opt/lampp/manager-linux-x64.run

The GUI opens fine, but then when I try to click on 'Get started' I get the following error message

[11233:11233:0228/211447.160334:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:101] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

Toghether with an error window that states an 'input/output error' and that the application could not open the browser.

I use Chome as my default browser, but I saw that the issue persisted even if I changed it to Firefox.

Below I will add my installation procedure, together with any tweaks that I tried.

----installation procedure below---

First I ran

sudo apt install php

Then I dowloaded the linux .run file for XAMPP, made it executable and activated it with the ./ command.

Then I figured out that it was incompatible with the Apache2 that was installed with the sudo apt install php, so I ran

sudo systemctl stop apache2

sudo systemctl disable apache2

Now 'sudo /opt/lampp/lampp start' works fine.

That's basically it, I did not do anything else.

Any help is appreciated. Thanks for everybody that will take the time to read this long and boring request for help.

edit: formatting edit2: as other suggested, I let go XAMPP and simply installed php, apache and it works flawlessly. Thanks everybody for your help and your suggestions.


r/PHPhelp • • Feb 24 '26

Solved PHPMailer only works some of the time.

4 Upvotes

As the tittle says the mailer works some of the time perfectly. I can mail out dozens of emails for a while and 15 minutes later it suddenly stops working completely, another 15 minutes later it can suddenly work again flawlessly or maybe not...It running or not running seems completely random, but if the email sends then most likely the next one will as well and vice versa.

I used postman for trouble shooting and with the exact same data it sometimes works and sometimes it doesn't.

I asked the guy who manages the security if it might be tripping over something, but he didn't see anything.

The error I keep getting is 500, I already placed this in to the code, but I still only get error 500:

error_reporting(E_ALL);

My code even though I don't think there's something wrong in this part:

$filenaam = "$map\\$attachment";
$ccar = array();
if ($emailadress2 !== '')
{   $cc = new mailAddress();
    $cc->name = $emailadress2;
    $cc->address = $emailadress2;
    $ccar[]=$cc;
}

$fa = new fileattachment();
$fa->filename=$filenaam;
$faa=array();
$faa[]=$fa;

ccar: ".$ccar."\n header: ".$emailheader."\n text: ".$emailtext."\n faa: ".$faa);
if (!Send_Email(MAIL_FROM_ADDRESS,MAIL_FROM_NAME,$toar,$ccar,$emailheader,$emailtext,$faa))
{$resultcode=8;}

The file for the Send_Email function:

<?php
 //use PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\PHPMailer;

 require 'PHPMailer/src/PHPMailer.php';
 require 'PHPMailer/src/SMTP.php';
 require 'PHPMailer/src/Exception.php';
 require 'PHPMailer/src/OAuth.php';
 require 'PHPMailer/src/POP3.php';

class mailAddress {
    public $name;
    public $address;
}

class emailAddress {
    public $emailAddress ;
}

class _bodytext {
    public $contentType;
    public $content ;
}

class fileattachment {
    public $filename;
}

class _365attachment {
    public $odatatype;
    public $Name;
    public $contentType;
    public $contentBytes;
    //Name' => 'blah.pdf', 'ContentType' => 'application/pdf', 'Content' => 'results of file_get_contents(blah.pdf)')  )
}

function Send_Email($fromaddress,$fromname,$toaddresses,$ccaddresses,$subject,$bodytext,$attachmentlist)
{
$returnvalue=false ;    
$smtp_mail = 0 ;
$graph_mail= 0;

if (MAIL_through=='smtp') { $smtp_mail=1; }
if (MAIL_through=='o365') { $graph_mail=1; }

if ($smtp_mail==1)
{
    $smail = new PHPMailer(true);//(false);

    //try {
    $smail->isSMTP();// Set mailer to use SMTP
    $smail->CharSet = "utf-8";// set charset to utf8
    $smail->SMTPAuth = false;//MAIL_SMTP_LOGIN;// Enable SMTP authentication
    $smail->Host = MAIL_SMTP_SERVER ;// Specify main and backup SMTP servers
    $smail->Port = MAIL_SMTP_PORT;// TCP port to connect to
    $smail->isHTML(true);// Set email format to HTML
    $smail->setFrom( $fromaddress, $fromname);//Your application NAME and EMAIL
    $smail->addReplyTo($fromaddress);
    $smail->Subject = $subject ;
    $smail->MsgHTML($bodytext);// Message body

    foreach ($toaddresses as $ea)
    {   $smail->addAddress($ea->address); }
    foreach ($ccaddresses as $ea)
    {   $smail->addAddress($ea->address); }

    if (!$attachmentlist==null)
    {    
        $att = new fileattachment() ;
        foreach ($attachmentlist as $att)
        {
            //print "Smail: ".$smail;
            //print "Filename: ". strval($att->filename);
            //print "test";
            if (file_exists($att->filename)) {
                //print "test";
                $smail->addAttachment($att->filename);
            //} else {
                //print "File bestaad niet";
            }
        }
    }


        if (!$smail->send() )
        { $returnvalue=false;}
        else
        {$returnvalue=true ;}
    // } catch (Exception $e) {
    //     echo $e;
    //    echo "❌ Fout bij verzenden: {$smail->ErrorInfo}";
    // }

    
}
if ($graph_mail==1)
{
    class mJSON {
        var $toRecipients;
        var $ccRecipients;
        var $subject;
        var $importance ;
        var $replyTo ;
        var $body;
        //var $images;
        var $attachments;
    }
    $rep = new mailAddress() ;
    $rep->name=$fromname ;
    $rep->address = $fromaddress ;
    $rep2 = new emailaddress() ;
    $rep2->emailAddress=$rep ;
    $jparam = new mJSON() ;
    $jparam->subject = $subject ;
    //$jparam->replyTo=$rep2 ;

    $toa=array() ;
    
    foreach ($toaddresses as $ea)
    {
        $toe = new emailaddress() ;
        $toe->emailAddress=$ea ;
        $toa[] = $toe ;
    }

    $cca=array() ;
    foreach ($ccaddresses as $ea)
    {
        $cce=new emailaddress() ;
        $cce->emailAddress=$ea ;
        $cca[]=$cce ;
    }
    $repa=array() ;
    $repa[]=$rep2 ;
    $jparam->replyTo=$repa ;

    $bodytxt = new _bodytext() ;
    $bodytxt->contentType= 'HTML' ;
    $bodytxt->content = '<html>'.$bodytext.'</html>' ;

    $jparam->toRecipients=$toa ;
    $jparam->ccRecipients=$cca ;
    $jparam->body = $bodytxt ;
    $jparam->importance='normal';

    $jparam->attachments=array();
    if (!$attachmentlist==null)
    {
        $aolist=array();
        $att = new fileattachment() ;
        foreach ($attachmentlist as $att)
        {
            $oatt=new _365attachment();
            $oatt->odatatype='microsoft.graph.fileAttachment';
            $oatt->Name=basename($att->filename) ;
            $oatt->contentType='text/plain';
            $oatt->contentBytes=base64_encode(file_get_contents($att->filename));
            $aolist[]=$oatt;
        }
        $jparam->attachments=$aolist ;
    }

    $graphMailer = new graphMailer(O365_tenantid,O365_clientid,O365_secretid) ;
    $jparam2=json_encode($jparam) ;

    $jparam2 = str_replace('odatatype','@odata.type',$jparam2);

    if (!$graphMailer->sendMail($fromaddress,$jparam2,false))
    { $returnvalue=false;}
    else
    { $returnvalue=true;}

}
return $returnvalue ;
}

?>

(mind you I didn't write this code it's from a colleague who wrote it years ago, but it's now up to me to fix it and there's no documentation.)


r/PHPhelp • • Feb 23 '26

Solved I get an internal server error when trying to open the default Laravel view: welcome.blade.php

3 Upvotes

First, I get a warning when running composer create-project laravel/laravel projectname, which says: WARN could not find driver (Connection: sqlite, Database: /path/to/my/project/database/database.sqlite, SQL: select exists (select 1 from "main".sqlite_master where name = 'migrations' and type = 'table') as "exists").

Then when I run php artisan serve, localhost:8000, I get an internal server error "Illuminate\Database\QueryException" with the message: could not find driver (Connection: sqlite, Database: /path/to/my/project/database/database.sqlite, SQL: select * from "sessions" where "id" = JX7b9QAAl2AjLC6ghgLMwpf8H8FBt6a0QFqxSLBD limit 1)

I am on arch linux, and the package php-sqlite is installed. I also have php-pgsql installed which is what I actually want to use, but trying to change any settings to switch to it causes the same types of errors.

- - - - - Update - - - - -

I was following this video, which made getting things running seem so simple, but apparently on Arch it's more complicated.

First, I needed to edit /etc/php/php.ini, uncommenting the line for the database extension I wanted to use, in my case "extension=pdo_pgsql".

Then I needed to edit DB_CONNECTION in .env inside the Laravel project, changing sqlite to pgsql, and uncomment/add the info underneath.

Then in /config/database.php within the Laravel project, I switched sqlite to pgsql.

Enable postgres, and make sure the database that is referenced in .env is created.

And instead of messing with database sessions at this early stage, I switched SESSION_DRIVER in .env from "database" to "file".

And now it works.


r/PHPhelp • • Feb 21 '26

Looking for guides/walkthroughs/advice for taking a Laravel project from local dev to production.

6 Upvotes

I know there are a few services that will handle it all for you, but I want to learn a bit more about the process.

At the moment I have a project running locally (Herd). Just to play around before I go VPS, I want to run through the process (hopefully multiple times) of getting a Laravel project 'Production Ready'.

I'm not looking at setting up the Pi, installing nginx, etc. Have done this quite a few times and am comfortable with that.

More the Laravel specific things. What changes to make in the .env, what should or shouldn't be in my .gitignore, how to go about handling/monitoring queues, etc.

What are the optimisations, build processes, etc that change between dev/prod, what should github actions cover, etc.

And then once I have an understanding of what is happening throughout the process, what is the recommendation in terms of semi-autonomous deployments.

I don't mind a bit of reading, all about the learn!

Cheers. :)


r/PHPhelp • • Feb 16 '26

When to choose a function over a class, and vice versa?

7 Upvotes

I'm sure this is a common question, but I'd like to know what the criteria are for choosing a function or class to improve or add a feature.

I ask because in the Laracasts beginner course, there's a lesson where the host, Jeffrey, creates a Validator class with a string method to ensure a string's length is within a specified range. He also said that, later in the course, he would come back to that class to add a method that confirms whether a string is an email address.

The question is, considering that these are fairly simple methods, what's the benefit of creating a class over a function? In this particular case, it seems to make sense, since you have various functions that belong to a specific theme (validating strings), so, is that a criterion?

What are some other criteria for whether to orient the application toward objects or functions?


r/PHPhelp • • Feb 17 '26

Does Laracast Php and Laravel courses on youtube is still valid? (Not outdated?)

Thumbnail reddit.com
1 Upvotes

r/PHPhelp • • Feb 15 '26

PHP course

9 Upvotes

I know JavaScript,css and html I want to learn PHP ,of course I know I must try and write code to learn, but I want to understand complex concepts like cookies and.... ; if you can provide helpful tutorials


r/PHPhelp • • Feb 14 '26

Cannot load pdo_mysql with Apache2

1 Upvotes

Upgraded my Debian system from bookworm to trixie. Apache2 loads but pdo_mysql fails with the following error:

(/usr/lib/php/20240924/pdo_mysql.so: undefined symbol: pdo_dbh_ce)) in Unknown on line 0

I've found a few references to this error but nothing with a solution that works. Things I have tried:

```

>apt install --reinstall php-pdo php-pdo-mysql

Note, selecting 'php8.4-common' instead of 'php-pdo'

Note, selecting 'php8.4-mysql' instead of 'php-pdo-mysql'

```

```

phpenmod pdo_mysql

```

(I actually did phpenmod on every module listed in /etc/php/8.4/mods-available based on this: https://bugs.launchpad.net/ubuntu/+source/php8.4/+bug/2111102 )

Manually added a line to load to load pdo before the line loading pdo_mysql (Adds an extra error log that pdo is already loaded but does nothing else.)

I've both restarted the apache2 service and rebooted the machine multiple times which trying to fix this. Any suggestions welcome.


r/PHPhelp • • Feb 13 '26

Beginner PHP form project – looking for feedback on structure and best practices

4 Upvotes

Olá a todos,

Estou aprendendo PHP e recentemente construí meu primeiro projeto baseado em formulários. Comecei isso depois de receber a recomendação de praticar criando algo simples, mas funcional.

Como ainda sou iniciante, usei ChatGPT como auxílio de aprendizado sempre que ficava preso ou não tinha certeza de como implementar algo. No entanto, certifiquei-me de entender o código antes de usá-lo — meu objetivo é realmente aprender, não apenas copiar e colar.

Agradeceria muito por feedbacks e sugestões, especialmente em relação a:

  • Estrutura e organização do código
  • Validação e sanitização
  • Boas práticas de segurança
  • Legibilidade e manutenibilidade
  • O que devo focar em melhorar como iniciante

Estou ciente de que algumas partes podem não seguir as melhores práticas ainda, então qualquer crítica construtiva é bem-vinda.

Agradeço antecipadamente pelo seu tempo e ajuda!

https://github.com/ronaldomatheus364-collab?tab=repositories


r/PHPhelp • • Feb 11 '26

Solved phpMyAdmin shows terraria logo instead of it's own on xampp

2 Upvotes

This is an issue that my friend is having; instead of normal phpMyAdmin logo, the one of Terraria is displayed. We checked, the path to logo is correct, and in that location there is no terraria logo, but the correct one. On a machine that it happens on, terraria was never installed, nor any of the images were ever downloaded. It's a laptop running windows 8. This issue doesn't disrupt functionality of the whole program, but we are curious where that could come from.

Edit:

As am0x suggested, clearing the cache helped. However if anyone has any ideas where the logo could come from, feel free to comment, because I’m still curious of that


r/PHPhelp • • Feb 11 '26

Solved How to fix arabic direction?

3 Upvotes

Hello.

I want to print the lines in raw order.

		echo 'مكتب';

		echo ' number 123';

returns "مكتب number 123"

but

		echo 'مكتب';

		echo ' 123 number';

returns "مكتب 123 number"

How to maintain sequential order?

Thanks.


r/PHPhelp • • Feb 11 '26

Struggling with PHPMailer + Microsoft SMTP OAuth2 (XOAUTH2) – Any tips?

2 Upvotes

Hey everyone,

We've been trying to get PHPMailer working with Microsoft 365 SMTP using OAuth2 (XOAUTH2) authentication, and we're stuck.

Here's our situation:

We're using PHPMailer to send emails via smtp.office365.com on port 587 with STARTTLS.

We've set up an Azure AD app registration with the scope Things we've already tried:

Verified the access token is fresh and has the correct scope (SMTP.Send)

Confirmed SMTP AUTH is enabled for the mailbox.

Made sure the token user matches the FROM address

Has anyone successfully implemented PHPMailer with Microsoft OAuth2 SMTP? We'd really appreciate any pointers on:

Is there a specific Azure AD app configuration we might be missing?

Do we need specific API permissions (delegated vs. application)?

Has anyone run into issues with personal Microsoft accounts (e.g. yahoo/outlook) linked to a tenant?

Should we just give up on SMTP and use the Microsoft Graph API sendMail endpoint instead?

Any help would be greatly appreciated. Thanks!


r/PHPhelp • • Feb 11 '26

Any PHP or webdev newsletters/blogs you can recommend that aren't only shadcn or js framework news?

2 Upvotes

I finally decided to unsubscribe from daily.dev because each newsletter looks identical to the previous one, always about the js ecosystem and the new and shiny AI tool.

So I feel like it's not for me/us as PHP devs. Any alternatives you can think of?


r/PHPhelp • • Feb 11 '26

I uninstalled XAMPP and accidentally deleted something important from htdocs

0 Upvotes

I was having problems with XAMPP, so I decided to uninstall it and reinstall it later. However, I forgot that there was an important folder in htdocs that I hadn't backed up anywhere.

While uninstalling, I desperately tried to drag the folder to Documents, but it didn't work, it's nowhere to be found now, not even in the Recycle Bin. Is there any way to recover everything that was inside it?


r/PHPhelp • • Feb 09 '26

Multi line array formatting in php-cs-fixer

3 Upvotes

I was wondering if its possible with php-cs-fixer to handle formatting multi line arrays. I don't want all arrays to be multiline but if they are deformed I would like them to be formatted. So like the following:

// These are all malformed
$arr = [
    'one', 'two', 'three', 'four'];

$arr = [
    'one',
    'two', 'three', 'four'];

$arr = [
    'one', 'two',
    'three', 'four'];

$arr = [
    'one', 'two', 'three',
    'four'];

$arr = [
    'one', 'two',
    'three',
    'four'];

$arr = [ 'one', 'two', 'three', 'four',
];

// They all should be formatted to
$arr = [
    'one',
    'two',
    'three',
    'four',
];
 
// This should stay the same
$arr = [ 'one', 'two', 'three', 'four', ];

Unless there's a rule I'm missing this formatting doesn't happen. This leads to severely inconsistent code. Is my only course of action to write my own fixer? It's pretty annoying to have to import a custom fixer for every project.

This seems like something that should definitely be a feature of a code formatter. This is true in basically every formatter in every language. Even Intelephense does this but Intelephense is severely limited in its formatting options. I've seen some features brought up in their github for all arrays to be multi line but that seems like it would be too much because you should still have single line arrays. I just want malformed arrays to be formatted.

Any help would be appreciated.


r/PHPhelp • • Feb 09 '26

Migrating Laravel 9 → 12: API-only project, looking for tips from those who've done it

4 Upvotes

Hey fellas,

I'm planning to upgrade a production REST API from Laravel 9.52 / PHP 8.1 to Laravel 12. Dockerized, MySQL, uses ext-rdkafka (Kafka), ext-imagick, l5-swagger, doctrine/dbal. It's one of our microservices It's a small one.

Planned path: L9 → L10 → L11 → L12, upgrading PHP to 8.2 at the first step.

I've read through the official upgrade guides.

The L10 → L11 step looks like the hardest — especially the column ->change() behavior where you must re-specify ALL modifiers or they're silently dropped.

A few questions:

  1. Column ->change() in L11 — Did you rewrite old migrations or only worry about new ones going forward?
  2. l5-swagger — Anyone running it on L11 or L12? Which version works?
  3. Step-by-step vs skipping — Is there any real benefit to jumping L9→L11 directly, or is one-at-a-time safer?
  4. Laravel Shift — Worth it for a small API-only project, or is manual migration straightforward enough?
  5. Any non-obvious gotchas the upgrade guides don't emphasize enough?

Any other breaking changes ? am i missing somenthing ?

Thanks in advance.


r/PHPhelp • • Feb 08 '26

Solved I'm following along with Laracasts and my project stopped working after moving index.php to /public folder.

2 Upvotes

I'm following along with the Laracasts course on YouTube. Everything is working well so far. However, in Episode 30: Autoloading and Extraction, the host moves the index.php file to a public folder inside the project's root folder. In my case, it is /test_website_laracasts/public.

The host is using PHP Storm, an editor that handles routing largely on its own, without a dedicated server config file. Furthermore, the host modified the docroot using the following command when firing up the server: php -S localhost:8888 -t public.

However, I'm using XAMPP on Mac, not PHP Storm or even PHP's built-in server. After doing some research outside the course in previous episodes, I created an .htaccess file in the project's root, which has the following configuration and helped get routing to work properly:

RewriteEngine On
RewriteBase /test_website_laracasts/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

However, after moving index.php to public, the whole local site stopped working. Now every page returns a 404 error. And not even the 404 page that I created; it's XAMPP's default 404 page.

I truly have no idea how to change the docroot on Apache and would like some help on how to get the project working again. Here's the current structure of the project (before adding the public folder and moving index.php to it), which, again, is working perfectly fine and breaks only after moving index.php into the public folder:

test_website_laracasts/
├─ controllers/
│  ├─ notes/
│  │  ├─ create.php
│  │  ├─ index.php
│  │  ├─ show.php
│  ├─ about.php
│  ├─ contact.php
│  ├─ index.php
├─ views/
│  ├─ notes/
│  │  ├─ create.view.php
│  │  ├─ index.view.php
│  │  ├─ show.view.php
│  ├─ partials/
│  │  ├─ banner.php
│  │  ├─ footer.php
│  │  ├─ head.php
│  │  ├─ navbar.php
│  ├─ 403.php
│  ├─ 404.php
│  ├─ about.view.php
│  ├─ contact.view.php
│  ├─ index..view.php
├─ .gitignore
├─ .htaccess
├─ config.php
├─ Database.php
├─ function.php
├─ index.php
├─ Response.php
├─ router.php
├─ Validator.php

Do you know what I should do, which configurations I should change, to move index.php without breaking the entire site?

The rest of the episode contains instructions for how to rebuild connectivity with the rest of the pages, but that will seemingly never work without getting the Apache server to recognize the new docroot. Any help?

Note: Thanks for all the helpful replies. In the end, I moved the folder outside XAMPP and used PHP's built-in server. Since I couldn't use XAMPP's Apache or MySQL server outside its directories, I installed MySQL Community Server (for the MySQL server) and MySQL Workbench for the graphical interface. Then I modified all the router's routes to match the new URL structure (localhost:8888/...) and all the URLs in the site's various links and buttons.


r/PHPhelp • • Feb 08 '26

Symfony bootstrap template integration problems

2 Upvotes

Hello, I am relatively new to symfony but I know the basics and used it to make a small project before. However, I keep having difficulties when it comes to integrating bootstrap templates to symfony. The process is tedious and long as far I know, I followed a youtube tutorial and saw multiple articles yet something always seems to go wrong and some styles just don't work. Does anyone know how to do speed up the process? Or has a tool that makes the process easier? It's genuinely confusing and frustrating


r/PHPhelp • • Feb 09 '26

Dicas

0 Upvotes

Olá pessoal, estou começando no mundo da programação agora com a linguagem de php, fiz um curso de logica da programação e estou no php e vou começar a estudar html e css, alguém tem algum dica de estudo ou algum canal que ajudaria um novato?


r/PHPhelp • • Feb 07 '26

[Laragon/Win11] MySQL Connection Refused: Can't connect to 127.0.0.1 (10061)

0 Upvotes

Hoi allemaal,

Momenteel loop ik vast op een een MySQL-ding in Windows 11. Ik ben nog maar kort bezig met php, mysql en laragon en kom er via google even niet uit. Ik hoop dat iemand hier me er mee kan helpen. :-)

Ik krijg de melding: "Can't connect to MySQL server on '127.0.0.1' (10061)". Voorheen hielp een herstart van mijn pc en het opnieuw opstarten van Laragon, maar sinds vandaag werkt dit niet.

Setup: Local server: Laragon, Database tool: TablePlus, en Connectie-instellingen: Host: 127.0.0.1, Port: 3306, User: root, en geen password ingesteld.

Mijn PC heb ik al herstart. Idem voor Laragon 'Stop All' en daarna 'Start All' uitgevoerd. (meerdere keren). In de dashboard staat MySQL aangevinkt op poort 3306.

Er draaien voor zover ik weet geen andere programma’s die poort 3306 gebruiken (zoals Docker of een losse MySQL installatie). Het heeft verder voorheen een tijdje probleemloos gewerkt.

Heeft iemand een idee waar ik verder kan zoeken? Of kent iemand dit probleem?

Thanks!

Edit - Update:
I managed to fix the issue by restarting my computer after shutting it off completely.

Since then, I follow a specific order: I start the SQL service in Laragon first, then open TablePlus to establish the connection, and only then launch the localhost site.

Since I started using this sequence, I haven’t run into the problem again.


r/PHPhelp • • Feb 06 '26

Discussion Question

1 Upvotes

If someone came to you with a PHP-coded e-commerce website and asked you to update the entire codebase to make it into a modern, world-class, fast-speed, AI-enabled store, would you:

  1. keep the site running on PHP and make sure everything is up to date
  2. tell the client that building the site in a newer framework for e-comm would be better and pitch a new rebuild
  3. explain to the client that some store business scale will be impacted by continuing to run on PHP, but that it can scale for awhile until it breaks

r/PHPhelp • • Feb 06 '26

Oracle - Passing null to parameter #X of type string is deprecated

Thumbnail reddit.com
0 Upvotes

r/PHPhelp • • Feb 06 '26

Can someone help me with this data php code(i'm new to this)

0 Upvotes

<?php

$hostname = "localhost";

$username = "root";

$password = "";

$db = "mydatabase";

$dbconnect=mysqli_connect($hostname,$username,$password,$db);

if ($dbconnect->connect_error) {

die("Database connection failed: " . $dbconnect->connect_error);

}

if(isset($_POST['submit'])) {

$username=$_POST['username'];

$password=$_POST['password'];

$query = "INSERT INTO registration (username, password)

VALUES ('$username', '$password')";

if (!mysqli_query($dbconnect, $query)) {

die('An error occurred. Your review has not been submitted.');

} else {

echo "Thanks for your review.";

}

}

?>


r/PHPhelp • • Feb 04 '26

[Help Needed] Authenticating wp_remote_get() Requests with Amazon Cookies to Access Logged-In Content

1 Upvotes

I'm building a WordPress plugin that checks the status of Amazon Associates Creator Connections campaigns. The challenge is that Amazon only displays the "Creator Connections" badge (showing commission rates) when you're logged into your Amazon Associates account. Without authentication, I can't detect if a campaign is active or expired.

What I'm Trying to Achieve

Goal: Make authenticated requests to Amazon product pages to check if they display the "Creator Connections" badge.

Current Flow:

  1. User copies their Amazon Associates cookies from browser (via DevTools)
  2. Plugin stores cookies in WordPress database
  3. Plugin makes HTTP requests WITH those cookies
  4. Amazon should return the page WITH the SiteStripe toolbar showing "Creator Connections +10.00%commission|BRAND"

The Problem

Issue 1: Cookies Not Saving Properly

When users paste their Amazon cookies, I get "Failed to save cookies" errors.

Current Code:

php

public function ajax_save_amazon_cookies() {
    check_ajax_referer('asin_manager_nonce', 'nonce');
    
    $cookies = isset($_POST['cookies']) ? trim(stripslashes($_POST['cookies'])) : '';
    
    if (stripos($cookies, 'session-id') === false) {
        wp_send_json_error(array('message' => 'Invalid cookie format'));
        return;
    }
    
    $updated = update_option('asin_amazon_cookies', $cookies, false);
    
    if ($updated === false) {
        wp_send_json_error(array('message' => 'Failed to save cookies'));
    } else {
        wp_send_json_success(array('message' => 'Cookies saved!'));
    }
}

Cookie String Example:

session-id=137-9699179-7318147; lc-main=en_US; ubid-main=130-5856986-5488309; 
at-main=Atza|gQA17Mp7AwE...(very long); session-token=UJJmLFE486OXDnQ...(very long); 
ac-language-preference=en_US%2F%22%EF%BF%BD%EF%BF%BD... (contains encoded chars)

The cookie string is ~2500 characters and contains URL-encoded special characters (%EF%BF%BD, %2F, etc.).

Questions:

  • Is there a character limit in WordPress update_option()?
  • Could the special characters be causing issues?
  • Should I encode/escape the string before saving?

Issue 2: Authentication Not Working

Even when cookies do save, the authenticated requests don't seem to work.

Current Code:

php

public function ajax_check_campaign_status() {
    $campaigns = json_decode(stripslashes($_POST['campaigns']), true);
    $amazon_cookies = get_option('asin_amazon_cookies', '');
    
    foreach ($campaigns as $campaign) {
        $url = $campaign['url']; 
// e.g., https://amazon.com/dp/B0CH4NYL6J?campaignId=...
        
        $headers = array(
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language' => 'en-US,en;q=0.9',
        );
        
        if (!empty($amazon_cookies)) {
            $headers['Cookie'] = $amazon_cookies;
        }
        
        $response = wp_remote_get($url, array(
            'timeout' => 20,
            'redirection' => 10,
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'sslverify' => false,
            'headers' => $headers
        ));
        
        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            
            
// Check if "Creator Connections" badge is in the response
            $has_badge = stripos($body, 'Creator Connections') !== false;
            
            if ($has_badge) {
                
// Extract commission rate
                preg_match('/\+([0-9.]+)%\s*commission/', $body, $match);
                $commission = $match[1] ?? 'unknown';
            }
        }
    }
}

What happens:

  • Request succeeds (HTTP 200)
  • Body contains product page content
  • BUT "Creator Connections" text is NOT found in response
  • It's as if Amazon isn't recognizing the authentication

Questions:

  • Is wp_remote_get() properly sending Cookie headers?
  • Do I need to set additional headers (Referer, Origin, etc.)?
  • Could Amazon be rejecting server requests even with valid cookies?
  • Should I be using cookie jar functionality instead?

What I've Tried

Attempt 1: Using cURL Directly

php

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $amazon_cookies);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0...');
$response = curl_exec($ch);
curl_close($ch);

// Still doesn't contain "Creator Connections"

Attempt 2: Setting More Headers

php

$headers = array(
    'Cookie' => $amazon_cookies,
    'User-Agent' => 'Mozilla/5.0...',
    'Accept' => 'text/html,application/xhtml+xml',
    'Accept-Language' => 'en-US,en;q=0.9',
    'Accept-Encoding' => 'gzip, deflate',
    'Connection' => 'keep-alive',
    'Upgrade-Insecure-Requests' => '1',
    'Referer' => 'https://affiliate-program.amazon.com/',
    'Origin' => 'https://affiliate-program.amazon.com'
);

// Still doesn't work

Attempt 3: Testing Cookie Validity

I can confirm the cookies work in browser:

  1. Open DevTools → Application → Cookies
  2. Delete all amazon.com cookies
  3. Manually add the cookies from my string
  4. Refresh page
  5. ✅ I'm logged in and can see Creator Connections badge

So the cookies are valid, but PHP requests aren't using them correctly.

Technical Constraints

  • WordPress environment (can't use external libraries easily)
  • Need to check 200+ campaign URLs
  • Cookies expire after ~1 year or when user logs out
  • Must work with wp_remote_get() or cURL (WordPress standard functions)

Questions for r/PHPHelp

  1. Cookie Storage: Why might update_option() fail with a 2500-char string containing special characters? Is there a size limit or encoding issue?
  2. Cookie Headers: Am I correctly passing cookies via the Cookie header in wp_remote_get()? Should the format be exactly as copied from browser?
  3. Amazon Detection: Could Amazon be detecting server requests and serving different content even with valid cookies? Any way to bypass this?
  4. Alternative Approaches: Is there a better way to authenticate PHP requests with browser cookies? Should I be using sessions, cookie jars, or something else?
  5. Special Characters: The cookies contain characters like %EF%BF%BD and long base64-encoded tokens. Do these need special handling in PHP?

Debug Information

What I see in debug log:

Cookie string length: 2543
First 100 chars: session-id=137-9699179-7318147; lc-main=en_US; ...
Using saved Amazon cookies for authentication
Response status: 200
Response body length: 45234
Found "Add to Cart": YES
Found "Creator Connections": NO  ← This is the problem

Expected vs Actual:

WhenCreator Connections Found?
Browser (logged in)✅ YES - Badge visible
PHP request (with cookies)❌ NO - Badge not in HTML

Minimal Reproducible Example

php

<?php
// Step 1: Get cookies from browser
$cookies = 'session-id=137-9699179-7318147; at-main=Atza|...'; 
// Full cookie string

// Step 2: Save to database
update_option('test_cookies', $cookies);

// Step 3: Retrieve and use
$saved_cookies = get_option('test_cookies');
echo "Saved length: " . strlen($saved_cookies) . "\n";
echo "Original length: " . strlen($cookies) . "\n";
echo "Match: " . ($saved_cookies === $cookies ? 'YES' : 'NO') . "\n";

// Step 4: Make request
$response = wp_remote_get('https://www.amazon.com/dp/B0CH4NYL6J?campaignId=xyz', array(
    'headers' => array(
        'Cookie' => $saved_cookies,
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    )
));

$body = wp_remote_retrieve_body($response);
echo "Has 'Creator Connections': " . (stripos($body, 'Creator Connections') !== false ? 'YES' : 'NO');

Current Output:

Saved length: 2543
Original length: 2543
Match: YES
Has 'Creator Connections': NO

What Success Looks Like

If authentication works, I should find this in the response HTML:

html

Creator Connections
+10.00%commission|FLASHFORGE

This text appears in Amazon's SiteStripe toolbar when logged in as an Associate.

Environment

  • PHP 7.4+ / 8.0+
  • WordPress 6.0+
  • Using wp_remote_get() (WordPress HTTP API)
  • Alternative: Can use cURL if needed
  • Server: Standard shared hosting (LAMP stack)

Any Help Appreciated!

I've been stuck on this for days. Any insights on:

  • Why cookies might not save correctly
  • How to properly authenticate wp_remote_get() with browser cookies
  • Whether Amazon specifically blocks server requests
  • Alternative approaches to achieve authenticated scraping

Thank you in advance! 🙏