PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label php-7. Show all posts
Showing posts with label php-7. Show all posts

Saturday, November 12, 2022

[FIXED] How to install PHP 7 extension "memcache" on Windows

 November 12, 2022     memcached, php, php-7, php-extension, windows     No comments   

Issue

I'm having huge problems installing memcached extension for php.

Currently using:

OS: Windows 10 x64
PHP: 7.0.1 via XAMPP
Apache: 2.4.18 (Win32)

I have successfully installed memcached in C:/memcached the service is running.

But the problem starts when trying to add the memcache php extension. I've tried numerous versions of php_memcache.dll and non seem to be working.
I did include the extension in php.ini extension=php_memcache.dll

When i run php -m memcache is not listed and at the top i recieve the error:

PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_memcache.dll'
- The specified module could not be found.

And when I try running a test.php for memcache initialization i recive the Class not found exception

This is a huge problem, because I need it for running selenium tests.


Solution

The memcached service doesn't actually install the PHP memcached extension for you. It only installs the memcached server used to store your cache.

You'll need to download the Windows DLL from the PECL repository first (click on the blue Windows DLL link). Then you must add the extension=php_memcache.dll line to the correct php.ini file for your SAPI. Also, note the extension DLL file needs to be placed in the correct path for your XAMPP installation.

For Apache, simply create a script in your document root with the line <?php phpinfo(); and try loading that in your web browser. You should see a line at the top labeled Loaded configuration (php.ini) which gives you the full path to your loaded php.ini file. On Windows the path may actually appear different than what is stated in phpinfo() if you installed PHP through something like XAMPP. So you may need to rely on XAMPP to locate the correct php.ini file.

For the CLI SAPI, you can use php.exe --ini to do the same. Again, you may need to rely on the XAMPP package if it has modified your configuration path (since this is a compile time directive).

After making your changes to php.ini you will need to restart PHP for the changes to take effect.


Since you're using PHP 7 on Windows it's probably also important to note that the compiled DLL from PECL may not actually work under apache for Windows, because you're more than likely using a theaded SAPI. So make sure you are downloading the correct version. As far as I can tell that version is only compiled to work with up to PHP 5.6. The github alternative, for PHP 7, available at https://github.com/nono303/PHP7-memcahe-dll as mentioned in the comments is tested under non-thread safe. So you may only be able to get this working for your CLI scripts on Windows.



Answered By - Sherif
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 10, 2022

[FIXED] How can I Enable Webp support in php GD library in xampp on linux

 October 10, 2022     gd, linux, php, php-7, xampp     No comments   

Issue

I have XAMPP for Linux 7.0.8.

And enabled with GD Support.

screenshot of phpinfo(); about GD

I want to use imagewebp();. I have error while using this,

Fatal error: Uncaught Error: Call to undefined function imagewebp()

while searching for a solution I have concluded with is solution from http://php.net/manual/en/image.installation.php

Image Format | Configure Switch

webp | To enable support for webp add --with-vpx-dir=DIR . Available as of PHP 5.5.

I want to enable webp support.

What I want to do?


Solution

I finally came up with a Solution of Uninstalling XAMPP Application and installing Native LAMP stack server.

Why Because I cannot Recompile PHP in XAMPP. It will be more difficult.

I used My native Linux Apache/PHP installation instead, So I can download source packages and recompile PHP to my needs.



Answered By - GanesH RahuL
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 4, 2022

[FIXED] How to read a excel file with merged cells in php?

 October 04, 2022     ex, php, php-7, phpexcel     No comments   

Issue

I wrote a php script that allows me to read an uploaded excel file and insert all the images contained in a folder by renaming them with the cell values "style" and "color" to have style_color.jpg. The script works fine but if I upload an xlsx file containing merged cells like this:

enter image description here

images with the same "style" doesn't work.The tool will just put the style on the first image. I would like the first two images to be called :

SCJEG4_1041
SCJEG4_0049

How can I read these merged cells?

<?php

//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_images.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);

require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xlsx);

