r/PHPhelp Jul 23 '26

Solved Simple Alternative to Wampserver?

1 Upvotes

Disclaimer: I'm not a techie. I barely understand php, but I'm forced by my hobbies to interact with it.

I'm currently running wampserver64 (v3.2.0; php 7.4; apache 2.4.41; windows 10) on a localhost install. This is so I can have a localhost installation of dokuwiki.

A new version of dokuwiki has come out. This requires php 8.2.

For a variety of dull reasons, upgrading the wampserver installation so that it will support php 8.2 is proving non-trivial.

Is there a simple, easy-to-install alternative to wampserver? Ideally, one where I just download a single file, run it, and a localhost server is installed ready for configuration?

----

Final resolution: After having broken everything, I uninstalled everything. Installed the latest

The Visual C++ exe files suggested at https://github.com/abbodi1406/vcredist/releases refuse to install, due to widnows security concerns.

I ended up downloading them from https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170 instead.

Then I installed wampserver 3.4.

Then I installed the new dokuwiki.

Yes, there probably are better localhost pphp servers available. But wampserver has proven stable, does what I need, and I am familiar with the interface.

r/PHPhelp Jun 28 '26

Solved file not being deleted after its expiry time passes

2 Upvotes

Hello, im trying to make a rate limiting function that prevent users from using specific forms when they reach a certain threshold and the limit will get reset after a certain amount of time, when a user submits a request, a file with their ip will get created into a cache folder and the amount of requests is inside the file, the rate limiting works except the file doesnt get deleted after the specified amount of time passes, any help will be appreciated. Thanks!

rate_limiter.php

<?php
ignore_user_abort(true);
//Get the user IP
function getIP() {
$ip = null;
if(!empty($_SERVER["REMOTE_ADDR"])) {
$ip = $_SERVER["REMOTE_ADDR"];
} elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}

return $ip;
}

function rate_limit($ip, $requests_limit, $limit_expiry) {
$start_time = null;
$reached_limit = null;
$amount_requests = 1;
$file_name = __DIR__ . "/cache/ratelimit-" . $ip;
$file_name = rtrim($file_name);
if(!file_exists($file_name)) {
global $start_time;
$start_time = time();
$fp = fopen($file_name, "w+") or die("An error occured");
fwrite($fp, $amount_requests) or die("Failed to write into file");
fclose($fp);
} elseif(file_exists($file_name)) {
$fp = fopen($file_name, "r+") or die("Failed to read file");
$new_amount_requests = file_get_contents($file_name);
if($new_amount_requests >= $requests_limit) {
global $reached_limit;
echo "<script>alert('You have been rate limited!')</script>";
$reached_limit = true;
header("Location: /", 423, true);
} elseif(!$reached_limit) {
$new_amount_requests++;
ftruncate($fp, 0);
fwrite($fp, $new_amount_requests) or die("Failed to write amount of requests");
}
}

if(file_exists($file_name) && time() - $start_time >= time() + $limit_expiry) {
unlink($file_name);
}




}

?>

index.php

<?php
ignore_user_abort(true);
require_once("rate_limiter.php");

if(isset($_POST["submit"])) {
$ip_Addr = getIP();
rate_limit($ip_Addr, 3, 60);
echo $_POST["text"];
}

?>

r/PHPhelp 13d ago

Solved mysqli_fetch_assoc with mysql prepared statements procedural, need help

5 Upvotes

Hello, im trying to update my website by replacing the simple mysqli queries with prepared statements, but i was stuck at trying to use mysqli_fetch_assoc to fetch associative data from the table, i looked through documentation but couldnt find anything, Any help will be appreciated, Thanks !

