PHP get WebKitFormBoundary name and it’s value

------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="username"

james
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="email"

[email protected]
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="language"

en
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="message"

hello world

Is it possible to get the name=”username” and its value “james” and so on like this in below.

username=james&[email protected]&language=en&message=hello world

I know I’m new to programming but I’m trying my best to produce this result but no luck so I’m trying ask here.

The requested resource was not found on this server

create.blade.php

<div class="row mb-3">
    <div class="col-md-12 mb-3">
        <label for="body">Body</label>
        <textarea name="body" id="body" class="form-control"></textarea>
    </div>
</div>

<script src="{{ asset('themes/ckeditor/ckeditor.js') }}"></script>
<script>
    CKEDITOR.replace('body' ,{
        filebrowserUploadUrl : '/admin/upload/image',
        filebrowserImageUploadUrl :  '/admin/upload/image'
    });
</script>

web.php

Route::post('/admin/upload/image', 'AdminController@upload');

AdminController.php

public function upload()
{
    $year = Carbon::now()->year;
    $imagePath = "/admin/upload/image/{$year}/";
    $file = request()->file('upload');
    $filename = $file->getClientOriginalName();
    if (file_exists(public_path($imagePath).$filename)) {
        $filename = Carbon::now()->timestamp.$filename;
    }
    $file->move(public_path($imagePath), $filename);
    $url = $imagePath.$filename;
    return "<script>window.parent.CKEDITOR.tools.callFunction(1, '{$url}', '')</script>";
}

VerifyCsrfToken.php

protected $except = [
    'admin/upload/image'
];

When I upload an image in CKEditor I get this error.

The requested resource /admin/upload/image?CKEditor=body&CKEditorFuncNum=1&langCode=fa was not found on this server.

In PHP file, Summernote is almost funny functional except returning the data from the database displays the HTML tags instead of implementing them

I’m new to stack overflow and I’m still a beginner at PHP/Web Development so please bear with me. I have a simple blogging application that requires 5 forms but only one needs WYSIWYG (description). My PHP should be fine for inserting the actual data:

            // Prepare the query
        $insert_query = "INSERT INTO characters (name,rarity,constellation,affiliation,description, element_id, image_id, url) VALUES (:name,:rarity,:constellation,:affiliation,:description, :element,:id, :url)";

        // Prepare the databaase object
        $statement = $db->prepare($insert_query);
    




        //print_r($sanitized_post); 

        // Bind values to the placeholders
        $statement->bindValue(':name', $sanitized_post['name']);
        $statement->bindValue(':rarity', $sanitized_post['rarity']);
        $statement->bindValue(':constellation', $sanitized_post['constellation']);
        $statement->bindValue(':affiliation', $sanitized_post['affiliation']);
        $statement->bindValue(':description', $sanitized_post['description']);
        $statement->bindValue(':element', $sanitized_post['element']);
        $statement->bindValue(':id', $imageID, PDO::PARAM_INT);
        $statement->bindValue(':url', slug($url));

And the HTML forms for my fields look like this:

 <!-- Main post form -->
<div class="form-group">
<form method='post' enctype='multipart/form-data'>
    <p>
        <label for="name">Name</label>
        <input name="name" id="name" />
    </p>
    <p>
        <label for="rarity">Rarity</label>
        <input name="rarity" id="rarity" />
    </p>
    <p>
        <label for="constellation">Constellation</label>
        <input name="constellation" id="constellation" />
    </p>
    <p>
        <label for="affiliation">Affiliation</label>
        <input name="affiliation" id="affiliation" />
    </p>
    <p>
        <label>Description</label>
        <textarea name="description" id="description" class="form-control"></textarea>
        <script>
    
    $('#description').summernote({
        placeholder: 'Text',
        tabsize: 2,
        height: 100,
        toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']],
      ['insert', ['link', 'picture', 'video']],
      ['view', ['fullscreen', 'codeview', 'help']]
    ]
    });
        </script>
    </p>

On my view.php, my data is returned like so:

   <ul>
   <li>Rarity: <?=$row['rarity']?></li>
   <li>Constellation: <?=$row['constellation']?></li>
   <li>Affiliation: <?=$row['affiliation']?></li>
   <li>Vision: <?=$row['element']?></li>
<h2><?= $row['description'] ?></h2>

But for some reason, on my view.php if I were to type “aaaaa”, it would print out as:

<p>aa<b>a</b>aa</p>

Which is odd, my peers confirm their code is functionally very similar to mine and they didn’t have this issue.

My tag in the HTML includes this:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.js"></script>

Please, any help is appreciated. My summernote is about 90% implemented. This appears to be the final roadblock.

Laravel updating multiple hasMany / belongsToMany relationships

I have inherited a project that has a a few CRUD forms … On the create form we need to create entries for a hasMany and belongsToMany relationship. So basically what i have got is the following

$movie = Movie::create($request->validated());

// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
  // do some data manipulation

  $actor = Actor::where('code', $actor->code)->first();

  $movie->actors()->attach($actor);
}

// Save the hasMany 
foreach ($request['comments'] as $comment) {
  // do some data manipulation

  $movie->comments()->create([
    'title' => $comment['title'],
    'body' => $comment['body'],
  ]);
}

I’m not sure if this is the best way of doing this, but it seems to work.

The problem I am having is that in the edit form, these actors / comments can be edited, added to or deleted and i am unsure of how to go about updating them. Is it possible to update them, or would it be better to delete the existing relationship data and re-add them?

I have never updated relationships, only added them so i am unsure how to even start.

Any help would be greatly appreciated.

Which template file does avada use for the blog post loop