//Unique name folder for the pictures
$dirname = uniqid();
mkdir("C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/");

//reading the xlsx file
$sheet = $objPHPExcel->getActiveSheet();
foreach ($sheet->getDrawingCollection() as $drawing ) {
    
    if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
        ob_start();
        call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
        );
        $imageContents = ob_get_contents();
        ob_end_clean();
        switch ($drawing->getMimeType()) {
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                $extension = 'png'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                $extension = 'gif'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                $extension = 'jpg'; break;
        }
    } else {
        $zipReader = fopen($drawing->getPath(),'r');
        $imageContents = '';
        while (!feof($zipReader)) {
            $imageContents .= fread($zipReader,1024);
        }
        fclose($zipReader);
        $extension = $drawing->getExtension();
        $chemin = "C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/";
    }    
    
    //retrieving cell values for the images name
    $row = (int) substr($drawing->getCoordinates(), 1);        
    $stylecode = $sheet->getCell('H'.$row)->getValue();
    $colorcode = $sheet->getCell('E'.$row)->getValue();
    $finalname = $stylecode.'_'.$colorcode;
    $myFileName = $chemin.$finalname.'.'.$extension;
    file_put_contents($myFileName, $imageContents); 
}

?>

Solution

If you can assume that you read the rows in sequence, you can get the cell value and if the cell is blank, use the previous value. This code use ?: to say if it's blank, use $stylecode ...

$stylecode = $sheet->getCell('H'.$row)->getValue() ?: $stylecode;


Answered By - Nigel Ren
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to copy cell values into other empty cells of a csv file in php?

 October 04, 2022     excel, php, php-7, phpexcel     No comments   

Issue

I have a csv file that contains several empty cells like this : enter image description here

I would like every time the value in the 'Style' column changes that the empty cells take the values of the same style, like this: enter image description here

I don't really see how I will be able to proceed to put the expected values in the cells, if someone could help me it would be a great help...

<?php

//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);

// Excel in CSV
$excel = PHPExcel_IOFactory::load($xlsx);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$nomcsv = "C:/wamp64/www/Extract_pictures_Excel/csv/".date('Ymd_His').".csv";
$writer->save($nomcsv);

$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        //I tried this for if this value changes put back the old ones 
        $data = $data[5] ?: $data[5];
        $csv_data[] = $data;
        $row++;      
    }
    fclose($handle);
}

if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}


?>

Solution

You need to keep track of the previous style, a simple way would be to set it to blank initially and if the element is blank - set it from the previous style. Note that you only should be updating that element of the array (so add [5] to the assignment)...

$prevData = [];
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
    // Overlay current values over the previous values
    $data = array_replace ( $prevData, array_filter($data));
    // Store current data for future use
    $prevData = $data;
    $csv_data[] = $data;
    $row++;
}


Answered By - Nigel Ren
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 20, 2022

[FIXED] How to select PHP version 5 and 7 per virtualhost in Apache 2.4 on Debian?

 September 20, 2022     apache, debian, php, php-7, virtualhost     No comments   

Issue

Would it be possible to run PHP 7 and PHP 5 simultaneously in Apache 2.4 on Debian 9? I would like to be able to select the PHP version I wish to use per virtualhost. I believe this would be useful considering that some of my websites still use deprecated PHP features. This allows me to perform upgrades per site. How do I achieve something like this?

For example

<VirtualHost *:80>
   ServerAdmin webmaster@localhost
   ServerName mywebsite.com
   DocumentRoot /var/www/mywebsite.com

   # UsePHP 7
</virtualHost>

And

<VirtualHost *:80>
   ServerAdmin webmaster@localhost
   ServerName mywebsite2.com
   DocumentRoot /var/www/mywebsite2.com

   # UsePHP 5
</virtualHost>

Solution

Let's start from beginning. I assume that you would prefer to use php-fpm instead of Apache module.

First install apache:

sudo apt-get update
sudo apt-get install apache2

Next install multiple PHP:

Debian 9:
Install PHP 7:

sudo apt-get install php7.0-cli php7.0-fpm php-pear libapache2-mod-fastcgi