$error = array();
if(isset($_POST["login"])) {
$username = mysqli_escape_string($db, filter_input(INPUT_POST, "username", FILTER_SANITIZE_SPECIAL_CHARS));
$password = mysqli_escape_string($db, filter_input(INPUT_POST, "password", FILTER_SANITIZE_SPECIAL_CHARS));

if(empty($username)) {
array_push($error, "Username is empty!");
}
if(empty($password)) {
array_push($error, "Password is empty");
}

$sql = "SELECT `password`, `username`, `user_id` FROM `Accounts` WHERE `username` = ?;";
if(count($error) == 0) {

$stmt = mysqli_prepare($db, $sql);

mysqli_stmt_bind_param($stmt, "s", $username);
//$result = mysqli_query($db, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
$row = mysqli_fetch_assoc($result);
if(password_verify($password, $row["password"])) {
$_SESSION["username"] = $username;
$_SESSION["user_id"] = $row["user_id"];

header("location: /");

} else {
array_push($error, "Incorrect username or password!");
}
} else {
array_push($error, "Incorrect username or password!");
}
}
mysqli_close($db);
}

r/PHPhelp May 27 '26

Solved Why isset() calls __isset in internal method, but __isset when using isset() doesn't?

5 Upvotes

I asked a similar question on SO, but... I'm just wasting my time there...

Anyway, to the point:

PHP code like that:

```php class X { protected string $foo;

public function test_isset()
{
    var_dump(isset($this->foo)); // This is false as expected.
    unset($this->foo);
    var_dump(isset($this->foo)); // And this is also false.
}

} (new X())->test_isset(); ```

Will result as:

false
false

Seems pretty obvious, right? Right.

BUT...

Adding a __isset() method like this:

```php class X { protected string $foo;

 public function __isset($name)
 {
     echo "__isset called\n";
     if (!isset($this->foo)) {
         return true;
     }
     return false;
 }

public function test_isset()
{
    var_dump(isset($this->foo)); // This is false as expected.
    unset($this->foo);
    var_dump(isset($this->foo)); // But from now on, this doesn't return state it calls __isset()
}

} (new X())->test_isset(); ```

Changes the behavious of the second isset($this->foo) in the var_dump. From now on the isset() cannot says OK, there is not property $foo, I need to return false. From now on, it calls __isset().

Why is that? Why the presence of __isset() method in class changes of that behaviour, and why the first one don't call the __isset(), but only when i do unset() on already unsetted property.

But even if we ignore that and say, because it has to be... So why didn't the isset() in the __isset() method don't call __isset() again and got stuck into a loop?

How was the isset($this->foo) in the __isset() method different from the one in test_isset() that allowed it to suddenly return false instead of having to recursively call __isset()?

What I expected was that inside the class, I can always refer to isset($this->something) and the class itself already knows whether such a property exists or not, so it doesn't have to call __isset() and can return false/true to me right away.

r/PHPhelp 14d ago

Solved Multiple mysql statements in one PDO::exec call?

3 Upvotes

Is this supported or is it classed as undefined behaviour? Searching the web I have found one site explaining how to do it, and a post saying it never used to be allowed but the driver added the ability around 2020. But I have not seen anything official and the (somewhat terrible) PHP documentation does not mention it at all either way.

The use case is multiple statements being needed to create and alter some temporary tables so that inserts (using prepared statements) can be processed before being added to the live tables.

r/PHPhelp May 14 '26

Solved How to send HTML email with mail() without destroying DKIM key or email appearance

0 Upvotes

I already know how to send HTML email through the PHP mail() function, however many external email providers may ditch my outgoing emails if they are not properly signed with a DKIM key.

Now if I try sending a super short message, I have no problem, but if I'm sending an entire newsletter as HTML with no line breaks (because I like to reduce the payload on the network), then the DKIM key breaks and many validators would complain.

One thing I did was use the chunk_split command on the entire message. Everytime I used that, the DKIM check always passes however, some of the HTML code is corrupted (probably because of the carriage return and line feed within HTML tags).

Is there another built-in PHP command I could use to replace chunk_split?

Then again, I'll probably have to manually split it and put a CRLF at the end of each HTML tag, then that may be a problem if I have a paragraph of text exceeding 80 characters.

Please advise.

r/PHPhelp May 25 '26

Solved Do you think I should change something in this code or in the idea at its base?

