/r/PHPhelp
This subreddit is for anyone who has questions about their PHP code.
Please read and understand the rules before creating a post.
Post specific problems or questions you have about PHP or your code.
Review our github to see if your question already has a great answer.
If someone answers your question, please mark your post as SOLVED.
/r/PHPHelp RULES:
1. Help us help you! Provide details about your question and be as specific as possible. When supplying code, preferably use PasteBin or similar.
2. Be nice Golden rule, people. If you believe someone is wrong, kindly inform them why you think so. It's possible you are also wrong. BE NICE!
3. Participate Posts that are only intended to get others to solve your problem add nothing to the community. Actively participate when you make a post by answering questions and sharing solutions.
4. Use a meaningful title Titles like: "PHP Help", "Help please", "Beginner question", or "I need some help with resolving this issue" are not good and not meaningful. Please include relevant info.
5. Don't delete an answered post People may be searching to solve a similar problem in the future. Don't take the provided answers away from them!
6. No malicious/illegal software Don't ask for help with phishing software, for example.
7. Self-promotion and/or linkdropping rules Our community adheres to the Reddit Self-Promotion Guidelines. Please become familiar with these guidelines as we, as moderators, will use them to remove content that we deem to violate these guidelines.
8. No job postings (For Hire or Hiring)
9. MARK YOUR POST AS SOLVED If your post has been solved, mark it as so by clicking Flair
-> Solved
.
CODE FORMATTING:
For inline code, use `backticks` to look like this
.
For a moderate amount of code, put it on separate lines, and prepend each line with four spaces, like this:
<?php /* code goes here */ ?>
For a lot of code, use PasteBin or something similar.
Upcoming PHP Conferences:
For a full list of conferences see the list on php.net.
Learning:
Examples:
Related subreddits:
/r/PHPhelp
I realised that throughout my application, the first thing my page would do is load settings - the locale, user id, 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 the settings 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.
Is there a better way of doing this?
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?
Dominate
is a Python library for creating and manipulating HTML documents through functions:
p('Hello world'); // <p>Hello world</p>
I found similar libraries on Github but they look like weekend projects (no offense). I was looking for something more mainstream.
Please don't suggest giant frameworks that do a thousand things. A small library is more than fine.
I've wanted to learn PHP for a long time, but I find it very hard to retain much or find motivation to continue when I'm learning independently using the widely available free resources. I have money nowadays so I want to invest in learning PHP. I'm currently looking at Codecademy, Udemy and Laracasts. Which would you recommend? If it helps, I'm already proficient in HTML and CSS with minimal knowledge in JS.
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!
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');
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
}
}
Recently got back into coding after a hiatus of about 15 years and have been delighted at the changes with PHP. Also switched to PHPStorm and I am astounded how much better the coding experience is as compared to SublimeText.
PHPStan/Psalm are two of the tools most frequently suggested as essential - however I am wondering if these are only useful to people not using PHPStorm?
PHPStorm is already alerting me to code issues - such as undefined variables.
Would PHPStan/Psalm offer me any major benefit?
Good day. I just wanted to ask if I've done this correctly.
Short story. I have an old version of Xampp running in my old PC. I have upgraded my PC and also installed the latest version of Xampp. I copied htdocs folder and mysql folder from the old PC to new PC. For the mysql folder, I only copy the folders of database and the ib_data1, ib_logfile1, and ib_logfile0.
Everything is working fine except with the FPDF. It is giving me an error with one of my webapp. It says: "FPDF Error: Unknown page size: letter"
I tried doing it with my old PC and no issue with FPDF.
Am I missing something here?
Hi all,
I am a complete newbie with anything php and was researching a solution for an event we have coming up.
I came across hi.events that is open source so decided I wanted to play around with it.
Was able to containerize the code in docker and make a few small changes as it didn’t completely suit my needs. The app worked perfectly on localhost.
I then tried to commit the changes and push the image to render. The backend pushed correctly but the frontend gave an error saying the file was not Arm 64.
Is there a simple guide to editing the open source software and then deploying it in render?
I used their one click deploy and was able to get it deployed on render (obviously) but I have no idea how I would change any of the code before deploying it.
I’m sure I am missing something obvious (or multiple things)
Thanks in advance.
Edit: the app is using Lavarel for the FE and React for BE
Hey all,
I am creating a PHP script that queries a MySQL database with table 'interns' but my script throws an exception at line 85 `$QueryResult = mysqli_query($DBConnect, $SQLstring); ` Ideally it would run the following and ascertain whether or not this email already exists. Observe:
$email = stripslashes($_POST['email']); //'email has already been validated through regex
$TableName = "interns";
if ($errors == 0) {
$SQLstring = "SELECT count(*) FROM $TableName where email = $email";
**$QueryResult = mysqli_query($DBConnect, $SQLstring);**//line 85
if ($QueryResult !== FALSE) {
$Row = mysqli_fetch_row($QueryResult);
if ($Row[0] > 0) {
echo "<p>The email address entered (" . htmlentities($email) . ") is already registered.</p>\n";
++$errors;
}
}
}
The database with table 'interns' exists and $DBConnect has established connection. '$email' value was retrieved from HTML form and has already been run through regex for data validation and value is passed ok until reaching this point. I tried utilizing a local variable with different email at the beginning of the block in question and receive the same error with the local email variable extension, so that proves the email value is passed until this point.
Hello. I'm trying to conditionally set Tailwind CSS classes. The idea is to highlight navbar elements to tell the user where they are. The navbar items have following styles when they're not the current page:
<div class="hidden md:block">
<div class="ml-10 flex items-baseline space-x-4">
<a href="index.php" class="rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white" aria-current="page">Home</a>
<a href="about.php" class="rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white" aria-current="page">About</a>
<a href="users.php" class="rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white" aria-current="page">Users</a>
</div>
</div>
However, if I want the item to be highlighted while the user is currently in the corresponding page, I need to use bg-gray-900 text-white
. The classes would look like this:
rounded-md bg-gray-900 px-3 py-2 text-sm font-medium text-white
Essentially, I need to add bg-gray-900
and text-white
, and remove text-gray-300 hover:bg-gray-700 hover:text-white
.
I'm using the following rather clunky approach:
<div class="hidden md:block">
<div class="ml-10 flex items-baseline space-x-4">
<!-- Current: "bg-gray-900 text-white", Default: "text-gray-300 hover:bg-gray-700 hover:text-white" -->
<a href="index.php" class="
<?php
if ( $_SERVER["REQUEST_URI"] === "/simple_user_management_system/index.php" ) {
echo "rounded-md bg-gray-900 px-3 py-2 text-sm font-medium text-white";
} else {
echo "rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white";
}
?>" aria-current="page">Home</a>
<a href="about.php" class="
<?php
if ( $_SERVER["REQUEST_URI"] === "/simple_user_management_system/about.php" ) {
echo "rounded-md bg-gray-900 px-3 py-2 text-sm font-medium text-white";
} else {
echo "rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white";
}
?>" aria-current="page">About</a>
<a href="users.php" class="
<?php
if ( $_SERVER["REQUEST_URI"] === "/simple_user_management_system/users.php" ) {
echo "rounded-md bg-gray-900 px-3 py-2 text-sm font-medium text-white";
} else {
echo "rounded-md px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white";
}
?>" aria-current="page">Users</a>
</div>
</div>
It certainly works in conditionally applying the required style, but it takes too much space and it's clumsy.
How would I make this shorter?
Let me explain better.
I want something like this:
<?php
SomeClass::processThisSomewhereElse(function() use ($var1, $var2...) {
// some heavy processing thing here
});
// continue the code here without noticing the heavy process (ant time taken) above
I tried many things with no success. I want to use this on Windows, so pcntl_* functions won't work. If possible, I want to update/share variables between the processes.
The maximum I got was creating a .php script and execute it with shell_exec/popen/proc_open/exec but they "wait" for the file to process...
Behind the scenes I tried with:
(just simplifying, I used the whole php bin path and script.php path)
and many other variations. All these don't work in a parallel or in an async way, the script has to wait until it stops, I want to deliver the function to another process and I wish I could do that only calling a function in the same file like the example I gave in the beginning of the post
I'm new to PHP and working on my project. I’m facing an issue where everything from the database loads fine with SELECT, except the image it’s not showing up/loading properly. I’ve tried a few different solutions, like creating a new table and experimenting with different syntaxes, but nothing’s working any tips or solution for this type of error
I am writing a program to generate a PDF calendar for my Mum to print out so she doesn't have to create it manually in Word every year. She has a list of dates that she always includes in the calendar, and there are some that I haven't figured out how to calculate yet. Can anyone help me with how to figure them out? I have done a number of searches, but haven't had any luck in figuring out how to calculate the listed dates. It is a UK Calendar, but many of the dates are not UK specific - as you will see it's a bit of a mix.
For completeness, I have also included dates that I have been able to figure out how to calculate, and how I did it. I realize that many of these are fairly obvious, but I am putting them all here so that future searchers have an easier time than I did! I have not included dates that are a set day each year (e.g. Christmas) as they don't need calculation.
Dates I still need to work out:
Any help on how to figure these out in PHP would be much appreciated.
Dates I have already figured out (and the code I used) are below.
Note 1: The year being calculated is stored in the $year
variable
Note 2: The result is stored in the $result
variable as a timestamp
Note 3: I know easter_date is only good until 2037 :)
Thanksgiving:
$result = strtotime('fourth thursday of november '.$year);
Remembrance Day:
$result = strtotime('second sunday of november '.$year);
Bank Holiday (First Monday in May):
$result = strtotime('first monday of may '.$year);
Bank Holiday (Last Monday in May):
$result = strtotime('last monday of may '.$year);
Summer Bank Holiday:
$result = strtotime('last monday of august '.$year);
British Summertime:
$result = strtotime('last sunday of march '.$year);
End British Summertime:
$result = strtotime('last sunday of october '.$year);
Easter Sunday:
$result = easter_date($year);
Easter Monday:
$result = strtotime(date('Y-m-d', easter_date($year))." + 1 day");
Ash Wednesday:
$result = strtotime(date('Y-m-d', easter_date($year))." - 46 day");
Ascension Day:
$result = strtotime(date('Y-m-d', easter_date($year))." + 40 day");
Shrove Tuesday:
$result = strtotime(date('Y-m-d', easter_date($year))." - 47 day");
Mothering Sunday:
$result = strtotime(date('Y-m-d', easter_date($year)).' -3 weeks');
Chinese New Year:
$formatter = new IntlDateFormatter(
'zh-CN@calendar=chinese',
IntlDateFormatter::SHORT,
IntlDateFormatter::NONE,
'Europe/London',
IntlDateFormatter::TRADITIONAL
);
$timeStamp = $formatter->parse($year.'/01/01');
$dateTime = date_create()->setTimeStamp($timeStamp);
$result = strtotime($dateTime->format('Y-m-d')." 00:00:00");
Hi, I'll include my code. I'm wondering what I'm doing wrong. I'm trying to display individual sets of unicode characters, but it isnt producing the correct results. It should be able to display emoticons when '10' (base 16) is selected. It doesn't. I've tried it using <<, + and *. I've also tried without a charset specifier, with iso 8859-1? and UTF-8. I think I'm doing something incorrectly, but not sure where my error may be. Thanks everybody!
Sorry, my bad.
Pastebin: https://pastebin.com/YM8i4xjs
On VPS: https://tecreations.ca/ca/tecreations/UnicodeTest2.php
Code on VPS: https://tecreations.ca/ca/tecreations/ViewFile.php?path=ca/tecreations/UnicodeTest2.php
Feel free to tell me to remove this but I’m looking for an iOS app to help me learn different php frameworks. Stuff I can look at when I’m not at work or home.
Wouldn’t have to be anything too in depth. Just something to rather teach the basics or help keep me updated. I can do the majority of the learning from home/work by reading the docs for whatever framework.
Anyway, I appreciate any ideas you have.
Hello Everyone, I am complete amateur to PHP. But my organisation has given me PHP Zend Framework 3 project with AngularJS Front end which is being transferred over to my Organisation from thier partner.
I need to work on the application to move it over to our cloud network and auth services. But I have no idea where to start since I don't know PHP.
Can you please help me with where I can start. Like Documentation, Tutorials etc. To get better understanding of the PHP ZF3 application.
Hey Redditors,
I’m dealing with a serious issue on my website, and I’m hoping someone here can provide some guidance.
About a month ago, we discovered that our website was under attack. The attacker managed to upload a PHP file into the images folder, which is used for storing user profile pictures. Unfortunately, our code was missing proper file validation at the time, which allowed them to exploit this vulnerability.
Even though we’ve since added file validation to prevent further exploits, the attacker seems to have retained some level of access. They are still able to upload PHP files into directories, which makes me suspect there’s an additional backdoor or vulnerability I’ve missed.
I’d appreciate any advice on:
Steps to identify and remove any backdoors or malicious scripts.
Best practices to secure the site and prevent further breaches.
Tools or resources to help analyze and clean the server.
Thanks in advance for your help!
So far what I understood is that the jobs gets serialized as a string object to be stored on whatever db/redid or whatever, then when running queue:work, you launch another process that actually fetches back from db and deserializes the object and builds the class via reflection api? Then executes it.
Is this how it happens???
I am currently following a course on Udemy regarding PHP and Javascript. I am at 25% of the course and I am now stuck for a few days at the point that the Google Maps API doesn't show when I inspect my page. In the course it says that the following line should be visible in the page inspection:
<script type='text/javascript' src='//maps.googleapis.com/maps/api/keyinputhere;ver=1.0'></script>But that line isn't showing. What am I possibly doing wrong? I've googles, chatGPTd, read the Q&A on the course and everything, but can't figure it out. I put the related code files in Github:
https://github.com/AshleyEnden/PHP-and-JS-University-website-course
I changed my API key so it only shows the first 4 letters with 2 dots.
Please let me know if I should ask this question more clearly or anything.
Edit to add: I am running 'npm run start' succesfully.
Hey,
I'm studying Laravel (with Blade at this moment).
I created CRUD project with supplements - https://github.com/aviran-abramov/laravel-blade-supplements-crud
The next thing I'm going to study is adding an admin middleware, and only there we will be able to edit/create/delete supplements.
What else should I add and learn?
2 images from the project:
https://i.imgur.com/LEzyvEA.png
https://i.imgur.com/eFlmXEZ.png
Thanks!
So I installed all fine. API key works well and i can get my access_token. All good.
But, I need my users to just access our SPA wit thei rAPI key, as an Authorization Bearer key, not by sending a post request to get a token First. Just a one way call our way so we can send back data.
We'll have a couple plans, 3 monthly/yearly. So each role will have some specific permissions.
Would you advise to tweak it manually/custom (NOT a lot of Laravel experience) or pick some package?
Taken from the Wave API pages:
I assumne it is not advised to use Laravel's own php artisan install:api in this case?
Have any of you walked this road before? What did you choose?
Thanks!
I was looking for an adoptable RedBeanPHP-type ORM for PHP v8.3 and currently looking at Travis CI. Did anyone use it? Can I trust it? Overall, I know I can use the RedBeanPHP with PHP v.5.7.4 but was wondering if the alternatives for v8+ are plausible. Thank you in advance!
SOLVED
I have an image of a gradient circle with a transparent background and I would like to color only the circle red. Everything I've tried so far colors the circle but also fills in the transparent area too. How do I maintain the base image's transparency? (The goal is to combine several images, all with transparency.)
Image, in case it's needed. (Link will self-destruct on 2024-12-22.)
p.s. Yes, I googled, but I don't find this question relative to PHP.
EDIT: FOUND IT, right in PHP's own documentation. Using adrien at unik dot solutions answer on this page. Was digging for it too late at night, I guess.
I have learned php, i have problem with two tasks firsttask:
Your task is to make a voting application with five candidates and one candidate can vote at once. To record the given sounds, a file results.txt is used. That file has five lines. Each line contains the candidate's voting number (1-5) and the votes received by the candidate. Separation of voting number and number of votes | Character. So, the format of the file looks like this:
1|22|63|84|35|10
You need to create a PHP script that modifies tulokset.txt file after the vote so that the number of votes cast for the voted candidate has been increased by one. Finally, the program must print out the total number of votes cast on the screen, including the one just cast.
The form on which the data is submitted is as follows:
<form action="vote.php" method="get">Pick a number: <select name="candidate"><option value=1 selected>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option></select><br><input type="submit" value="Lähetä"> </form>Example output:
Total votes cast: 15786 shares.
Php -script which i made
<?php if (isset($\_GET\['candidate'\])) { $candidate = $\_GET\['candidate'\]; $filename = results.txt'; $lines = file($filename, FILE\_IGNORE\_NEW\_LINES | FILE\_SKIP\_EMPTY\_LINES); $totalVotes = 0; foreach ($lines as $index => $line) { list($candidateNumber, $votes) = explode('|', $line); if ($candidateNumber == $candidate) { $votes = intval($votes) + 1; } $totalVotes += intval($votes); $lines\[$index\] = $candidateNumber . '|' . $votes; } file\_put\_contents($filename, implode(PHP\_EOL, $lines)); echo 'Total votes cast: ' . $totalVotes . ' pieces.'; } else { echo 'Select a candidate for voting.'; } ?>What have i done wrong Incorrect output: your program printed "1|22|6
", but should have printed "1|2 2|6
"
I have an sql database that I am connecting to PHP with HTML. I am currently working on a search bar that will select columns where any of the data terms match the input from the user (search all columns for a match). I am currently not getting my table displayed, and after some debugging I believe the problem occurs at this statement:
$stmt = $con->prepare("
SELECT t.truckid, t.truckmodel, d.driverlicenseNO, CONCAT(dr.firstname, ' ', dr.lastname) AS drName
FROM truck t, driver dr, drives d
WHERE t.truckid = d.truckid AND dr.driverlicenseNO = d.driverlicenseNO AND t.truckid LIKE ? OR t.truckmodel LIKE ? OR d.driverlicenseNO LIKE ? OR dr.drName LIKE ?");
I've been staring at this project all day, so I might be missing something simple, like a spelling error, but I was wondering if there is any reason this statement would not go through. I am using the '?' from an online suggestion, and my understanding is that it is a placeholder until I use the lines
$likeTerm = "%" . $searchTerm . "%";
$stmt->bind_param("sssss", $likeTerm, $likeTerm, $likeTerm, $likeTerm, $likeTerm);
$stmt->execute();
$result = $stmt->get_result();
Any ideas?
Hello. I'm setting up the primary files for a user management system. I'm following the steps for a tutorial I found on YouTube.
I've come across a problem. In index.php
I've set up things so that you get sent to a login screen if the GET variable isn't set or is empty. If it's not empty or unset, then there are other conditions to either show a specific view, default to the login page, or return a 404 error.
The problem is that when I enter index.php?view=home
, I should see:
home.php
Instead, what I get is a 404 error. Inputting index.php?view=login
indeed takes me to the login screen, so I'm not sure what's wrong with home
specifically.
Would you mind taking a look at this repo and maybe giving me ideas about what's up? Thankfully, everything is very light in code and content right now, so it shouldn't take much time.