Configure repositories:

sudo apt-get install apt-transport-https
sudo curl https://packages.sury.org/php/apt.gpg | apt-key add -
sudo echo 'deb https://packages.sury.org/php/ stretch main' > /etc/apt/sources.list.d/deb.sury.org.list
sudo apt-get update

Install PHP 5:

sudo apt-get install php5.6-cli php5.6-fpm

Debian 8:
Install PHP 5:

sudo apt-get install php5 php5-fpm php-pear libapache2-mod-fastcgi

Configure repositories:
Edit /etc/apt/sources.list and add the following lines to the end of file:

deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all

Install GPG key:

wget https://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
sudo apt-get update

Install PHP 7:

sudo apt-get install php7.0 php7.0-fpm

Next switch from prefork and enable necessary modules:
For Debian 8:

a2dismod php5 mpm_prefork

For Debian 9:

a2dismod php7 mpm_prefork

Next for both:

a2enmod actions fastcgi alias proxy_fcgi mpm_worker
systemctl restart apache2

Change content of /etc/apache2/mods-enabled/fastcgi.conf to the following one:

<IfModule !mod_fastcgi.c>
    AddHandler fcgid-script fcg fcgi fpl
</IfModule>
<IfModule mod_fastcgi.c>
    <Directory /usr/lib/cgi-bin>
        Require all granted
    </Directory>
</IfModule>

Now create document root folders for websites:

mkdir -p /var/www/example.com/public_html
mkdir -p /var/www/test.com/public_html

Add sys users for these websites:

sudo useradd example --home-dir /var/www/example.com
sudo useradd test --home-dir /var/www/test.com

Configure ownership:

sudo chown -R example.example /var/www/example.com
sudo chown -R test.test /var/www/test.com

For example website example.com will use PHP 5 and website test.com will use PHP 7.

Create configuration files for websites:
Website on PHP 5:

touch /etc/apache2/sites-available/example.com.conf
ln -s /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-enabled/example.com.conf
cat /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/example.com/public_html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        <IfModule mod_fastcgi.c>
            AddType application/x-httpd-fastphp5 .php
            Action application/x-httpd-fastphp5 /php5-fcgi
            Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi-example.com
            FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi-example.com -socket /var/run/php5-fpm-example.com.sock -pass-header Authorization
        </IfModule>

</VirtualHost>

Website on PHP 7:

touch /etc/apache2/sites-available/test.com.conf
ln -s /etc/apache2/sites-available/test.com.conf /etc/apache2/sites-enabled/test.com.conf
cat /etc/apache2/sites-available/test.com.conf
<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        ServerName test.com
        ServerAlias www.test.com
        DocumentRoot /var/www/test.com/public_html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        <IfModule mod_fastcgi.c>
                AddHandler php7-fcgi .php
                Action php7-fcgi /php7-fcgi virtual
                Alias /php7-fcgi /usr/lib/cgi-bin/php7-fcgi-test.com
                FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi-test.com -socket /var/run/php/php7.0-fpm-test.com.sock -pass-header Authorization
        </IfModule>

</VirtualHost>

Create pool configs (I used the following):
Website on PHP 5:

cat /etc/php5/fpm/pool.d/example.com.conf
[example.com]
user = example
group = example
listen = /var/run/php5-fpm-example.com.sock
listen.owner = www-data
listen.group = www-data
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_flag[allow_url_fopen] = off
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chdir = /

Website on PHP 7:

cat /etc/php/7.0/fpm/pool.d/test.com.conf
[test.com]
user = test
group = test
listen = /var/run/php/php7.0-fpm-test.com.sock
listen.owner = www-data
listen.group = www-data
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_flag[allow_url_fopen] = off
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chdir = /

Restart apache and php-fpm services:

sudo systemctl restart apache2 php5-fpm php7.0-fpm

Enjoy!



Answered By - Elvis Plesky
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 22, 2022

[FIXED] How to find the Lower and Upper Byte from Hex value in PHP?

 July 22, 2022     php, php-5.4, php-7, php-7.2     No comments   

