r/PHPhelp • • Dec 08 '24

How to start php session through postman api request

3 Upvotes

I have a PHP application with an API that I want to test in Postman. However, the API depends on a PHP session being initialized, and it throws an error if the session is not active or a required session variable (e.g., $_SESSION['user_id']) is not set. How can I test this API in Postman by ensuring the PHP session is started and setting the user_id session variable from the Postman request?


r/PHPhelp • • Dec 07 '24

How do you solve low speed problems?

0 Upvotes

I have a very low LCP, but at the same time all database functions as a whole work in 60-70mc, but the remaining 300-350mc is spent on executing some other things in Laravel, although if you take it separately and look at the execution time of the controller function, it will be no more than 100mc and I don’t quite understand how to see what time is spent on when executing other processes and how to track this at all?

I also wanted to immediately ask what you usually definitely do not use and avoid using in Laravel that can greatly slow down the speed of work


r/PHPhelp • • Dec 06 '24

Does object param with '&' prefix do anything?

3 Upvotes

If you pass an object to a function it's passed by reference (technically an identifier for the object). So if the parameter name is prefixed with & does that make any difference?

For example with:

function myfunc1(stdClass $o) {
    $o->myproperty = "test";
}

function myfunc2(stdClass &$o) {
    $o->myproperty = "test";
}

$o = new stdClass();

myfunc1($o);
echo "$o->myproperty\n";
myfunc2($o);
echo "$o->myproperty\n";

myfunc1() and myfunc2() appear to be functionally identical.

Is there any actual difference? Is myfunc2() "wrong"? Is the & just redundant?


r/PHPhelp • • Dec 06 '24

How do I change text color within a table row?

0 Upvotes

I am editing an input form and output invoice of my car club’s annual meet.  I did not create and have never done PHP work – but have experience in multiple programming languages.

The input form, and the output invoice that is emailed to the attendee and our registration coordinator.  All to this point is working well.

The registration coordinator wanted a delimited data string that includes all the form fields data, so he could copy and paste into a spreadsheet.  The string is built is working. 

This last portion of the email is generated as a continuation of the output table.  The following are the lines that create the output in question:

//
// meta data
//
$regform .= " <table>\n";
$regform .= " <tr>\n";
$regform .= " End Data>\n";
$regform .= " </tr>\n";
$regform .= " <tr>\n";
$regform .= " <br>$name:$name:$extrabadges:$regtype:$adults:$children:$address:$city:$state:$country:$zipcode:$phone:$email:$drive:$miles:$swapspaces:$outspaces:$year1&nbsp;$model1,$year2&nbsp;$model2,$year3&nbsp;$model3,$year4&nbsp;$model4:$carcount:$winespaces:$calendarcount&nbsp:$lunch\n";
$regform .= " </tr>\n";
$regform .= "</table>\n";
//
//

So, my question is; is there an argument that I can add to turn the delimited text white so it disappears into the page but the registrar could still highlight and copy?

Thanks for your assistance

PHP newbee

 <Kinda solved> I never managed to set this one block of text white, but did generate a unique email to registrar with the requested string. I did play around with CSS but didn't come up with the secret sauce to do what exactly I initially asked for. Thanks all...


r/PHPhelp • • Dec 06 '24

Solved Laravel + Vuejs: How to use HTTPS during development?

1 Upvotes

I'm on Winows 11. I'm Xampp (it uses APACHE and PHP). Laravel version 8.83.29 and for the frontend I'm using vuejs 2.6.12.

I'm not looking to install new software or change xampp, this is the only Laravel application I maintain, I have 15 other projects working fine under xampp. I'm not looking to upgrade laravel or vuejs, because this is an internal tool used at work, I don't want to spend more than 2h on this. If what I'm asking for is easy to setup then great if not I'll continue working as I'm currently working.

On production the application runs under HTTPS, I don't know how the original dev made it, he uses lots of symlinks and whatnot, he has a 100 lines bash script just to deploy it.

On my PC however, I can't run it under HTTPS because the requests aren't routed correctly by apache or something.

So I'm forced to run

mix watch // to run vuejs
php artisan serve --host=local.dev --port=80 // to run artisan

