I would like to add the Apartment Number optional field at checkout (without third-party plugins) so it will be added automatically at the New Customer Order email and PDF invoice that is automatically generated.
Category: PHP
Category Added in a WPeMatico Campaign
CodeIgniter 4 redirect()->to() not working on IE
I am getting error from IE when I redirect to “dashboard” controller after settings session values in “login” function ( return redirect()->to(base_url('dashboard'));
). I have this working on Chrome, Firefox, Edge, and Opera.
I am using public $sessionDriver = 'CodeIgniterSessionHandlersDatabaseHandler';
for session storage. this works well with other borwsers.
<?php
namespace AppControllers;
use AppControllersBaseController;
use AppModelsUserModel;
class User extends BaseController
{
public function login()
{
$data = [];
if ($this->request->getMethod() == 'post') {
$rules = [
'email' => 'required|min_length[6]|max_length[50]|valid_email',
'password' => 'required|min_length[8]|max_length[255]|validateUser[email,password]',
];
$errors = [
'password' => [
'validateUser' => "Email or Password don't match",
],
];
if (!$this->validate($rules, $errors)) {
return view('login', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$user = $model->where('email', $this->request->getVar('email'))
->first();
// Stroing session values
$this->setUserSession($user);
// Redirecting to dashboard after login
return redirect()->to(base_url('dashboard'));
}
}
return view('login');
}
private function setUserSession($user)
{
$data = [
'id' => $user['id'],
'name' => $user['name'],
'phone_no' => $user['phone_no'],
'email' => $user['email'],
'isLoggedIn' => true,
];
session()->set($data);
return true;
}
public function register()
{
$data = [];
if ($this->request->getMethod() == 'post') {
//let's do the validation here
$rules = [
'name' => 'required|min_length[3]|max_length[20]',
'phone_no' => 'required|min_length[9]|max_length[20]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[tbl_users.email]',
'password' => 'required|min_length[8]|max_length[255]',
'password_confirm' => 'matches[password]',
];
if (!$this->validate($rules)) {
return view('register', [
"validation" => $this->validator,
]);
} else {
$model = new UserModel();
$newData = [
'name' => $this->request->getVar('name'),
'phone_no' => $this->request->getVar('phone_no'),
'email' => $this->request->getVar('email'),
'password' => $this->request->getVar('password'),
];
$model->save($newData);
$session = session();
$session->setFlashdata('success', 'Successful Registration');
return redirect()->to(base_url('login'));
}
}
return view('register');
}
public function profile()
{
$data = [];
$model = new UserModel();
$data['user'] = $model->where('id', session()->get('id'))->first();
return view('profile', $data);
}
public function logout()
{
session()->destroy();
return redirect()->to('login');
}
}
What is the best way to get /24 blocks from IP address ranges?
I am trying to figure out what the best/most efficient way to get individual /24 IP blocks from a range of IP addresses using PHP.
I have ranges of IP addresses in an MySQL database (I cannot change how this is presented) and have to have individual ranges of /24 blocks saved, also in a specific way (I cannot change the MySQL entries, nor how the software processes the list).
For example, I have various ranges of IPv4 IP addresses in this format:
86.111.160.0 - 86.111.175.255
Which I need to save in this format:
86.111.160.0
86.111.161.0
86.111.162.0
...
86.111.175.0
I’m having a bit of a block on how to do this without writing something hugely complicated to process each line.
Is there any function in PHP that can help me with this?
Thanks in advance.
substr_replace either creates an infinite loop or doesn’t replace substrings
I’ve been having this issue lately.
So basically I have a string that I get like this:
$contents = file_get_contents("system.po");
And it looks like this:
msgctxt "views.view.fra_vacancies:label:display:default:display_title:display_options:exposed_form:options:submit_button:reset_button_label:exposed_sorts_label"
msgid "Sort by"
msgstr ""
msgctxt "views.view.fra_vacancies:label:display:default:display_title:display_options:exposed_form:options:submit_button:reset_button_label:exposed_sorts_label:sort_asc_label"
msgid "Asc"
msgstr ""
(but with many entries like the above)
And I also have a table like this called $finalArray (with many entries as well):
[1041] => Array
(
[0] => Sort by name
[1] => Ταξινόμηση κατά όνομα
)
[1042] => Array
(
[0] => Country
[1] => Χώρα
)
What I do is going to each msgid in my file-string with strpos and check the value (for example “Sort By”), then i search if the value exists in my table (at [0] index) and then I move to msgstr with strpos and I replace the whole line with a string which contains the translation from my table (at [1] index)
Here is the code:
$lastPos = 0;
//while loop to go to each 'msgid' in my file-string
while (($lastPos = strpos($contents, 'msgid', $lastPos))!== false) {
//here i get the whole 'msgid' line
$startOfLine = strrpos($contents, "n", ($lastPos - $len));
$endOfLine = strpos($contents, "n", $lastPos);
$sourceLine = substr($contents, $startOfLine, ($endOfLine - $startOfLine));
//here i change the pos and i go to the next 'msgstr' and i get the whole line
$lastPos = strpos($contents, 'msgstr', $lastPos);
$start = strrpos($contents, "n", ($lastPos - $len));
$end = strpos($contents, "n", $lastPos);
$transLine = substr($contents, $start, ($end - $start));
//here i find the value that matches from my array and i try to replace the substring
foreach ($finalarray as $key => $value) {
if (substr_count_array($sourceLine, [$value[0], 'msgid']) == 2){
$rstring = 'msgstr ' . '"' . $value[1] . '"';
//debugged and checked that $sourceLine and $transLine are correct but is the issue *
$contents = substr_replace($contents, $rstring, $start, 0);
break;
}
}
}
//just a function that checks if more strings exist in a substring
function substr_count_array( $haystack, $needle ) {
$count = 0;
foreach ($needle as $substring) {
$count += substr_count( $haystack, $substring);
}
return $count;
}
*The issues is that when i use:
$contents = substr_replace($contents, $rstring, $start, 0);
I get an infininte loop and when I assing the result of substr_replace to a different variable (for example $contentsNew) and I echo it, my strings aren’t replaced.
Thank you for your time.
Can’t generate a regular expression
I’m trying to generate a regular expression to detect any string that :
- Starts with the [
- Ends with ]
- Contains any word or number or space
Example : [Maxsens8 Innovations]
I’m using : https://regex101.com
I create this regular expression : ^[[a-zA-Z0-9]]$
This regular expression does not match to expressions that i’m looking for and i thing the problem
is about the last character .
I will be gratefull if someone explain to me how to generate to right regular expression that
detect strings like : [Maxsens Innovations] [Verifik8] [Divoluci] …
APP_URL is not having impact on URL generated in Laravel; ASSET_URL works
I’m not a Laravel/PHP dev. Just trying to setup a service built in it..
Have setup APP_URL
to a scheme & domain-name based url. And the views are generating links using route(..)
function.
But, the links that are getting generate have Base URL at which it is browsed instead of APP_URL config.
For example:
If http://abc.domain
, https://abc.domain
and https://a12.domain
all are endpoint of same app. And we have config for APP_URL=https://abc.domain
.
Still depending on what we use to browse the page as; if visited via https://a12.domain
.. it will generate route with https://a12.domain
at base.
ASSET_URL
are working. APP_URL
is not having any impact though.
Versions in use are
"laravel/framework": "^8.12",
"laravel/helpers": "^1.4",
"laravel/tinker": "^2.5",
From SQL to Laravel 8 Eloquent
I have created a query in SQL and it works quite well.
SELECT learning_content_number,
course,
count(required) as required,
count(overdue) as overdue,
count(status) as status,
count(completion_date) as completion_date
FROM hse_leatros
GROUP BY learning_content_number
Now I want to translate it in Laravel 8 Eloquent. This script works, but I am missing the information about the course.
$courses = Leatro::groupBy('learning_content_number')
->selectRaw('count(required) as required, learning_content_number')
->selectRaw('count(overdue) as overdue, learning_content_number')
->selectRaw('count(status) as status, learning_content_number')
->selectRaw('count(completion_date) as completion_date, learning_content_number')
->get();
How can I enter the in the code that it is transferred with?
Show shipping class on product page (variable products) Woocommerce
I’m struggling to show the different shipping classes on the product page in Woocommerce. I have found several codes that show the shipping class of simple products. But not codes that show the classes of the different variations on a variable product.
The code should get the shipping class of simple products to show (cause I gave several simple products). But when the product is a variable product it needs to show the shipping classes of the variations instead of the parent shipping class.
I am not capable of coding this, hoping there is someone who is skilled enough and willing to help.
It would be nice if the front end looks like this:
Front end shipping class
execute iplog.php on click of links
i am logging visitors IP by the following code below
$iplogfile = 'ips.txt';
$ipaddress = $_SERVER['REMOTE_ADDR'];
$webpage = $_SERVER['SCRIPT_NAME'];
$timestamp = date('d/m/Y h:i:s');
$browser = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen($iplogfile, 'a+');
chmod($iplogfile, 0777);
fwrite($fp, '['.$timestamp.']: '.$ipaddress.' '.$webpage.' '.$browser. "rn");
fclose($fp);
but i want it to be execute only when user clicks on this particular links
<a href="tel:+1 (000) 000-0000" class="btn-blue btn-red">Book Now</a>
<a href="tel:+1 (111) 111-1111" class="btn-blue btn-red">Call Now</a>
can someone help me out here? i cannot figure out how to acheive it 🙁
Thanks alot for your help and input.
PHP – sending outlook invite to specific calendar
I am trying to send meeting invite through php and all is woking fine, but meeting is displayed in my personal calendar and I want in to be visible in shared calendar. Can I set it up, so meeting will be written in another selected calendar? Or is there some parameter, where I can describe it?
My code:
function sendIcalEvent($address, $subject, $name, $datum_na_kdy, $datum_podani_pozadavku){
$domain = "@domain.com";
$startTime = "some date";
$endTime = "some date";
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->IsSMTP();
$mail->Host = "host.com"; // SMTP server
$mail->Username = "[email protected]";
$mail->Password = "********";
//$mail->SMTPSecure = 'tls';
$mail->Port = some-number;
$mail->AddAddress($address);
$mail->From = "[email protected]";
$mail->FromName = "Automat ";
$mail->ContentType = 'text/calendar';
$ical = 'BEGIN:VCALENDAR' . "rn" .
'PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN' . "rn" .
'VERSION:2.0' . "rn" .
'METHOD:REQUEST' . "rn" .
'BEGIN:VTIMEZONE' . "rn" .
'TZID:Eastern Time' . "rn" .
'BEGIN:STANDARD' . "rn" .
'DTSTART:20091101T020000' . "rn" .
'RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=11' . "rn" .
'TZOFFSETFROM:-0400' . "rn" .
'TZOFFSETTO:-0500' . "rn" .
'TZNAME:EST' . "rn" .
'END:STANDARD' . "rn" .
'BEGIN:DAYLIGHT' . "rn" .
'DTSTART:20090301T020000' . "rn" .
'RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2SU;BYMONTH=3' . "rn" .
'TZOFFSETFROM:-0500' . "rn" .
'TZOFFSETTO:-0400' . "rn" .
'TZNAME:EDST' . "rn" .
'END:DAYLIGHT' . "rn" .
'END:VTIMEZONE' . "rn" .
'BEGIN:VEVENT' . "rn" .
'ORGANIZER;CN="'.$name.'":MAILTO:'.$address. "rn" .
'ATTENDEE;CN="'.$name.'";ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:'.$address. "rn" .
'LAST-MODIFIED:' . date("YmdTGis") . "rn" .
'UID:'.date("YmdTGis", strtotime($startTime)).rand()."@".$domain."rn" .
'DTSTAMP:'.date("YmdTGis"). "rn" .
'DTSTART;TZID="Eastern Time":'.date("YmdTHis", strtotime($startTime)). "rn" .
'DTEND;TZID="Eastern Time":'.date("YmdTHis", strtotime($endTime)). "rn" .
'TRANSP:OPAQUE'. "rn" .
'SEQUENCE:1'. "rn" .
'SUMMARY:' . $subject . "rn" .
'CLASS:PUBLIC'. "rn" .
'PRIORITY:5'. "rn" .
'BEGIN:VALARM' . "rn" .
'TRIGGER:-PT15M' . "rn" .
'ACTION:DISPLAY' . "rn" .
'DESCRIPTION:Reminder' . "rn" .
'END:VALARM' . "rn" .
'END:VEVENT'. "rn" .
'END:VCALENDAR'. "rn";
$mail->Subject = "Invitation: Outlook Calendar Event";
$mail->AddStringAttachment($ical, "event.ics", "7bit", "text/calendar; charset=utf-8; method=REQUEST");
$mail->Body = "Test Outlook Calendar event mail";
$mail->Ical = $ical;
$mail->CharSet = 'UTF-8';
$message = NULL;
if(!$mail->Send()) {
$message = false;
} else {
$message = true;
}
return $message;
}
how can i reduced app.js file size when i use laravel ,vuejs and vuetify in my project and i use treeshaking concept?
app.js import vuetify module.
import Vuetify, {
VApp,
VContent,
VListGroup,
VListItem,
VListItemAction,
VListItemActionText,
VListItemAvatar,
VListItemContent,
VListItemGroup,
VListItemIcon,
VListItemSubtitle,
VListItemTitle,
VFooter,
VForm,
VChip,
VMenu
} from 'vuetify/lib'
Cannot kill a process by a PHP Script running behind nohup
I have a php script that perform some actions after killing some old processes.
act.php
$pids = shell_exec('ps aux | grep "saso" | awk '{print $2}'');
$pids = str_replace("n", ' ', $pids);
$pids = array_filter(explode(' ', $pids));
foreach ($pids as $pid) {
shell_exec('kill -9 ' . $pid . ' > /dev/null 2>&1 &');
}
// reset of the code . ..
The script works well by running php act.php
. It fetch process ids, kill it, then run the reset.
But it is not working when I run nohup php act.php &
or nohup php act.php
. The process is not killed.
I need nohup
to run the script in the background with no hang up.
Can’t PHP script fetch pids behind nohup
? and are there any alternatives ?
Thanks in advance.
Symfony5: form for self-referencing many-to-many
In a Symfony5 application, how can we utilize the form-component to correctly set up a self-referencing, many-to-many relationship?
Note: this is purely about the form-side of things, Doctrine is already happy.
Let’s say we have a “Person”-entity, and these Person-instances host guests, who are also Persons:
#[Entity(repositoryClass: PersonRepository::class)]
class Person
{
#[Id]
#[GeneratedValue]
#[Column(type: Types::INTEGER)]
private int $id;
#[Column(type: Types::STRING, length: 255)]
private string $firstName;
#[Column(type: Types::STRING, length: 255)]
private string $lastName;
/** @var Collection<Person> */
#[ManyToMany(targetEntity: self::class, inversedBy: 'guestsHosted')]
private Collection $hosts;
/** @var Collection<Person> */
#[ManyToMany(targetEntity: self::class, mappedBy: 'hosts')]
private Collection $guestsHosted;
public function __construct()
{
$this->fellowshipHosts = new ArrayCollection();
$this->fellowsHosted = new ArrayCollection();
}
// getters/setters ommitted for brevity
public function addHost(self $host): self
{
}
public function removeHost(self $host): self
{
}
public function addGuestsHosted(self $guestHosted): self
{
}
public function removeGuestsHosted(self $guestsHosted): self
{
}
What I would like to achieve is a form with a collection of addable/removable rows, where the user then is able to add a row, select an existing other person as their host, add another row, select another person, and so on. A simple mockup:
How do I achieve this using Symfony’s form-component? What I have in there now does not work due to recursion on the same form-type:
class PersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('firstName', null, [])
->add('lastName', null, [])
->add('hosts', CollectionType::class, [
'entry_type' => self::class,
'entry_options' => ['label' => false],
'required' => false,
'allow_delete' => true,
'allow_add' => true,
'by_reference' => false,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Person::class,
]);
}
}
NB: I’ve built similar UIs like this in the past and know about the little dance involving form.vars.prototype
and hooking up the JS to that. Where I’m lost is how to map this association on the form-level, so that I get a dropdown of all Persons, and map that into the $hosts
property of the entity.
Any help is appreciated!
Why are my Symfony Router are not Working?
I am currently creating a Symfony Project for School and i was just trying some things out with this Security Bundle… I was creating the Registration Controller with this php bin/console make:registration-form
Command and it worked out fine. The Files got created and i got no Errors but when i am trying to go to /register
they just show me my index.php
all the time… if i delete index.php its always # Page not Found
from my Symfony Local Server… Im just testing out so im just using this localhost Webserver from Symfony. I tested out the Route with php bin/console router:match /register
and it showed green, it works and exists. But when i try going to the Site nothing happens.
namespace AppController;
use AppEntityUser;
use AppFormRegistrationFormType;
use AppRepositoryUserRepository;
use AppSecurityEmailVerifier;
use DoctrineORMEntityManagerInterface;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentMimeAddress;
use SymfonyComponentPasswordHasherHasherUserPasswordHasherInterface;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyCastsBundleVerifyEmailExceptionVerifyEmailExceptionInterface;
class RegistrationController extends AbstractController
{
private EmailVerifier $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address('[email protected]', 'Julian Schaefers'))
->to($user->getUserIdentifier())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
return $this->redirectToRoute('_profiler_home');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
#[Route('/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
{
$id = $request->get('id');
if (null === $id) {
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
// @TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Your email address has been verified.');
return $this->redirectToRoute('app_register');
}
}
How to generate TLV Zakat, Customs Compatible QR Code in PHP Codeigniter
I need help in creating Zatca Compatible QR Code in PHP Codeigniter. The government requires us to create QR Code fields encoded in Tag-Length-Value (TLV) format.