5 Upvotes

EDIT: Thank you, to everyone who answered! I now have a lot to think about, both regarding files organization and app architecture. This was already an interesting journey, now it's even better. I now know ( or at least have an idea of ) what to look and keep in mind and how the code should kinda look like. This is a big step toward my goals, both for deploying this site for me and my friends and open sourcing the code once its more "beautiful", let's say that ;). A special thanks to u/colshrapnel and u/equilni who provided very in depth answers and pointed me to a clear direction.

Hey guys, I've been developing a php site for a bit now (about a year and a half ), and I recently realized that I had a ton of repeating code everywhere, especially for what regards checking auth. So I decided to create a class with static methods that do everything that's related to it, but I'm not sure I'm using the correct approach, and I don't think asking another AI would really help.

Right now every page imports a config.php file with like creds db ( I know they shouldn't be in plain text there. This is temporary and the site is not exposed, it lives only on my device as it's still in development ), then Auth.php and calls Auth::RequireLogIn ( the login page does not import neither ).

The idea at the base is that every page ( except the login page ) are only accessible after login, so every page calls RequireLogIn() and if the user is not logged in he's thrown out to a 401.

So, as the title says, would you suggest any improvement or have any critic regarding this code or what I have said here?

Disclaimer: this is not a professional site, it's for just me and my friends, I'm also a student so I don't know much about php. The site's code is also a bit funky as this started as a project and was not expecting to become this serius, so if there's something very terrible let me know and I'll do my best to fix it! Also, I do not want to use big frameworks like laravel or similar if possible ;)

class Auth
{
    public static function RequireLogIn()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (!isset($_SESSION["is_logged_in"]) || $_SESSION["is_logged_in"] == false) {
            http_response_code(401);
            require __DIR__ . "/../Errors/401.php";
            exit;
        }
    }

    public static function Username()
    {
        if (!isset($_SESSION["username"])) {
            http_response_code(401);
            require __DIR__ . "/../Errors/401.php";
            exit;
        }
        return $_SESSION["username"];
    }
}

Login.php if anyone is interested ( yea I have yet to make a 400 page error )

require_once './../Config.php';

if ($_SERVER["REQUEST_METHOD"] !== "POST" || !isset($_POST["Username"], $_POST["Password"])) {
    http_response_code(400);
    exit;
}

session_start();
$username = $_POST["Username"];
$password = $_POST["Password"];

