/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 need guidance and steps on how can i go about creating a page on a web app which will be completely editable by admin just like elemantor , how do i go on creating a page like this and this has to be done in a wordpress website, how much do you guys think it will take for a intern developer with 7 month experience. This functionality is asked by my company client and my response was that why dont they just use elemantor themselves to edit the page as it will be too complex to make, but my manager said they dont want to use wordpress for anything and we need . Am i correct in thinking that it will be too complex, i made the page to be editable completely for text but i am having hard time with editing image as text is being stored in database so i ask if we can use a service like imagekit where we store image and in code use like so i can store it in db too but it was denied. Please guide me if there is a better solution for it and how can i proceed further thanks
The payment gateway provider has a wordpress plugin but it does not have all the gateway functions built in and also they have a seperate portal made available to merchants to get following data;
Merchant ID : API Key : Merchant Secret Key : Confirmation Endpoint Endpoint
Private key
Download Server Public key
Download Public key
Download
Their most uptodate plugin can be downloaded here; npmjs. com/package/directpay-ipg-js
IPG User Wise Card Management API Documentation justpaste. it/7w34p
IPG Integration Payment Link V1.0.1 Integration document justpaste .it/gj7ny
To access above links pls copy it and remove the space between the dot
I need support to help setup all this on wordpress explain steps need to setup as If I know nothing about JS, HTML, CSS or APIs
Installed plugin provided by them and researched all options inside their merchant portal but those functions provided by sdk seem to have no GUI to be easily accessed and edited
The affiliate plugin installed has feature to track sales of affiliated when checkout using woocommerce, where each affiliate gets their unqiue link with UTM like sitename. com/?abc=1 where this UTM would track the traffic and when customer clicks checkout pays and completes order it should auto credit affiliate balance with commission but since at checkout page that is sitename. com/checkout it simply overwrites UTM and at end page after payment it becomes like sitename. com /checkout/order-received/427999/?key=wc_order_WPTn5WSPKv9Kg which then again double overwrites any UTM if got to that point. Which i think might be main reason why affiliates sales are not getting auto credited with commission??
Hey Gang,
Thanks for all your input on a previous post I had found here
I am in the process of implementing some of the recommendations. But I want to ask about sessions and if someone uses the browser back/forward button.
I have a multipage/step form. About 4 steps, once filled out it emails me the info and the client a message saying it was completed. Why 4 steps, its a booking form, instead of overwhelming them I broke it down to Personal / location for service / service details / contract terms
A few times the form was completed but parts of the steps are blank, or missing info. I have validation in place to check for required fields, and will reload the page and it is "sticky" or remembers the input.
I've talked to a couple of clients and one was telling me they were using the forward and back buttons in the browser to read over the info or go back etc. I wasn't expecting this, (beginner here).
So I'm wondering if there is something I need to add to Sessions info, either some expiry, extending it, or changing how the form remembers inputs?
Researching this, Sessions don't seem to expiry until someone closes the browser, but then you see comments like PHP has a default value of 24 mins. Also see the browsers will cache info so when they go back it will fill it in (i've yet to actually try this), but not sure how that works if they then go forward instead of using the "next" button on the form, they may not realize going forward is not submitting the info they might have changed etc.
Some direction would be appreciated.
Is there a "right way" to parenthesise comparison operators when there are multiple conditions in, say, an if()
statement? For example, I would always do:
if ($a && ($b > $c)) {...}
If someone instead does:
if ($a && $b > $c) {...}
then I comment in a code review preferring the first form. But from reviewing operator precedence they appear to be effectively the same.
Am I old fashioned to prefer the former? Should I be ignoring these during CRs?
Or is there a good reason to use parenthesis for comparisons such as this?
I'm going through a friend's website that was made by someone else and I see this now: https://prnt.sc/mieJagx947-m
Does this seem safe? Seems poorly made and somewhat suspicious to me.
Thanks
I'm making a code according to a tutorial, but even though it's right, the "echo" and "print" don't appear on the site so I can check the information. Is there something wrong with the code? Why aren't the "echo" and "print" working?
<div class="content">
<h1>Title</h1>
<form action="" method="GET" name="">
<input type="text" name="search" placeholder="Text here" maxlength="">
<button type="submit">Search here</button>
</form>
<?php
if (isset($GET['search']) && $_GET['search'] != '') {
// Save the keywords from the URL
$search = trim($_GET['search']);
// Separate each of the keywords
$description = explode(' ', $search);
print_r($description);
}
else
echo '';
?>
But when I put in the code below, the echo works and appears on the site:
<?php
$mysqli = new mysqli(‘localhost’,‘my_user’,‘my_password’,‘my_db’);
// Check connection
if ($mysqli -> connect_errno) {
echo ‘Failed to connect to MySQL: ‘ . $mysqli -> connect_error;
exit();
}
?>
Hey everyone!
I’m working on a Laravel project where I’ve got requests with a ton of nested objects, each with its own validation rules. I need to make sure I get specific error messages for each validation, and once everything’s validated, I need to save the data into the models.
So, I’m wondering: Should I use Form Requests to handle the validation of all these nested objects, or is it better to use Value Objects (VOs) to keep the validation and data consistency in check before persisting it?
I’m torn between these two approaches and would love to hear if anyone’s dealt with something similar. Or if you’ve got other suggestions for handling complex nested validation and saving data in Laravel, I’m all ears!
Thanks in advance!
Should be easy but I've gotten nowhere with this. I know I've been away from coding since COVID and have been spinning my wheels with this.
works:
$stmt = "SELECT * FROM OpSigEST WHERE state= '$state';";
$result = mysqli_query($conn,$stmt);
so I was looking to update to prepared statements in my old code. I was looking to use the following but the MySQL is getting an empty request. I get no errors and the change is on the PHP side and just those few lines.
fails:
$stmt = mysqli_prepare($conn, "SELECT * FROM OpSigEST WHERE state=?");
/* create a prepared statement */
mysqli_stmt_bind_param($stmt, "s", $state);
/* bind parameters for markers */
mysqli_stmt_execute($stmt);
/* execute query */
$result = mysqli_query($conn,$stmt)
What am I forgetting or have miss-formatted or strait up screwed up?
based on what i've read, full special chars is better for security but the input will be less usable for non-malicious purposes. i wanna know others' opinion, which one is better in general?
I wanted the function to take in both data types, so either boolean or array. But for some reason the handler sees it as a syntax error. I've tried searching it on Google without any useful results. Any help would be appreciated
function isUsernameWrong(bool|array $result) { //two data types at the same time
return (!$result) ? true : false;
}
Error: syntax error, unexpected '|', expecting variable (T_VARIABLE)
Hi everyone, I have been trying to implement Laravel Cashier with Stripe in my application. So far I have competed the checkout page and also set up webhooks, created subscriptions and the billing portal. The only problem is that when I try to check the user status for subscription using user->subscribed() as per documentation I get false in the console.
As you may know better than me that with InertiaJs applications we use usePage() hook to access the user object in the front-end. When I check it in the console it does not even have the subscribed property. I also tried to access user from the request object but I go the same result in the console.
This is what I have done so far
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Log;
class BillingController extends Controller
{
public function index()
{
return Inertia::render('Billing/index', );
}
public function checkout(Request $request)
{
$priceId = $request->input('priceId');
$checkout_session = $request->user()
->newSubscription('prod_R8sIpY2XNM061A', $priceId)
->checkout([
'success_url' => route('success'),
'cancel_url' => route('cancel'),
]);
return Inertia::location($checkout_session->url);
}
public function success(Request $request)
{
$user = $request->user();
if ($user->subscribed('default')) {
Log::info('User is subscribed');
}
return Inertia::render('Billing/success', [
]);
}
public function cancel()
{
return Inertia::render('Dashboard');
}
public function billing(Request $request)
{
$billing_url = $request->user()->redirectToBillingPortal(route('dashboard'));
return Inertia::location($billing_url);
}
}
Here is my front-end
import SubscriptionPlans from "@/Components/SubsciptionCards";
import Authenticated from "@/Layouts/AuthenticatedLayout";
import { Head, Link, usePage } from "@inertiajs/react";
type Props = {};
const index = (props: Props) => {
const user = usePage().props.auth.user;
console.log(user);
return (
<Authenticated>
<Head title="Billing"></Head>
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8">
<SubscriptionPlans></SubscriptionPlans>
</div>
<Link href={route("billing.portal")}>Billing</Link>
</Authenticated>
);
};
export default index;
Can I provide access to routing to php files that are not generated as module in zend expressive? Or the routes are provided only to modules and actions of zend expressive?
Hi, I`m learning php for my classes. My teacher told us to wite php code and html code in seperate files, but in every php tutorial they say to do php and html in one document, Which option is better acording to you?
Idk if I wrote this correctly bc english is my 2nd language, bit I hope u understand this<3
Hey everyone,
https://imgur.com/gallery/KSHgOqE
I've got this assignment to build an organizational tree using PHP (Laravel/Symfony) for the backend and ReactJS for the frontend. I need to implement these actions:
List all individuals
View individual details
Edit info
Add new people
Delete entries
What should be my approach given that I've worked core php only and have very basic knowledge of laravel framework
Hey,
Using VSCode.
So I inserted code from tailwindui to my blade file.
When I click cmd+s to save, it won't do anything. But only when I change the name from x.blade.php to x.php and save, it will reformat.
What do I need to do fix that?
----------------------------------------------
EDIT: Guys, stop being rude, I'm just learning. I forgot to mention VSCode but you attack me like I did something bad or something to you.
"Right, lemme just find my crystal ball and my magic wand to cast the telepathic spell to know what IDE you are using, what extension you are talking about and what configuration you are setting"
"And you expect us to guess what IDE and extension you are using? I don't know about others, but I don't have a crystal ball."
Is this your friendly community of PHP? This is shameful and disgusting.
this is html
<html>
<head>
<script src="jquery-3.7.1.min.js"></script>
</head>
<body style="background-color:#d7d5ef ; display: flex; justify-content: center; align-items: center;">
<div
style="padding: 20px; border: 2px solid transparent; box-shadow: 0 0 15px 5px #00ff00; background-color: #5a7b90;">
<form id="frmone" method="POST">
<label for='fname'>First name</label><br>
<input type='text' id='fname' name='fname'><br>
<label for='lname'>Last name</label><br>
<input type='lname' id="lname" name='lname'><br>
<label for='email'> Email:</label><br>
<input type='text' id='email' name='email' oninput="validateEmail()"><br>
<span id="email-error" style="color:rgb(255, 51, 0);"></span>
<p><label for="address">Address:</label></p>
<textarea id="address" name="address" rows="4" cols="50" placeholder="Enter your address"></textarea>
<br>
<label for='phno'> Phone number:</label><br>
<input type="number" id='phno' name='phno' oninput="vphno()"><br>
<span id="phno-error" style="color:rgb(255, 59, 0);"></span><br>
<label for='password'> PASSWORD:</lable><br>
<input type="password" id='password' name='password' required><br>
<br><br>
<h3>Choose Gender</h3>
<input type='radio' id='male' name='gender' value="male">
<label for='male'>Male</label>
<input type='radio' id='female' name='gender' value="female">
<label for='female'> Female </label><br>
<input id="sbmbtn" type="submit" value="Submit">
</form>
</div>
</body>
<script>
function validateEmail() {
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
let email = document.getElementById('email').value;
let emailError = document.getElementById('email-error');
emailError.textContent = '';
if (/\d/.test(email)) {
emailError.textContent = 'Do not enter numbers. Only letters are allowed.';
}
if (!email.match(validRegex)) {
emailError.textContent = "not a valid email";
}
}
function vphno() {
let numm = document.getElementById('phno').value;
if (numm.length > 10) {
numm = numm.slice(0, 10);
document.getElementById('phno').value = numm;
}
let errorMessage = document.getElementById('phno-error');
errorMessage.textContent = '';
if (numm.length < 10) {
errorMessage.textContent = 'Phone number must be exactly 10 digits long.';
return false;
}
return true;
}
</script>
<script>
$(document).ready(function () {
$('#frmone').on('submit', function (e) {
e.preventDefault();
let email = $('#email').val();
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
let fname = $('#fname').val();
let lname = $('#lname').val();
let address =$('#address').val();
let phno= $('#phno').val();
let password= $('#password').val();
let gender = $('input[name="gender"]:checked').val();
if (email.match(validRegex)) {
if (phno.length == 10) {
if(fname.length > 0) {
console.log("Password:", password);
$.ajax({
url: "gendb.php",
method: "POST",
data: {
action: 'submit',
email: email,
fname: fname,
lname: lname,
address: address,
phno: phno,
password: password,
gender: gender,
},
contentType: 'json',
dataType: 'json',
beforeSend: function () {
$('#sbmbtn').val('wait...');
},
success: function (data) {
$('#sbmbtn').val('Submit');
if (data.error == 1) {
alert('error submitting data '+ data.message);
}
else if(data.success==1) {
alert('data submitted succesfully');
window.location.reload();
}
},
error: function(xhr,status,err){
var status=status;
}
})
} else {
alert('Please ensure all fields are valid before submitting, phonenumber.');}
} else {
alert('Please ensure all fields are valid before submitting, email.');}
}
else {
alert('Please ensure all fields are valid before submitting, email.');}
});
})
</script>
</html>
and this is php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "gemdb";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("connection failed" . $conn->connect_error);
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data=[];
if (!isset($_POST["password"])) {
$data['error']=1;
$data['success']=0;
$data['message']='password empty';
} else {
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$address = $_POST["address"];
$phno = $_POST["phno"];
$password = $_POST["password"];
$gender = $_POST["gender"];
$sql = "INSERT INTO addressdata (fname, lname, email, address, phno, password, gender)
VALUES ('$fname', '$lname', '$email', '$address', '$phno', '$password', '$gender')";
if ($conn->query($sql) === TRUE) {
$data['success']=1;
$data['error']=0;
exit;
}
else {
$data['error']=1;
$data['success']=0;
$data['message']=$conn->error;
}
}
echo json_encode($data);
}
}
$conn->close();
?>
I saw a tutorial on how to make a page for inserting data into the database, but it was an old tutorial and it's not working anymore.
I saw that this version of php is old, but I don't know how to update it. I'm a php newbie.
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
if(isset($_POST['submit'])) {
$site_title = $_POST['site_link'];
$site_title = $_POST['site_title'];
$site_title = $_POST['site_description'];
if($site_title=='' OR $site_link=='' OR $site_description) {
echo "<script>alert('please fill all the fields!')</script>";
exit();
}
else {
$insert_query = "insert into sites (site_title,site_link,site_description) values ('$site_title', '$site_link', '$site_description')";
if(mysql_query($insert_query)) (
echo "<script>alert('Data insert in databse')</script>";
)
}
}
?>
I'm having a strange issue in my app. I have this section which uses 2 functions and stores the result in 2 variables. Both the functions do pretty simple stuff. It takes in a long string and indicates whether that string contains a target word. The first function takes in an array of strings, while the second function only takes 1 string.
Both functions are supposed to return a boolean value.
The first variable (appleResult) shows up as true in a var_dump.
The second variable (bananaResult) however shows up as an empty string in a var_dump, even though I have inserted a console_log inside that function which writes to the console right before it returns true.
//This value registers as true
$appleResult = checkIfRealApple($description, $arrOfFruitNames);
//This value does not register as true
$bananaResult = checkIfRealBanana($otherDescription, $singularFruitName);
//shows up as bool (true)
console_log("appleResult: " . var_dump($appleResult));
//shows up as empty string
console_log("bananaResult: " . var_dump($bananaResult) );
function checkIfRealApple($clueString, $arrOfFruits)
{ for ($b = 0; $b < sizeof($arrOfFruits); $b = $b + 1) {
if (strpos($clueString, $arrOfFruits[$b])) {
return true;
}
}
return false;
}
The second function (below) is returning true, but that is not being stored in the variable.
function checkIfRealBanana($clueString, $targetName){
console_log("checkIfRealBanana:clueString:".$clueString.",targetName:".$targetName."_");
if(strpos($clueString, $targetName)){
console_log("ReachedTrueReturnPoint");
//I have confirmed my console is showing the string "ReachedTrueReturnPoint";
return true;
}
else{
//I have confirmed that my console DOES NOT contain the following string.
console_log("ReachedFalseReturnPoint");
return false;
}
}
I'm also using this helper function as a console log simulator (I got it off stack exchange)
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;
}
Is there a PHP equivalent of Python's "random.randrange" function?
Hi, I'm using Herd for a Laravel Site/Project but I also want a Site/Project for vanilla PHP development since XAMPP doesn't play nice with Herd. I've found references to "LocalValetDriver" but it's unclear what the process is. to create the site and what code needs to be in LocalValetDriver.php to have a simple folder with subfolders to run any random PHP file.
Hello everyone i'm using blade and have a homepage component where i included a search-form component and once the submit button on that form is clicked i redirect it to another component called searchresult where again the searchform is included a long with petsitterlist component the thing is that the route /home calls a method that sends the data im supposed to populate the selects with in the search form and that method formListHomepage calls the view homepage ```
public function formList()
{ $prestations = PrestationModel::all();
$countries = CountryModel::all();
$species = SpeciesModel::all();
return ['prestations' => $prestations, 'countries' => $countries, 'species' => $species];
// dd($prestations);
}
public function formListHomepage(){
$prestations = $this->formList()['prestations'];
$countries = $this->formList()['countries'];
$species = $this->formList()['species'];
return view('components.homepage', compact('prestations', 'countries', 'species'));
} ``` and i wanted after clicking submit and being redirected to have the previously chosen options in the selects and the input data to still show in in the form after redirection and so in the method that handles the search i tried to resend the same data that was sent in the homepage (redundant which bothers me) and added to it the $searchParams->$request->all() like this ``` return view('components.searchresult',[
'query' => $query,
'prestations' => $prestations,
'countries' => $countries,
'species' => $species,
'searchParams' => $request->all()
]); ```
and tried to modify the searchform by adding this ``` <select class="w-full h-full text-center text-md tracking-wide font-medium border rounded-full border-gray-300 cursor-pointer focus:outline-none focus:ring-0 focus:border-transparent" name="prestationId" id="prestation">
@ if ($prestations)
@ foreach ($prestations as $prestation)
<option value="{{ $prestation->id }}"{{ ( isset($searchParams['prestationId']) &&
$searchParams['prestationId'] == $prestation->id) ? 'selected' : ''}}
>{{ $prestation->name }}
</option>@ endforeach
@ endif``` so that if we are in the case of redirection and there are $searchParams to put in the chosen options and the inputs but it doesn't seem to be working and im getting the parts ['prestationId'] colored in red. Can anyone help me with this?
Hello guys! We encountered an error, we cannot generate or download a pof file because it says it detected an incomplete character in input string. We never encountered this before production. It just happened when we switched from VPS. Does anybody know how to solve this? I dont think the problem is within our code as it worked from local.....
I am a complete rookie at PHP and this question is most likely already answered, but I get terrible results from Google and Stack Overflow. I am almost certainly not using the correct term.
I am attempting to write if statements to alter what a user sees in the nav bar depending on what category of user they are. For example, I want my "admin" users to have a drop down that no one else has access to.
Is there a variable I can set in the session to check if there is a yes or no in a column of the users database?
These users are all in one table in my database. The category is set by a drop down in the form I created to input new user information.
God I hope I'm making sense.
UPDATE: Thank you all for your replies! It was extremely helpful and a good learning experience as I was in fact using incorrect terminology.
So basically what the title says. There’s this project that is a pain to work at my job. Queries are just plain SQL and not everything is escaped properly so it causes issues between MySQL versions. Idc one way or another but this just seems like bad design. What are your thoughts?
Hi all
I wanting to give access to different areas of the page but I need to know if there on the WiFi local network or www. How can I do this in php please
I've had a look at below but only returns not access from local no matter how much I try.
<?php if ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1') { echo 'You are accessing the website from localhost.'; } else { echo 'You are NOT accessing the website from localhost.'; } ?>Hi everyone, I have been trying to implement Stripe payment into my application. I have completed the functionality which opens the stripe checkout page. Now I wanna redirect user to the success page. in the success page url I pass in session id through which I get customer details to show on the page. Here comes the error
//checkout page
public function checkout(Request $request)
{
Log::info($request->input('product'));
$product = $request->input('product');
$stripe = new StripeClient(env('STRIPE_API_KEY'));
$totalPrice = 0;
$totalPrice = $totalPrice + $product['price'];
$checkout_session = $stripe->checkout->sessions->create([
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => $product['name'],
],
'unit_amount' => $product['price'] * 100,
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => route('products.success', [], true) . '?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('products.cancel', [], true),
]);
$order = new Order();
$order->status = 'unpaid';
$order->total = $totalPrice;
$order->session_id = $checkout_session->id;
$order->save();
return Inertia::location($checkout_session->url);
}
//success page
public function success(Request $request)
{
// \Stripe\Stripe::setApiKey(env('STRIPE_API_KEY'));
$stripe = new StripeClient(env('STRIPE_API_KEY'));
$sessionId = $request->query('session_id');
Log::info($sessionId);
try {
$session = $stripe->checkout->sessions->retrieve($_GET['session_id']);
$customer = $stripe->customers->retrieve($session->customer_details);
$order = Order::where('session_id', $session->id)->first();
if (!$order) {
throw new NotFoundHttpException();
}
if ($order->status === 'unpaid') {
$order->status = 'paid';
$order->save();
}
return Inertia::render('Products/success', [
'session' => $session,
'customer' => $customer,
]);
} catch (\Exception $e) {
Log::error($e->getMessage());
throw new NotFoundHttpException();
}
}
//route in web.php
Route::get('/success/{session_id?}', [ProductController::class, 'success'])->name('products.success');
//front-end react code to make a request to the back-end
import Authenticated from "@/Layouts/AuthenticatedLayout";
import { Head, Link } from "@inertiajs/react";
type Props = {
products: any;
};
const index = ({ products }: Props) => {
return (
<Authenticated
header={
<h2 className="text-xl font-semibold leading-tight text-gray-800">
Products
</h2>
}
>
<Head title="Products"></Head>
<div className="max-w-7xl mx-auto p-5">
<div className="grid md:grid-cols-3 items-center justify-items-center gap-5">
{products.map((product: any) => (
<div
className="border border-slate-300 shadow-2xl p-4 rounded-lg"
key={product.id}
>
<img
src={product.image}
alt={product.name}
className="w-full h-full rounded-md mb-2"
/>
<h1 className="mb-2">{product.name}</h1>
<Link
href={route("products.checkout", {
product: product,
})}
method="post"
as="button"
>
<button className="px-4 py-2 bg-blue-700 rounded-lg text-white">
Buy now
</button>
</Link>
</div>
))}
</div>
</div>
</Authenticated>
);
};
export default index;
This request was blocked because the URL path includes the forbidden characters '..' or control characters.
So i'm learning php on the fly and need to pull some data from a json file thats formatted like this: https://pastebin.com/kAPnLZVe
I need to loop through and grab the "names" and a few other bits (once i know how to get the names i can pull and format the rest. Right now I have
$filename='alarms.json'
jsonstring=file_get_contents($filename);
$jsonData=(json_decode($jsonString, true);
then various foreach loops that will get me all the way up to $jsonData['data'][0] from which i can pull the name, but id like to be able to loop through [0-n] to pull them.
I'm trying to learn classes. I asked ChatGPT about potential project ideas involving classes and it proposed a simple user management system. The features would be login
, register
, and logout
.
I just did this as an initial test but I'm not sure how to move forward from here:
class User {
public $username, $email, $password;
function getUserInfo() {
return "Username: $this->username \nEmail: $this->email \nPassword: $this->password";
}
}
$andy = new User();
$andy->username = "andy";
$andy->email = "andy@example-test.com";
echo "<pre>";
echo $andy->getUserInfo();
echo "<pre>";
I'm interested in developing methods to login, register and logout but I'm not sure to do it. For example, if I wanted to log in, how would I validate that the input for the username, password, and email actually matches an existing user? Would I need a database for this? Do I need at least some basic HTML to input the data?
PS: The \n
doesn't work unless I use echo "<pre>";
. How to fix that?
Hi. I'm running imagick on a large number of JPGs (thousands) on a remote server, cropping and resizing. Sooner or later the process crashes or freezes, killing my ssh, and I have to restart the server (AWS EC2). I was monitoring memory and disk use, hadn't run out. PHP 8.3.6 (cli), Ubuntu 24.04 LTS. Anyone have any ideas?