Can someone please point me in the right direction regarding the location of the template file that contains the blogs posts loop I’m using the blog element.

I’ve tried multiple files but it does not work, Would ideally like to add a link after the meta information

Any help would be greatly appreciated.

Kind redards

Property does not exists in template although its assigned

I’m working on a Symfony application to add meter values to a meter. A meter can have a set of measurements, and for each measurement I want to display a value form to enter values.

Fot this I have a function in a controller that creates an ArrayCollection of empty (new) elements depending on the corresponding measurements like so:

/**
 * @Route("/{id}/add", name="metervalue_add", methods={"GET","POST"})
 */
public function add(Request $request, Meter $meter): Response
{
    $metervalues = new ArrayCollection();
    $measurements = $meter->getMeasurements();
    // create an empty metervalue for each measurement of the meter
    foreach ($measurements as $measurement) {
        $mv = new MeterValue();
        $mv->setMeter($meter);
        $mv->setMeasurement($measurement);
        $metervalues->add($mv);
    }
    $form = $this->createForm(MeterValueAddType::class, ['metervalues' => $metervalues]);

    $form->handleRequest($request);

    // ... form submitting stuff
    // ...

    return $this->renderForm('metervalue/add.html.twig', [
        'form' => $form
    ]);
}

The corresponding MeterValueAddType looks like

class MeterValueAddType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('metervalues', CollectionType::class, [
                'entry_type' => MeterValueType::class
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => null,
        ]);
    }
}

When I render the form all works fine, the empty objects are rendered as expected, I can submit the form and all data is inserted correctly in the DB, including measurement and meter ids.
However, in my template I cannot access reference properties of the metervalue object, like metervalues.measurement or metervalue.meter

{% for metervalue in form.metervalues %}
   {{ form_widget(metervalue.value) }}
   {{ form_widget(metervalue.date) }}

   Name of measurement: {{ metervalue.measurement.name }} <-- this throws the following error
{% endfor %}

Error: Neither the property “measurement” nor one of the methods
“measurement()”,
“getmeasurement()”/”ismeasurement()”/”hasmeasurement()” or “__call()”
exist and have public access in class
“SymfonyComponentFormFormView”.

I don’t understand why I can’t access the properties in here just to display them, as they are assigned above in the controller and stored correctly in the DB on save…

The property “measurement” and a correspoding “getmeasurement()” exist and e.g. if I display all saved objects in a list I can access these.

Any hints appreciated!

How to define a RegularExpresion Validation for an Controller Action Param, in TYPO3 v10/v11?

I’m updating an extension for usage in TYPO3 v10 or higher and have an issue with a regular Expression validator, i don’t know how to get in runnable in v10 or higher now. Tried the following:

/**
 * action list
 *
 * @param string $filterChar
 * @ExtbaseValidate("RegularExpression",options={ "regularExpression": "/^[0-9A-Za-z]{0,1}$/i" })
 * @return void
 */
public function listAction(string $filterChar = '') {

But i got the following exception:

Invalid validate annotation in ABCMyExtControllerMyController->listAction(): The following validators have been defined for missing param "$": RegularExpression

What i’m doing wrong and how can i fix it, or what is the correct definition now for a RegularExpression validator for an action parameter?

how to pass data in view with php?

Blockquote
Hello, I will need an experienced look:
I am in training and I rely on a tutorial to carry out a blog project developed in php-> POO-> MVC.

https://www.youtube.com/watch?v=iB4NEbId6kY&list=PLeeuvNW2FHVgfbhZM3S8kqZOmnY7TEorW&index=3

when i switch to my content view, the tutorial uses laravel syntax, and phpstorm gives me an error when i echo my $ content variable in /views/layout.php at the root of my project.
Here are the following files:
enter image description here

PHP Function for get result between two number by entered parameter

I’m thinking about how to write a function for getting a result dependent on a specific range.

See my code:

function($number){
    if($number < 10){
        return 0;
    }else if($number>=10 && $number < 200){
        return customrange($number,10,200,0,200);
    }else if($number>=200 && $number < 1000){
        return customrange($number,200,1000,200,500);
    }else if($number>=1000 && $number < 3000){
        return customrange($number,1000,3000,500,800);
    }
}
function customrange($number,$min,$max,$minResult,$maxResult){
    return '????';
}

I need to fill customrange function for my code to be work but I haven’t any idea.

result of customrange function will be between $minResult and $maxResult parameter depending on how much $number is near to $min and $max

Examples:

customrange(10,10,200,0,200); // Result: 0;
customrange(105,10,200,0,200); // Result: 100;
customrange(200,10,200,0,200); // Result: 200;
customrange(200,200,1000,200,500); // Result: 200;
customrange(600,200,1000,200,500); // Result: 350;
customrange(1000,200,1000,200,500); // Result: 500;
customrange(1000,1000,3000,500,800); // Result: 500;
customrange(2000,1000,3000,500,800); // Result: 650;
customrange(3000,1000,3000,500,800); // Result: 800;

Thanks.

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.

Looking for some WordPress shortcodes to include in php file

I am currently using a neat little plugin from WordPress’ repository called Citationic which displays a little box that generates the correct citation for the individual website to be included in a bibliography. I had a look at the php file and it is quite easy to modify the various templates. However, I am confused how to pull the published date from WordPress.

The APA style is as follows: Organisation. (Publish date). Title. Retrieved Current date, from siteurl.

The php is
$cion_styles = [
“apa” => ‘{sitename}. ({date}). {title}. Retrieved {date}, from {permalink}.’,

Now, my question is to what I have to change the first {date} to display the published date instead of the current date?
I hope that I made myself somewhat clear 🙂

Thanks!