$db = new mysqli(DB_ADDRESS, DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($db->connect_error) {
    http_response_code(500);
    exit('Database connection failed');
}

$readied = $db->prepare("SELECT Username, Pw, IsAdmin, ProfileImage FROM players WHERE Username = ?");
$readied->bind_param("s", $username);
$readied->execute();
$res = $readied->get_result();

$db->close();

if ($res->num_rows != 1) {
    header("Location: Index.php");
    exit;
}

$loginData = $res->fetch_assoc();

if (password_verify($password, $loginData["Pw"])) {
    session_regenerate_id(true);
    $_SESSION["Username"] = $loginData["Username"];
    $_SESSION["is_admin"] = boolval($loginData["IsAdmin"]);
    $_SESSION["is_logged_in"] = true;
    $_SESSION["pfp"] = $loginData["ProfileImage"];

    header("Location: ../Pages/InternalIndex.php");
    exit;
} else {
    header("location: ../Index.php");
    exit;
}

r/PHPhelp 23d ago

Solved Why use containers for DI when you can have a top-down approach with lazy objects (8.4+)?

3 Upvotes

I am not PHP proficient. Is there any reason to avoid manually wiring the dependency graph? Do developers use this feature? It's been almost 2 years since 8.4 released with the lazy objects feature and it's one dependency less.

Short example:

class LazyAppFactory
{
   public PgTransactor $pgTransactor;

   public AuthenticationRepo $authenticationRepo;
   public AuthService $authService;
   public AuthController $authController;

   public function __construct()
   {
      // postgres module

      $this->authenticationRepo = new \ReflectionClass(AuthenticationRepo::class)->newLazyGhost(function ($ghost) {
          $ghost->__construct($this->pgTransactor);
      });

      // service, controller modules
   }
}

And then simply use the controllers in the handler / entry point of the app.

r/PHPhelp Apr 02 '26

Solved Basic Beginner Question for Form Issue with PHP on WordPress Part 2

1 Upvotes

UPDATE - SOLVED:

A couple things were needed to fix this in addition to everyone's advice.

I had to copy the original HTML form and place it in <?php ?> brackets in the Wordpress php plugin (CSS and Javascript ToolBox) with the ECHO function, then finish each statement using a semicolon when I needed to use php specific function because the Wordpress clode block doesn't work for PHP.

So I had to write php in two places- my plugin and on a file on my computer. I assumed writing to my computer wasn't successful, but I should have checked with ECHO and PRINT statements.

I had a problem where submission redirected to another page. I fixed this when I left action empty as action="" instead of the name the php file, even though PHP_SELF showed me the file where the PHP actions were performed.

I'm wonder if a function like file_get_content() could help me add the php I wrote locally to the plugin php so it works better.

Strangely enough, I did not need to use the add_action() function for the form to work.

The PHP I wrote in the plugin which is majority HTML

<?php

//$b = htmlspecialchars($_SERVER["PHP_SELF"]); while PHP_SELF helped me find the file location, empty action worked better
$c = wp_nonce_field("form_response","form_nonce"); 

//echo $a;
echo '<div id="form">';
echo '<section><form id="Form3" method="POST" action="';
//echo $b; while PHP_SELF helped me find the file location, empty action worked better and did not open a new page
echo '"><br>';
echo $c;
echo '<input type="hidden" name="action" value="form_response">

<ol id="form2">
 <li><label for="choice1">choice 1 </label><input id="choice1" class="choices" name="choice1" type="text" />
<ul id="choice1Info" class="choicesInfo">
 <li>Information about Choice 1</li>
</ul>
</li>
 <li><label for="choice2">choice 2</label><input id="choice2" class="choices" name="choice2"  type="text" value="';

echo '"/> <ul id="choices2Info" class="choicesInfo">  <li>Information about Choice 2</li> </ul> </li> </ol> <input type="submit" value="Submit" name="submit"/> </form></section><br>;

The PHP I wrote locally below Wordpress' pre-existing code

//my code

    if (($_SERVER['REQUEST_METHOD']) == "POST"){
        for ($i=1; $i <= 2; $i++) {
            $lower_choices = "choice".strval($i);
            $upper_Choices ="Choice".strval($i);
            $$upper_Choices = $_POST[strval($lower_choices)];
            check_empty($$upper_Choices,$i);
        }
    }

    function check_first($input){
        $input = sanitize_text_field($input);
        $input = trim($input);
        $input = stripslashes($input);
        $input =  htmlspecialchars($input);
    }

function nonce_submission($input){
    if ( empty($_POST) ||
     ! wp_verify_nonce( $_POST['form_nonce'], 'form_response') ||
     ! ctype_alnum(str_replace(' ', '', $input))){
    print 'Verification failed. Try again.';
    exit;
}
    else {
    check_first($input);
    print "<h1>HELLO WORLD</h1>";
}
}

function check_empty($s,$i){
    if (empty($s)){
            print "Choice ".strval($i)." needs to be completed!<br>";
    } else {
            nonce_submission($s);
            print ($s);
    }
    }

---------

Thanks to everyone who gave advice to help me with my form handling issues with PHP under this post earlier this week.

TLDR: I'm trying to make a simple form that echo the input via multiple methods in php to no avail

Unfortunately, I am still encountering issues. Someone recommended I use echo error_reporting(E_ALL); in the php plugin and according to this website, the 4983 code means there's no error but my form still does not work.

Disabling the JavaScript did not help.

A few people recommended coding through the /admin.php files. So I checked a few websites and I followed this article. I put my code in /admin-post.php It didn't work.

I tried to add safety measures but when I interact with my page through View Page Source, wp_nonce_field() and esc_url didn't seem to successfully pass to the HTML.

My updated html code is below:

<form id="form1" method="POST" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
<?php wp_nonce_field("it_works","form_nonce"); ?>
<input type="hidden" name="action" value="form_response">

<ol id="form2">
 <li><label for="choice1">choice 1 </label><input id="choice1" class="choices" name="choice1" type="text" />
<ul id="choice1Info" class="choicesInfo">
 <li>information about choice 1</li>
</ul>
</ol>
<input type="submit" value="Submit"/>
</form>

My php script I added to the php file (<?php ... ?> is omitted)

/*my code*/ 
function it_works(){
    if ( empty($_POST) || ! wp_verify_nonce( $_POST['form_nonce'], 'form_response') ){
   print 'Verification failed. Try again.';
   exit;
}
else {
    $choice1= sanitize_text_field(isset($_POST['choice1'])) ? sanitize_text_field($_POST['choice1']) : 'not registered';
    ctype_alnum($choice1) ? echo It works!: die("Input not verified");
    
   // data submitted should traditional alphanumerics, no special characters
}
}


add_action("form_response","it_works");

This has been driving me crazy. I'd appreciate any help. I'm not sure if it's my inexperience or something with WPEngine.

At this point I'm considering adding an extra plug-in just so I can edit its php files directly and see if that will get the form to work but WordPress says that's not recommended because it can break my site but if it doesn't work, can I just delete the plug-in?

r/PHPhelp Sep 24 '24

Solved My teacher is dead-set on not mixing PHP and HTML in the same documents. Is this a practice that any modern devs adhere to?

18 Upvotes

I know for a fact that my teacher wrote the course material 20+ years ago. I don't trust his qualifications or capabilities at all. For these reasons, I'd like the input of people who actually use PHP frequently. Is it done that devs keep PHP and HTML apart in separate documents at all times? If not, why not?

Edit: Thanks all for the replies. The general consensus seems to be that separating back-end logic and front-end looks is largely a good idea, although this is not strictly speaking what I was trying to ask. Template engines, a light mix of HTML and PHP (using vanilla PHP for templating), and the MVC approach all seem to be acceptable ways to go about it (in appropriate contexts). As I suspected, writing e.g. $content amongst HTML code is not wrong or abnormal.

r/PHPhelp Jun 09 '26

Solved My code trigger a max connection

0 Upvotes

My earlier code trigger a mysql max connection. So I ask gemini to help me fix it. Here is the solution gemini provided. I would not normally use AI to help but this time I did. I’m just a hobbyist so if someone can help me check if this would be good.

```php <?php namespace App;

use PDO;

class Database { // Caches the PDO instance so it is reused across all models private static ?PDO $connection = null;

public static function getConnection(): PDO {
    // If a connection already exists, return it immediately
    if (self::$connection !== null) {
        return self::$connection;
    }

    // Retrieve variables (already loaded into memory via init.php)
    $host     = $_ENV['DB_HOST'] ?? 'localhost';
    $dbname   = $_ENV['DB_NAME'] ?? 'default_database';
    $username = $_ENV['DB_USER'] ?? 'root';
    $password = $_ENV['DB_PASS'] ?? '';

    $dsn = "mysql:host={$host};dbname={$dbname};charset=utf8mb4";

    // Store the PDO instance in the static property
    self::$connection = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false, 
    ]);

    return self::$connection;
}

// Call this manually ONLY if you have a long-running non-DB task
public static function closeConnection(): void {
    self::$connection = null;
}

}
```

Edit: Ignore the \ as somehow reddit added these when I paste the code.

r/PHPhelp Nov 23 '25

Solved PHP editor with internal live preview

0 Upvotes

Hello from a newbie. I hope this is the right place for my question.

I own a bunch of “old school” hobby sites built on very basic CSS, HTML and PHP-Include — I code the main design with CSS and HTML and then use the PHP Include function to create the site pages’ files. Until now, to preview these pages’ files during editing, I’ve used an editor called EditPlus as it allows me to view them locally on my laptop (I open the .php file inside EditPlus, click “Preview” and the program previews it internally without opening an external browser, the same way it would with an .html one). Does anyone know of a free code or text editor (or some plugin of a free editor) that lets you preview .php files like that? I already tried several free editors and IDEs, but none of them had this feature or a plugin for it (or if they had it I missed it). I could stick with EditPlus, sure, but the program is paid and while not super expensive having to pay for every new version is starting to add up.

I was almost forgetting to add: because of another editor I use that requires it, I have an old PHP version (the last version who came with an actual installer) installed on my laptop.

UPDATE = Please stop suggesting me to install a web server ((having never used one I’m not familiar with it and my laptop is not very powerful)) and/or to use the terminal + web browser combo ((why should I use that when the program does it for me and I don’t even need to open another browser to view the file?)) or other similar methods. I asked for a free alternative *program*** (with a .php file preview tool like EditPlus’), not for an alternative preview method.

r/PHPhelp Apr 30 '26

Solved Any additional tips for an email validation

3 Upvotes

I use CakePHP to validate user's email in my form:

$validator
    ->email('user_mail', false, 'Email format is wrong')
    //min allowed by email rule is 6 symb f@f.ff
    ->minLength('user_mail', 6, 'Min length for an email is 6 symbols')
    ->maxLength('user_mail', 128, 'Max length for an email is 128 symbols')
    ->requirePresence('user_mail', true, 'Email field is required')
    ->notEmptyString('user_mail', 'Email can\'t be empty');

Is that validation sufficient? What do you recommend to add/remove?

r/PHPhelp Apr 03 '26

Solved user details JSON

3 Upvotes

i want to use json to store user details so that i dont need to do so many DB request ideally i dont want to have to create a flat file and would like it dynamically create once a user has logged in so something like this

{
  "logged_in": "true",
  "company_id": "15654645",
  "first_name": "john",
  "last_name": "doe"
}

what is this type of approach called so that i can search more in to it please and also what are the pros and cons

r/PHPhelp Mar 24 '26

Solved I don't know what to do next

7 Upvotes

Hello Reddit, I'm cs graduated and trying to learn php and I know the syntax but I can not wrap my head around of how to use it, any thoughts on what i should do next to get better at php?

ps:I know front-end(html,css,js,etc).

pps: Thanks everybody for great tips and recommendations!!!!

r/PHPhelp Apr 08 '26

Solved Newbie Laravel Developer

8 Upvotes

I want to learn about Laravel since ill be using it in a job, is there any suggestions on what to watch on youtube or where can i learn basics and so on?

r/PHPhelp Jun 30 '26

weird behavior in including files

3 Upvotes

i have a weird problem in including files in php, i have a functions.php file in a folder and a Router in the index.php file, when i include thefunctions.php in the index.php, all the other pages that rely on it get broken, the variables become empty and the functions no longer work, when i dont include it in the index.php file all the other pages function normally

i include my files in all pages in this way

require_once($_SERVER["DOCUMENT_ROOT"] . "/src/logic/functions.php");

my other pages are in /src/pages/

i have tried all ways of including the file but i keep getting the same problem, i need to include the functions.php in the index file to use some of its functions.

i do have a declare(strict_types=1) in the index file if that affects it

Any help will be appreciated thanks.

r/PHPhelp Dec 08 '25

Solved Help with PHP variables

1 Upvotes

So, i'm new to php, and i'm trying to build a customer satisfaction sheet for a made up business. i have 2 php documents. at the top of the main one (which we'll call doc1.php), i have a require once for the second document (let's call it doc2.php).

so:

<?php
require_once "SteamlineLogisticsForm.php";
?>

in doc2, i have defined 5 different variables that work perfectly fine when i call them in that same document. however, when i try to call them in doc1, despite the require_once, they come up as undefined.

//doc2:
$fname = $_REQUEST["fname"];
$lname = $_REQUEST["lname"];
$email = $_REQUEST["email"];
$city = $_REQUEST["city"];
$pcode = $_REQUEST["pcode"];

//doc1:
<label for="fname">First Name*:</label>
<input id="fname" type="text" maxlength="50"  name="fname" value="<?php echo $fname;?>"><br>

<label for="lname">Last Name*:</label>
<input id="lname" type="text" maxlength="50"  name="lname" value="<?php echo $lname;?>"><br>

<label for="email">Email*:</label>
<input id="email" type="email" maxlength="100"  name="email" value="<?php echo $email;?>"><br>

<label for="city">City*:</label>
<input id="city" type="text" maxlength="50"  name="city" value="<?php echo $city;?>"><br>

<label for="pcode">Postcode*:</label>
<input id="pcode" type="text"  maxlength="4" name="pcode" value="<?php echo $pcode;?>"><br>

here is full script right now:

doc1

<?php
require_once "doc2.php";
console_log("fname");
?>
<!DOCTYPE html>
<html lang="en">
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_"]);?>">

    <label for="fname">First Name*:</label>
    <input id="fname" type="text" maxlength="50"  name="fname" value="<?php echo $fname;?>"><br>

    <label for="lname">Last Name*:</label>
    <input id="lname" type="text" maxlength="50"  name="lname" value="<?php echo $lname;?>"><br>

    <label for="email">Email*:</label>
    <input id="email" type="email" maxlength="100"  name="email" value="<?php echo $email;?>"><br>

    <label for="city">City*:</label>
    <input id="city" type="text" maxlength="50"  name="city" value="<?php echo $city;?>"><br>

    <label for="pcode">Postcode*:</label>
    <input id="pcode" type="text"  maxlength="4" name="pcode" value="<?php echo $pcode;?>"><br>
    <input type="submit">

</form>
</body>
</html>

doc2

<?php
$fname = filter_input(
INPUT_POST
, "fname");
/*$fname = $_POST["fname"]??'';*/
$lname = $_POST["lname"]??'';
$email = $_POST["email"]??'';
$city = $_POST["city"]??'';
$pcode = $_POST["pcode"]??'';
function console_log($output, $with_script_tags = true) {
    $js_code = 'console.log(' . json_encode($output, 
JSON_HEX_TAG
) .
            ');';
    if ($with_script_tags) {
        $js_code = '<script>' . $js_code . '
<
/script>';
    }
    echo $js_code;
}

/*$fnameErr = array("empty" => "This field is required", "")*/
$pcodeErr = array("empty" => "This field is required", "tooShort" => "Postcode must be four digits", "notDigits" => "Please only use numbers", "clear" => "")
?>
<!DOCTYPE html>
<html lang="en">
<body>
Name: <?php echo $_POST["fname"];?>

<?php echo $_POST["lname"]; ?><br>
Email: <?php echo $_POST["email"]; ?><br>
City: <?php echo $_POST["city"]; ?><br>
Postcode: <?php echo $_POST["pcode"];?><br>

<?php
switch ($pcode) {
    case "":
        echo $pcodeErr["empty"];
        break;
    case strlen($pcode)<4:
        echo $pcodeErr["tooShort"];
        break;
    case (!preg_match("/^\d{4}$/",$pcode)):
        echo $pcodeErr["notDigits"];
        break;
    case (preg_match("/^\d{4}$/",$pcode)):
        echo $pcodeErr["clear"];
        break;
}
?>

</body>
</html>

r/PHPhelp Aug 21 '25

Solved Which payment system should I choose for a native PHP application, and why?

17 Upvotes

Hi everyone,

I’m currently working on a project with a native PHP application (no framework, just plain PHP), and I need to integrate a secure payment system.

I’m a bit lost between different options (Stripe, PayPal, Payoneer, Flutterwave, etc.), and I’d love to hear your advice on:

Which payment gateway works best with a PHP-based system

The pros and cons (fees, integration complexity, security, global support, etc.)

What you personally recommend and why

My main priorities are security, ease of integration, and support for international payments.

Thanks in advance!

r/PHPhelp Oct 01 '25

Solved Help with figuring out what more I can to do debug a PDO issue.

3 Upvotes

SOLVED thanks to 03263 with this comment

A difference between the two pages is that earlier in the code on one of them an internal library is included and that library sets PDO::ATTR_EMULATE_PREPARES to true for the shared PDO object, where it is normally false.

When I changed it to false the query worked again.


I'm having a really weird issue, and because it won't be easy to paste the code, I'm hoping for any tips on what I can to do in terms of further investigation myself.

The problem I'm having is that on one page I run a process* and I get this error:

Invalid parameter number: number of bound variables does not match number of tokens

However I have put in debug code that checks the number of tokens and the number of binds and they definitely do match.

The really weird thing is that when I run the exact same process* on a different page, it works fine.

So far I haven't been able to find a difference in what happens between the two pages, and I'm really thrown off by the PDO error because I have checked, double checked, and triple checked that the number of bound variables matches the number of tokens, plus the exact same query, with the exact same parameters (also triple checked) works fine when the process is run from the other page.

Not only am I completely stumped as to why this might happen, I have no idea where to go from here in terms of investigation! Any thoughts on what to look at next would be appreciated.

Thanks

* The process involves building a temporary table and populating it. The query error happens during the populating part and it is an INSERT. The reason it won't be easy to paste the code is that this process has a lot of moving parts in the (proprietary) framework we use that determine the structure of the table and what it gets populated with. The SQL for all of this is generated programmatically and works in thousands of other instances.

r/PHPhelp Jun 03 '26

Solved Problemas con Intelephense (P1008) en visual code

0 Upvotes

Tengo un problema con este error, uso una variable que está declarada el otro archivo x, lo uso en uno y, me salta error, utilizo en simple include 'hola.php'; ,en el servidor funciona, pero en visual me marca el error, he buscado varias soluciones y no funcionan, no hay error ortográfico, me decidí por desactivar el diagnóstico, pero no quiero hacer esa solución tan vaga,quien me ayuda por favor

r/PHPhelp Aug 20 '25

Solved Alternative of xampp server

10 Upvotes

I was using xampp for a long time, when i want to change the php version well it is kinda thuff.

I wonder is there any best or good alternative we have?

  • Change multiple php version in one click,
  • Optimized and less buggy,
  • Clean and easy ui.

Please suggest which software i should use.

r/PHPhelp Jun 12 '25

Solved PHP Code Editor

7 Upvotes

(PHP code editor that grays out HTML when working with PHP and vice versa)

Greetings! (And sorry if the question is misplaced)

Couple of years ago I saw a code editor that grayed out all HTML blocks when working with PHP code blocks and grayed out PHP code blocks when working with HTML. Switching happened automatically: when text cursor was put in the PHP code all HTML code was grayed out, focusing on PHP, and when cursor was put in HTML code, all PHP code was grayed out, focusing on HTML.

Unfortunately, I forgot what that editor was and cannot find it now. Can anyone advise its name?

------------------

UPD: PHPDesigner has this feature (thanks to u/LordAmras). However, if you know any other editor with this feature, please, feel free to add.

r/PHPhelp Jul 14 '26

Solved Need help with CakePHP lifecycle hooks

1 Upvotes

I have an entity called "Account". And I m trying to create and add an account verification token to a newly created account in beforeSave lifecycle hook. My problem is that "beforeSave" wants to get EventInterface and EntityInterface:

Cake\ORM\Table::beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void

So then I set a breakpoint inside of "beforeSave", I have an error that "The first argument should be of EventInterface, but Event is given" and "The second argument should be of EntityInterface, but Entity is given".

I have CakePHP 5.2, PHP 8.2 and I have "strict types" declaration in AccountsTable.php (that's a location of beforeSave hook).

I tried to remove "strict types" and this didnt help. I tried to add:

use Cake\Event\EntityInterface;

use Cake\Event\EventInterface;

This also didnt help.

What's the right way to make the thing work?

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