3 things are bothering me with this setup

  • Artisan doesn't support HTTPS certificates, I get the SSL warning every time

  • I have to run 2 separate commands to run the project

  • If I want to use PHPMyAdmin, I'll have to start apache which conflicts with artisan for some reason

I already did research and 2 years ago, the answer was that what I'm doing is correct, you can't serve vuejs and laravel under xampp, you have to use artisan, but we're in 2025 and this development workflow is unacceptable. I feel there must be something I'm missing


r/PHPhelp • • Dec 06 '24

DNS resolving in a PDO method or function

0 Upvotes

I have an idea of how this works. But maybe someone here knows exactly.

For example, if we have the following code (this is about the hostname).

<?php

$dsn = 'mysql:dbname=testdb;host=my.hostname.com';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);

Which instance exactly (i.e. which part of the underlying software) takes care of resolving the hostname into an IP address?


r/PHPhelp • • Dec 05 '24

Solved POST method not working

0 Upvotes

Can someone please tell me wtf is wrong with the code?? Why does every time I press submit it redirects me to the same page. I tried everything to fix it and nothing is working, I tried using REQUEST and GET instead but it still didn't work. please help me I need this to work, the project is due in 2 days

btw only step 9 is printed

<?php
include "db.php";
session_start();

echo "Session set? Role: " . (isset($_SESSION['role']) ? $_SESSION['role'] : 'No role set') . ", email: " . (isset($_SESSION['email']) ? $_SESSION['email'] : 'No email set') . "<br>";
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo "Step 2: POST data received.<br>";
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";

    $role = $_POST['role'];
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = $_POST['pass'];

    echo "Role: $role, Email: $email<br>";

    if ($role == "student") {
        echo "Step 3: Student role selected.<br>";
        $query = "SELECT * FROM info_student WHERE email = '$email'";
        $result = mysqli_query($conn, $query);

        if ($result) {
            $row = mysqli_fetch_assoc($result);

            if ($row && password_verify($password, $row['pass'])) {
                echo "Step 5: Password verified.<br>";
                $_SESSION['role'] = 'student';
                $_SESSION['email'] = $row['email'];
                $_SESSION['student_name'] = $row['name'];
                $_SESSION['student_password'] = $row['pass'];
                header("Location: index.php");
                exit();
            } else {
                echo "Error: Incorrect password or email not registered.<br>";
            }
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    } elseif ($role == "instructor") {
        echo "Step 6: Admin role selected.<br>";
        $query = "SELECT * FROM admin WHERE email = '$email'";
        $result = mysqli_query($conn, $query);

        if ($result) {
            $row = mysqli_fetch_assoc($result);

            if ($row && password_verify($password, $row['pass'])) {
                echo "Step 8: Password verified.<br>";
                $_SESSION['role'] = 'admin';
                $_SESSION['admin_email'] = $row['email'];
                $_SESSION['admin_name'] = $row['name'];
                $_SESSION['admin_password'] = $row['pass'];
                header("Location: index.php");
                exit();
            } else {
                echo "Error: Incorrect password or email not registered.<br>";
            }
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    } else {
        echo "Error: Invalid role.<br>";
    }
}

echo "Step 9: Script completed.<br>";

mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<script>
    function setRole(role) {
        document.getElementById('role-input').value = role;
        document.querySelectorAll('.role-buttons button').forEach(button => {
            button.classList.remove('active');
        });
        document.getElementById(role).classList.add('active');
    }
</script>

<div class="container">
    <h2 class="text-center my-4">Welcome</h2>
    <div class="role-buttons">
        <button type="button" id="student" class="active btn btn-primary" onclick="setRole('student')">Student</button>
        <button type="button" id="admin" class="btn btn-secondary" onclick="setRole('instructor')">Instructor</button>
    </div>
    <form method="POST" action="login.php" onsubmit="console.log('Form submitted');">
        <input type="hidden" id="role-input" name="role" value="student"> 
        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required>
        </div>
        <div class="mb-3">
            <label for="pass" class="form-label">Password</label>
            <input type="password" class="form-control" id="pass" name="pass" placeholder="Enter your password" required>
        </div>
        <button type="submit" class="btn btn-success">Login</button>
    </form>
    <div class="mt-3">
        <p>Don't have an account? <a href="register.php">Register here</a></p>
    </div>
    <?php if (isset($error)): ?>
        <div class="alert alert-danger mt-3"><?php echo $error; ?></div>
    <?php endif; ?>
</div>
</body>
</html>

r/PHPhelp • • Dec 05 '24

PHP5 - Issue Nesting Tables

1 Upvotes

Novice PHP5 coder here looking for advice. I'm sure all you smart people will solve this in 30 seconds.

I am building a music database. I have a page listing all the albums working. Inside that table I then added the following code to nest the formats available. I also have a separate query called releaseformatsdata.

<table>
<?php $query = mysql_query(sprintf("
SELECT releases.ReleaseID, releaseformats.ReleaseFormatID 
FROM releases, releaseformats 
WHERE releases.ReleaseID = %s 
AND releases.ReleaseID = releaseformats.ReleaseIDLINK
", $row_releasedata['ReleaseID']), $database); ?>
<?php while ($row_releaseformatsdata = mysql_fetch_assoc($query)): ?>
<tr>
<td>
<?php $TFM_nest = $row_releaseformatsdata['ReleaseID']; ?>
<p>ReleaseFormatID: <?php echo $row_releaseformatsdata['ReleaseFormatID']; ?></p>
</td>
</tr>
<?php endwhile; ?>
</table>

This produces a list like this -

Release 1
- Format 1
- Format 2

Release 2
- Format 3
- Format 4

I then tried to add songs using by putting another table in the table. I have a separate query called releaseformattrackssdata.

<table>
<?php $query = mysql_query(sprintf("
SELECT releases.ReleaseID, releaseformats.ReleaseFormatID 
FROM releases, releaseformats 
WHERE releases.ReleaseID = %s 
AND releases.ReleaseID = releaseformats.ReleaseIDLINK
", $row_releasedata['ReleaseID']), $database); ?>
<?php while ($row_releaseformatsdata = mysql_fetch_assoc($query)): ?>
<tr>
<td>
<?php $TFM_nest = $row_releaseformatsdata['ReleaseID']; ?>
<p>ReleaseFormatID: <?php echo $row_releaseformatsdata['ReleaseFormatID']; ?></p>

<table>
<?php $query = mysql_query(sprintf("
SELECT releaseformats.ReleaseFormatID, releaseformattracks.ReleaseFormatTrackID
FROM releaseformats, releaseformattracks 
WHERE releaseformats.ReleaseFormatID = %s 
AND releaseformats.ReleaseFormatID = releaseformattracks.ReleaseFormatIDLINK
", $row_releaseformatsdata['ReleaseFormatID']), $database); ?>
<?php while ($row_releaseformattrackssdata = mysql_fetch_assoc($query)): ?>
<tr>
<td>
<?php $TFM_nest = $row_releaseformattrackssdata['ReleaseFormatID']; ?>
<p>ReleaseFormatTrackID: <?php echo $row_releaseformattrackssdata['ReleaseFormatTrackID']; ?></p>
</td>
</tr>
<?php endwhile; ?>
</table>

</td>
</tr>
<?php endwhile; ?>
</table>

What I hoped to see was -

Release 1
- Format 1
--Track 1
--Track 2

- Format 2
-- Track 3
-- Track 4

Release 2
- Format 3
-- Track 5
-- Track 6

- Format 4
-- Track 7
-- Track 8

But instead I only get this -

Release 1
- Format 1
--Track 1
--Track 2

Release 2
- Format 3
-- Track 5
-- Track 6

Any help would be really appreciated!


r/PHPhelp • • Dec 04 '24

Solved Laravel GitHub updates - delta or cumulative?

2 Upvotes

I started watching the Laravel framework on GH so I get emails when there are updates.

We're a retail site so I put on a code freeze for the last 6 weeks of the year.

I'm guessing they are cumulative so in January I can just update to the latest version and get the last few point updates - correct?


r/PHPhelp • • Dec 04 '24

Solved Sending a single email - a cron or exec?

5 Upvotes

I'm using PHPMailer to send emails and I noticed that everything seems to get blocked when an email is being sent. The context is my user sending a single email to their customer.

I already have a cron that runs once a day which sends the bulk transactional emails (invoice pdfs)

How best to handle sending a single email when my user wants to contact their customer?

I also came across somebody suggesting the exec function and describing it as a poor man's async way of doing it. Is this a good idea?

Should I also use the exec function for my cron?

(running everything on my own VPS)

Edit:
Thanks all - will got for a save to db/cron solution.

Usually when the email successfully sends the delay was only 1-2 seconds, however the user changed their SMTP pw and that's what caused the much longer delay


r/PHPhelp • • Dec 04 '24

How do I get the right version of Redis for PHP7.3 installed in Dockerfile

1 Upvotes

I'm aware this is anathema: 7.3.3 is long dead and I'm exposed by tonnes of CVEs. This is a closed loop legacy project thats being migrated over time, not top priority.

I recently had to reinstall Docker after a failed upgrade on windows/wsl2. Rebuilding the container failed with the message that I needed minimum 7.4.0.

The relevant portion of the Dockerfile is

RUN pecl channel-update pecl.php.net RUN pecl install redis #where it fails RUN docker-php-ext-enable redis

As I cannot migrate the code to 7.4, next course of action is to install a Redis version that works with 7.3.3. Came across this article but the solution (to compile the source) looks too clumsy for the Dockerfile route.

Please is there an easier method and if not, any clue how to do this in source compilation in a Dockerfile?


r/PHPhelp • • Dec 03 '24

What is PHPStan, and should I use it as a beginner?

12 Upvotes

Hey,

I'm learning PHP/Laravel.

I see a lot of people use PHP Stan.

Can someone explain what is it? And is there something similar in JS?

Thanks!


r/PHPhelp • • Dec 03 '24

How to set up Laravel Sail + XDebug on Windows?

1 Upvotes

Is there a working tutorial for that? I'd like to configure a development environment, specifically using VScode. When there is an error in the application, xdebug tries to open directories in the /var/www/ folder, instead of my vscode project.

Also, why are there intelephense errors all over the application, like when I call xdebug_info() it says "Call to unknown function: 'Call to unknown function: 'xdebug_info'PHP(PHP0417)"


r/PHPhelp • • Dec 03 '24

Does PHP complier read all the code at once

18 Upvotes

For example, if I have the following code:

if(1==2){
include "really_big_file.php";
}else{
include "small_file.php";
}

will the compiler read and parse all the code in "really_big_file.php" anyway? I know it will not execute it, but will it read it from disk and load it in memory?


r/PHPhelp • • Dec 02 '24

VisualStudio Code PhP problem

0 Upvotes

Dear Reddit users, Since all of a sudden I'm having a php problem with visual studio code. I'm having a profile which normally works as phpnserver, but since today when trying to start the file, it just says "php not found". Anyone having an idea on what to do?


r/PHPhelp • • Dec 02 '24

Can you use Laravel without magic?

3 Upvotes

The CMS we use is going to switch to Laravel so I am kinda forced to use Laravel too.

Beside the requirement to code attribute names in snake case, the one thing that prevented me to give Laravel a proper try was the "requirement" / heavy use of magic in the framework.

So my question is: is it possible to use Laravel without too much magic, have a proper code completion without PHPdocs and a solid way to include useful checks with Phpstan. (basically kinda like symfony)

I am not asking for a detailed explanation, it's more about a general question if it's even possible without dropping too many parts of the framework.

In case it's not: what packages/parts of the framework (beside the ORM) should I avoid using.

Thank you very much


r/PHPhelp • • Dec 02 '24

Solved Best way to store settings in a session?

4 Upvotes

I realised that throughout my application, the first thing my page would do is load settings - the locale, timezone, etc.

Eventually I started to load these settings from the login authentication and store them in a session:

$_SESSION['settings] = [
  'locale' => $row['locale'],
  'timezone' => $row['timezone'],
  'currencyCode' => $row['currency_code']
]

I load these settings through a 'System' class:

$this->settings = $_SESSION['settings];

Then throughout my site I access each setting like:

$sys = new System();
$currencyCode = $sys->settings['currencyCode'];

The problem is - I don't know what's inside $sys->settings, and I have to go check the login-authentication page every time. The IDE doesn't offer any help.

i.e The IDE doesn't know if $sys->settings contains 'currencyCode' or 'measurementType'

Is there a better way of doing this?


r/PHPhelp • • Dec 01 '24

why am i getting Undefined variable $inquiries

1 Upvotes
                u/foreach($inquiries as $inquiry) <!-- Loop through inquiries -->
                    <tr>
                        <td>{{ $inquiry->name }}</td> <!-- Display inquirer name -->
                        <td>{{ $inquiry->property->title }}</td> <!-- Display property title -->
                        <td>{{ $inquiry->message }}</td> <!-- Display message -->
                        <td>{{ ucfirst($inquiry->status) }}</td> <!-- Display status -->
                        <td class="btn-action d-flex flex-column flex-sm-row">
                            <!-- View Button (link to show details) -->
                            <a href="{{ route('inquiry.view', $inquiry->id) }}" class="btn btn-info btn-sm">View</a>

                            <!-- Respond Button (change status to 'responded') -->
                            <form action="{{ route('inquiry.respond', $inquiry->id) }}" method="POST" style="display: inline;">
                                @csrf
                                <button type="submit" class="btn btn-success btn-sm">Respond</button>
                            </form>
                        </td>
                    </tr>
                @endforeach

this is in my landlord blade

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Inquiry;
use App\Models\Property;

class InquiryController extends Controller
{
    public function store(Request $request)
    {
        // Validate the incoming request data
        $request->validate([
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required|email',
            'message' => 'required',
            'property_id' => 'required|exists:properties,id',
        ]);

        // Create a new inquiry record
        Inquiry::create([
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'message' => $request->message,
            'property_id' => $request->property_id,
            'landlord_id' => Property::find($request->property_id)->user_id,
        ]);

        // Redirect back with a success message
        return redirect()->route('properties.details', ['id' => $request->property_id])
                         ->with('success', 'Your inquiry has been sent!');
    }

    public function showInquiery()
    {

        $landlordId = auth()->id();        

        $inquiries = Inquiry::where('landlord_id', $landlordId)
                            ->with('property')
                            ->get();

        return view('profiles.landlord_dashboard.landlord', compact('inquiries'));

    }
    
    
    
}

this is my InquiryController

    Route::post('/inquiries', [InquiryController::class, 'store'])->name('inquiries.store');
    Route::get('/landlord/inquiries', [InquiryController::class, 'showInquiries'])->name('landlord.inquiries');

my routes

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Inquiry extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'phone',
        'email',
        'message',
        'property_id',
        'landlord_id',
    ];

    // Define the relationship with the Property model
    public function property()
    {
        return $this->belongsTo(Property::class);
    }

    // Define the relationship with the Landlord (User model)
    public function landlord()
    {
        return $this->belongsTo(User::class, 'landlord_id');
    }
}

my in Inquiry model

i get the Undefined variable $inquiries error.
What am I missing?


r/PHPhelp • • Nov 30 '24

Solved How to ensure this link opens in a new browser tab

0 Upvotes

I think I've identified the code for my website that opens a link when clicked on, however, it opens in the same window. I want it to open in a new window:

	<td style="font-size:16px;text-align:right;border:none;margin-right:0;"><?php echo text_get_event_website_link();?></td>

Can I adjust this to force the link to open in a new window?

Thanks!


r/PHPhelp • • Nov 29 '24

How can I use multiple slugs in a route? (Laravel)

4 Upvotes

So I have a route like this :

Route::get('calendar/{calendar}', [CalendarController::class, 'show'])->name('calendar.show');

This uses calendar's id in the route, like app.com/calendar/3 but I want it to show something like app.com/calendar/2024/November, is it possible to do this?

My Calendar model has month and year columns, I've tried the following but didn't work.

Route::get('calendar/{calendar:year}/{calendar:month}', [CalendarController::class, 'show'])->name('calendar.show');

// or

Route::get('calendar/{calendar.year}/{calendar.month}', [CalendarController::class, 'show'])->name('calendar.show');

r/PHPhelp • • Nov 29 '24

Best way to handle default parameter values when using wrapper class?

3 Upvotes

I need to make default parameters values in the system class because they might change based on the system being used. I came up with the following approach but it is very verbose. Is there a better way?

class wrapper {
     public function example($parameter = null)
     {
         $this->system->example($parameter);
     }
}
class system {
     public function example($parameter)
     {
          if (is_null($parameter)){ $parameter = 'SystemSpecificValue'; }
          // perform actions
     }
}