Issue

I have a series of Hex values like 0x1b12, 0x241B, 0x2E24, 0x392E and I need to calculate the Lower byte and Upper Byte from each of these hex values for further processing. How can I do that? I did a bit of research and saw that there is an unpack function in php but the "format" part in the argument is making me confused. Some of the unpack code that I've seen is added below.

unpack("C*",$data)
unpack("C*myint",$data)
unpack("c2chars/n2int",$data)

As mentioned the aforementioned code, I don't quite understand what "C*","C*myint","c2chars/n2int" does in the unpack function. So I'm not quite sure if I can use unpack as the solution to my problem. Your help is much appreciated.

Thanks in advance.


Solution

You can do this with the pack function. It is easier and faster with Bitwise Operators:

$val = 0x1b12;  //or $val = 6930;

$lowByte = $val & 0xff;  //int(18)
$uppByte = ($val >> 8) & 0xff;  //int(27)

The code needs an integer $val as input. If a string of the form "0x1b12" is available as input, then this must be converted into an integer:

$stringHex = "0x1b12";  //or "1b12"
$val = hexdec(ltrim($stringHex,'0x'));

ltrim is required so that no depreciation notice is generated from 7.4.0 onwards.



Answered By - jspit
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 3, 2022

[FIXED] How to use OCI8 on PHP 7.0 with XAMPP?

 July 03, 2022     oci8, php-7, xampp     No comments   

Issue

I installed the oracle instant client 12, but I can't connect the php with OCI8. I am using XAMPP 32bit and PHP 7.0.15. In my phpinfo() don't show the OCI section. Please, I'm stuck in this problem for a few days. :/ Thanks for all!


Solution

Well, the problem was that XAMPP as well PECL(web site) has the wrong (or outdate) DLL for OCI8. So this link here has the correctly DLLs for PHP.



Answered By - RamonVicente
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 19, 2022

[FIXED] child parent problems with parameters php

 March 19, 2022     cakephp, cakephp-3.0, php, php-7     No comments   

Issue

This is what kind of edit method am I using inside the ChildController.

        public function edit($id = null)
        {
            parent::edit();
            $id = $this->request->data['id'];
            $company = $this->Companies->get($id, [
                'contain' => []
            ]);
            $this->set(compact('company'));
            $this->set('_serialize', ['company']);
        }

And this is what kind of method am I using inside the parent controller.

public function edit()
{
    $model = $this->getCurrentControllerName();
    $editEntity = $this->{$model}->newEntity();
    if ($this->request->is(['patch', 'put'])) {
        $entityData = $this->{$model}->patchEntity($editEntity, $this->request->data);
        if ($this->{$model}->save($entityData)) {
            $this->Flash->success(__('The entity has been saved.'));

            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The entity could not be saved. Please, try again.'));
        }
    }
}

Currently I have a situation in which when I edit, it 'posts' creates another record.

Scenarios that I have already tried:

  1. When I input this before calling the parent action then it gives me the right number. $id = $this->request->data['id']; But then when it goes to parent class it's gone and it says that it is a NULL.

  2. When I put it after calling the parent class it just deletes it and it says that it is a value 'NULL'.

  3. I have also tried to put it inside the parent::action public function edit($id) and with the return $id; with no luck. enter code here I have tried parameter ID to the edit in parent class. It is obvious to me that I am doing something wrong in the parent class, but I don't know what.

Of course, I want obviously to edit/update the only one record inside my application. What am I doing wrong ?


Solution

In your parent function, you aren't doing anything at all with the ID or the existing entity, so little wonder that it's not updating as you want it to.

Something like this, perhaps?

public function edit($id = null)
{
    $company = parent::_edit($id);
    if ($company === true) {
        return $this->redirect(['action' => 'index']);
    }

    // If you use the Inflector class, you could even move these lines into _edit,
    // and perhaps even eliminate this wrapper entirely
    $this->set(compact('company'));
    $this->set('_serialize', ['company']);
}

// Gave this function a different name to prevent warnings
// and protected access for security
protected function _edit($id)
{
    $model = $this->getCurrentControllerName();
    // No need to get the $id from $this->request->data, as it's already in the URL
    // And no need to pass an empty contain parameter, as that's the default
    $editEntity = $this->{$model}->get($id);

    if ($this->request->is(['patch', 'put'])) {
        $entityData = $this->{$model}->patchEntity($editEntity, $this->request->data);
        if ($this->{$model}->save($entityData)) {
            $this->Flash->success(__('The entity has been saved.'));
            return true;
        } else {
            $this->Flash->error(__('The entity could not be saved. Please, try again.'));
        }
    }

    return $editEntity;
}


Answered By - Greg Schmidt
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 22, 2022

[FIXED] CodeIgniter CI_Exceptions::show_exception error after updating to PHP 7

 February 22, 2022     codeigniter, codeigniter-3, php, php-7     No comments   

Issue

I was using CodeIgniter 3.0.0 with PHP 5.6.

Yesterday I updated to PHP 7 and started getting following error:-

Uncaught TypeError: Argument 1 passed to CI_Exceptions::show_exception() must be
 an instance of Exception, instance of Error given, called in /my/file/path/app/system/core/Common.php on line 658 and defined in /my/file/path/hgx_portal/app/system/core/Exceptions.php:190
Stack trace:
#0 /my/file/path/hgx_portal/app/system/core/Common.php(658): CI_Exceptions->show_exception(Object
(Error))
#1 [internal function]: _exception_handler(Object(Error))
#2 {main}
  thrown in /my/file/path/hgx_portal/app/system/core/Exceptions.phpon line 190

Solution

This is a know issue in CodeIgniter 3.0.0, see the github issue here and changelog below:

Fixed a bug (#4137) - :doc:Error Handling <general/errors> breaks for the new Error exceptions under PHP 7.

It's because set_exception_handler() changed behavior in PHP 7.

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

Upgrading to anything beyond 3.0.2 will fix your issue.



Answered By - Garry Welding
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 16, 2022

[FIXED] Handshake between ManyToMany relation created by Symfony's make:entity command

 February 16, 2022     php, php-7, symfony, symfony4     No comments   

Issue

So, can you please clarify to me why the Symfony's command make:entity generates different addProperty methods to a ManyToMany relation?

I spent a few minutes trying to understand why and didn't get yet.

To Exemplify:

Assuming you have these two classes:

  • Language
  • Country
# Now running:
bin/console make:entity Country

# You'll enter in the interactive terminal, just type:
> languages
> ManyToMany
> Language
> yes

These steps will generate the following code in Country class:

    ...
    public function addLanguage(Language $language): self
    {
        if (!$this->languages->contains($language)) {
            $this->languages[] = $language;
        }
        return $this;
    }
    ...

In the Language class you'll get this:

    ...
    public function addCountry(Country $country): self
    {
        if (!$this->countries->contains($country)) {
            $this->countries[] = $country;
            $country->addLanguage($this);
        }
        return $this;
    }
    ...

I'm trying to understand why Language has the line $country->addLanguage($this); and Country doesn't have.


Solution

This is the correct answer:

Remember, all of this owning versus inverse stuff is important because, when Doctrine saves an entity, it only looks at the owning side of the relationship to figure out what to save to the database. So, if we add tags to an article, Doctrine will save that correctly. But, if you added articles to a tag and save, Doctrine would do nothing. Well, in practice, if you use make:entity, that's not true. Why? Because the generated code synchronizes the owning side. If you call $tag->addArticle(), inside, that calls $article->addTag()

Source: https://symfonycasts.com/screencast/doctrine-relations/many-to-many



Answered By - FabianoLothor
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 30, 2022

[FIXED] MVC routing, passing array as parameter (Laravel / CodeIgniter style)

 January 30, 2022     codeigniter, laravel, laravel-5, php, php-7     No comments   

Issue

I am going over a PHP / MVC / OOP course by Traversy Media and I am on a chapter that creates a router for a simple social app (initial routing of any request throguh domain.com/index.php).

The person talks about passing an array as a parameter and I don't get how this works:

class Posts {
   public function edit($id) {
      $post = $this->postModel->fetchPost($id); 
      $this->view('edit', ['post' => $post]);
  }
}

There is some more simple things in this class but I am just not sure about the ['post' => $post] part.

I don't get how this syntax works, like sign after sign. Is this based on something that is already builed in into some kind of framework (he does not have anything like this here, this is his and this is the first chapter when he builds it from scratch). I mean, I would imagine that array would be like an $array, in a variable and this is a parameter in square brackets, so what is the name of the array here?

Is this $post and is the second actual => $post a sub-array. I just dont get that at all.

I started learning Laravel previously (skipping this all together for now) and I've been getting stuck on such things too.

I mean, is this like framework-related only (not really a regular procedural PHP), like something that is already coded on a deeper level and we relate to that?

Thank you in advance for any info that I could get.


Solution

The part you are confused about is just a function call.

$this-view('edit',['post' => $post]);

This could have been written like this

$dataYouWantToPassToTheView = ['post' => $post];

$this->view('edit', $dataYouWantToPassToTheView);

You are calling the function view, and passing it two parameters. An Edit String and an Array containing a key post with a value of a variable called post. The view function simply takes all the values in the array and makes them available by their keys in the view.

This means you can in the view do the following

<span>This is post id: {{ $post->id }}</span>

Passing an Array as a parameter is regular PHP and has nothing to do with the specific framework. The Array doesn't need a "name", just like the 'edit' String doesn't need a name.



Answered By - Nicklas Kevin Frank
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 14, 2022

[FIXED] Filter all find queries on entity CakePHP 3.6

 January 14, 2022     cakephp, cakephp-3.6, php, php-7     No comments   

Issue

let's say that I have an articles database and I want to only display articles that are published on the site (where published = 1). Instead of adding the condition in every find queries like the following:

$articles = $this->Articles->find('all')->where(['published' => 1]);

Is there a way that I can automatically apply this condition on all the find queries in the whole application at one place? If so how?


Solution

You can use beforeFind. This will be fired before every find query on your Article Model. Here is the documentation

Here is how to use it

public function beforeFind($event, $query, $options, $primary)
{

    $query->where(['article.visible' => 1]);

    return $query;
}


Answered By - ascsoftw
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 2, 2022

[FIXED] ActionColumn in yii2

 January 02, 2022     php, php-7, yii, yii2     No comments   

Issue

The ActionColumn have view, update, delete by default.

I want to add a button "made" to mark task as done,( I have a column in db call status that get a int 0 or 1 ), so I want a function that implements the logic to mark the task as done, someone can help me with this ?

This example I get in the forum, but I don't understand very well

[
  'class' => 'yii\grid\ActionColumn',
  'template' => '{view} {update} {delete} {made}',
  'buttons'=> [
    'made' => function () {     
      return Html::button('<span class="glyphicon glyphicon-ok"></span>', [
        'title' => Yii::t('yii', 'made'),
      ]);                                
    }
  ],

Solution

You can do it this way:

[
  'class' => 'yii\grid\ActionColumn',
  'template' => '{view} {update} {delete} {made}',
  'buttons'=> [
    ...
    'made' => function ($url, $model) {
       if($model->status === $model::STATUS_SUSPENDED){
          return Html::a("Activate", $url, [
              'title' => "Activate",
              'class' => 'btn btn-xs btn-success',
              'data' => [
                   'method' => 'post',
                   'confirm' => 'Are you sure? This will Activate this.',
              ],
          ]);
       }
       return Html::a("Suspend", $url, [
          'title' => "Suspend",
          'class' => 'btn btn-xs btn-danger',
          'data' => [
              'method' => 'post',
              'confirm' => 'Are you sure? This will Suspend this.',
          ],
       ]);
     }
  ],
]

Then create method in your controller actionMade() where you check for post request, and perform necessary action on specified id. Hope this will helps.



Answered By - Serghei Leonenco
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing