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

Saturday, November 26, 2022

[FIXED] How to execute node command in a node app?

 November 26, 2022     command-line-interface, module, node.js     No comments   

Issue

So basically, I'm trying to make a cli to automate some little task that I'm repeating all the time. And here I want to replace the console.log by something that will run the command instead. I tried with the exec from 'child_process' but it didn't work and i ended with an infinite loader

switch (arg) {
    case "React App":
      console.log(`npx create-react-app ${projectName}`);
      console.log(`cd ${projectName}`);
      console.log(`npm start`);
      break;
    case "Next App":
      console.log(`npx create-next-app@latest ${projectName}`);
      console.log(`cd ${projectName}`);
      console.log(`npm dev`);
      break;

This is the version with the exec

 switch (arg) {
case "React App":
  () => exec(`npx create-react-app ${projectName}`);
  () => exec(`cd ${projectName}`);
  () => exec(`npm start`);
  break;
case "Next App":
  () => exec(`npx create-next-app@latest ${projectName}`);
  () => exec(`cd ${projectName}`);
  () => exec(`npm dev`);
  break;

I searched on many forums and also on stack overflow and I think the fact that I'm not an english native speaker has never been that obvious cause damn I didn't find what i wanted


Solution

run it sequentially with execSync

const execSync = require('child_process').execSync;

//...
switch (arg) {
    case "React App":
        console.log(`npx create-react-app ${projectName}`);
        execSync(`npx create-react-app ${projectName}`);
        console.log(`cd ${projectName}`);
        execSync(`cd ${projectName}`);
        console.log(`npm start`);
        execSync(`npm start`);
        break;
    case "Next App":
        console.log(`npx create-next-app@latest ${projectName}`);
        execSync(`npx create-next-app@latest ${projectName}`);
        console.log(`cd ${projectName}`);
        execSync(`cd ${projectName}`);
        console.log(`npm dev`);
        execSync(`npm dev`);
        break;
}


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

Monday, November 14, 2022

[FIXED] What is the best way of handling error in rust? (CLI with clap)

 November 14, 2022     clap, command-line-interface, error-handling, rust     No comments   

Issue

I'm trying to develop a simple cli bill manager in rust using clap. I want to let the user add new bills by entering its name and value, remove some bills, and I also want to add undo and redo features. As it is my first project in rust, I called it p1. In the terminal, the user must do like this:

p1 -n bill1 -v 50

And then, the bill will be added or

p1 undo 5

Then, the last 5 actions will be undone. But, because of the usual functioning of clap, at least as far as I understood, this behavior is also accepted:

p1 -n bill2 -v 30 redo 30

And I don't want to allow it. I don't want to let the user use flags and subcommands at the same time. So I made some validation. To make it easier for you to help me I will show the pertinent part of the code.

use clap::{Parser, Subcommand};
use std::{collections::HashMap, path::PathBuf};
use home::home_dir;
use std::fs;


#[derive(Parser, Debug)]
struct Args {
    /// The name of the bill
    #[clap(short, long, value_parser)]
    name: Option<String>,
    /// The value of the bill
    #[clap(short, long, value_parser)]
    value: Option<u32>,
    #[clap(subcommand)]
    command: Option<Commands>,
}


#[derive(Subcommand, Debug)]
enum Commands {
    /// Undo
    Undo { undo: Option<u32> },
    /// Redo
    Redo { redo: Option<u32> },
    /// Remove
    Remove { remove: Option<String> },
}

fn validate_args(args: Args) -> Result<Args, String> {
    match (&args.name, &args.value, &args.command) {
        (Some(_), Some(_), None) => Ok(args),
        (None, None, Some(_)) => Ok(args),
        (None, None, None) => Ok(args),
        _ => Err("You can't use options and subcommands at the same time".to_string())
    }
}


fn exit_on_error(error: &Result<Args, String>) {
    println!("{:?}", error);
    panic!("aaaaaaaaaaaaaaaaaa");
}


fn main() {
    let args: Result<Args, String> = validate_args(Args::parse());
    match args {
        Ok(_) => (),
        Err(_) => exit_on_error(&args)
    };
    ...
}

Another thing I need help is. When the user do not insert neither flags nor subcommands, just typing "p1" in the terminal, I want to redirect him to the help subcommand as if he had typed

p1 help

How can I do it?

And also, I'm still not used to the rust style of handle with variable possession. The "exit_on_error" function can only receive borrowed results because, apparently, strings cannot implement Copy. This prevents me to unwrap the Err before printing it, which makes it appears with quotation marks in the terminal. What should I do to workaround It?

Please help me and let me know if something isn't clear in my question.


Solution

I'd agree with @SirDarius that you probably shouldn't do this, but eh, doesn't mean it hurts to know how you could do it:

When the user do not insert neither flags nor subcommands, just typing "p1" in the terminal, I want to redirect him to the help subcommand as if he had typed p1 help

If knowing whether any arguments were passed at all from the parsed Args is difficult, you can for example sidestep clap and check the argument count from std::env::args()

if std::env::args().count() <= 1 {
    Args::parse_from(&[
        // Argument 0 is always the program name.
        // Could just use "p1" here, but this is more generic:
        std::env::args()
            .next()
            .as_ref()
            .map(String::as_str)
            .unwrap_or(env!("CARGO_CRATE_NAME")),
        // as if help was typed:
        "help",
    ]);
    unreachable!("Should print help and exit");
}

I think you can also use clap's ArgGroups to achieve this kind of behaviour, but I find them to be clunky.

And also, I'm still not used to the rust style of handle with variable possession.

This is a classic Rust problem, and there's so many things you could do:

  1. Just exit from validate_args directly. It's what Args::parse does, too.
  2. Use let args = match args { Ok(args) => args, Err(e) => exit_on_error(e) }; (Must change the type of exit_on_error for this.)
  3. Make exit_on_error have type fn(Result<Args, String>) -> Args and move the match into it.
  4. Make main return Result<(), Box<dyn std::error::Error>> so you can use ? to unwrap Results (though you would need to choose a different error type with a nice Display implementation type instead of String. Might as well use the anyhow crate.)
  5. Use error.as_ref().err().unwrap() (You could even add Option::cloned to have an owned copy of the error string.)

Lastly: One question per question on StackOverflow, please.



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

Thursday, October 6, 2022

[FIXED] Why does apt-get consume stdin when it installs something but not otherwise?

 October 06, 2022     buffer, command, command-line-interface, shell, terminal     No comments   

Issue

I am connected to a remote Debian system via macOS Terminal.

Command after apt-get never runs if apt-get installs something

At first, I copy these three commands from a text file on my macOS and paste it into the terminal with a single command+v press:

sudo apt-get -y remove tree
sudo apt-get -y install tree
echo hi

Here is what I see in the Terminal.

lone@lone:~$ sudo apt-get -y remove tree
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Package 'tree' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 17 not upgraded.
lone@lone:~$ sudo apt-get -y install tree
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  tree
0 upgraded, 1 newly installed, 0 to remove and 17 not upgraded.
Need to get 0 B/46.1 kB of archives.
After this operation, 106 kB of additional disk space will be used.
Selecting previously unselected package tree.
(Reading database ... 31853 files and directories currently installed.)
Preparing to unpack .../tree_1.7.0-5_amd64.deb ...
Unpacking tree (1.7.0-5) ...
Setting up tree (1.7.0-5) ...
Processing triggers for man-db (2.7.6.1-2) ...
lone@lone:~$ 

The third command, echo hi, was never executed. Why?

Command after apt-get does run if apt-get does not install anything

Next time, I simply paste these two commands with a single command+v press:

sudo apt-get -y install tree
echo hi

This time, since tree is already installed, apt-get does not need to install it again. This is the output I see:

lone@lone:~$ sudo apt-get -y install tree
Reading package lists... Done
Building dependency tree       
Reading state information... Done
tree is already the newest version (1.7.0-5).
0 upgraded, 0 newly installed, 0 to remove and 17 not upgraded.
lone@lone:~$ echo hi
hi

This time echo hi was executed. Why?

Both results are reproducible every time I perform these two sets of operations. Why does the echo hi command not run in the first example but does in the second example?


Solution

apt-get or a program called by apt-get is emptying its stdin (which happens to be the same as the shell's, where your list of commands originates).

Since you know nothing needs to be to read from the user, redirect stdin from /dev/null:

sudo apt-get -y remove tree </dev/null
sudo apt-get -y install tree </dev/null
echo hi


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

Sunday, August 21, 2022

[FIXED] How do I get rid of jenv in Ubuntu?

 August 21, 2022     command-line-interface, environment-variables, jenv, ubuntu     No comments   

Issue

I think I need to undo some commands I entered when trying to get jenv on my ubuntu instance and I am not sure how to do that.

Here's what I did:

brew install jenv

echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile

echo 'eval "$(jenv init -)"' >> ~/.bash_profile

jenv add /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

That last command gave me an error, and I ended up restarting my shell for whatever reason. Since then, all text is white (used to be multicolored), brew no longer works, and it says this:

Command 'jenv' not found, did you mean:

command 'env' from deb coreutils (8.30-3ubuntu2)

Try: sudo apt install

Couldn't find an alternative telinit implementation to spawn. user@DESKTOP-FG073RE:/mnt/c/Users/user$

I fear I messed up the PATH but I am not sure how to fix it. I tried to run the same command again but omitting the 'j' but that did nothing. Can't seem to find anything about this error online either. I also tried to uninstall jenv but that also did nothing.


Solution

I went into the ~/.bash_profile I made and deleted everything from it



Answered By - notnoahkirby
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 15, 2022

[FIXED] How to print out only the number of eslint errors in the terminal?

 August 15, 2022     command-line-interface, console, eslint, output, terminal     No comments   

Issue

The project I'm working with has a huge code-base, which means that if I do eslint *.js in the terminal, I get thousands of lines in the output. I want to tweak this command only to print out the number of errors, not to actually list all the errors one by one.

What to do to make my results similar to this:

96 problems

Solution

Thinking a bit more, if you really just want a single number, then create your own formatter that would look something like this.

const errorsInFile => (el, currentEl) => el + currentEl.errorCount

module.exports = function (results) {
  return `${results.reduce(errorsInFile, 0)} problems`
}

Or just for fun, we could do it functionally with Ramda

import { map, pipe, prop, reduce, sum } from 'ramda'

const sumArgs = (...args) => sum(args)
const nProblems = n => `${n} problems`

module.exports = pipe(
  map(prop(‘errorCount’),
  reduce(sumArgs),
  nProblems,
)


Answered By - David Bradshaw
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 22, 2022

[FIXED] How can I run an exec file that ouputs a csv without using `--user` in Mac?

 July 22, 2022     command-line-interface, exec, pyinstaller, python     No comments   

Issue

I created an executable on my Mac that runs Python code. It creates a csv file.

When I run the file on its own without freezing it using Pyinstaller, it works fine on both Windows and Mac. Then, when I do freeze it, it works fine, but it won't output the csv file on Mac (it does on Windows).

It will only work if I run the exec file in the CLI with --user.

I've already tried giving it permissions in the System Preferences, and in the Sharing & Permissions section of the info window. To no avail.

Is there anything I may have overlooked that others may know about?

Thanks, in advance!


Solution

It turns out that the file was being output in the user folder and not in the same folder as the exec file.

For those of you working on Python scripts and freeze them using Pyinstaller, remember that files that you output are placed in your user folder on Mac.



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

Tuesday, July 12, 2022

[FIXED] How to move multiple messages in mutt

 July 12, 2022     command-line-interface, email, message, mutt     No comments   

Issue

Before all of my messages were in one maildir. Now I want move all arch-general mail to another one.

From here, I see:

"move" as we know it from other places is "save" in mutt. 
"save" as we know it from other places is "copy" in mutt.

~e EXPR         message which contains EXPR in the ``Sender'' field

so I use pattern in index

'T'  and  '~e arch-general' then  's'

but just one message moved.

How can I move all pattterned messages to another dir?


Solution

;s

;     tag-prefix     apply next function to tagged messages


Answered By - Paul Yin
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 6, 2022

[FIXED] PHP - execute web script as command line script?

 March 06, 2022     command-line-interface, facebook, facebook-php-sdk, php     No comments   

Issue

Using PHP version 5.4.28, what I'm trying to accomplish is:

  • A facebook app I have is script "otherevent.php". It should not be publicly visible to any user. It is a backend app that is on the web server, due to Facebook requiring it to have a web address, and the app is run and managed by other scripts.

  • The first script I have to run and manage the app is called "app.php". Ideally all it's supposed to do is execute "otherevent.php", get the output, and echo the output to the screen.

  • Craziness ensues in the form of "unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING" errors, amongst other things.

I have comments and code here for three test files, "otherevent.php", "app.php", and "test.php" which is a test file used for debugging the errors. Here goes:

test.php:

echo $argv[1] . " TADA!";
exit();

?>

otherevent.php (trimmed down and censored, for sensitive information):

require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookServerException.php' );
require_once( 'Facebook/FacebookOtherException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphSessionInfo.php' );
require_once( 'Facebook/GraphUser.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookServerException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
use Facebook\GraphUser;


  // Get session variable!
session_start();
$output = array(
);
// Initialize the app with the app's "secret" and ID. These are private values.
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxx','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );

$arg1 = $_SESSION['arg1']; //This is a password variable that tells the script it's being run by an authorized script on the server, not by an outside source.
$arg2 = $_SESSION['arg2']; //This is an argument that tells the script what it's supposed to be trying to do.
if($arg1 != "whatever"){
    echo"Something went wrong; the password variable didn't work.";
    //The following line is what is -supposed- to happen when this codeblock executes, but we're debugging right now, so we're providing output instead to see what happens in the code.
    //header("Location: http://www.fantasycs.com/app.php");
}elseif($arg2 == "loginurl"){
    echo "It worked! Login URL will be displayed here.";
    unset($_SESSION['arg2']);
    unset($_SESSION['arg1']);
    exit();
}
?>

And finally, app.php:

<?php

session_start();
$_SESSION['arg1'] = "whatever";
$_SESSION['arg2'] = "loginurl";

$output = shell_exec('php-cli test.php Thisworks'); //This runs test.php and $output captures the output properly just fine. No worries.

echo $output;


$output = shell_exec('php test.php Thisworks'); //This keeps running indefinitely so far as I can tell, and I can't see what's happening because no output is produced. It simply keeps trying to load the page forever. No output is seemingly capture. Bizarre.

echo $output;


$output = shell_exec('php otherevent.php'); //This has the same problem as when you try to run test.php with the "php" command. It stalls.

echo $output;


$output = shell_exec('php-cli otherevent.php Thisworks'); //This produces an error on the "use" lines in otherevent.php. It says there's a syntax error on those lines. This has never happened or appeared before; these lines, simply put, do NOT have any errors in them. They've run fine before and have never been changed. As a result of the error, the script is aborted, and no output is captured.

echo $output;

?>

All I want in this instance is for app.php to be able to execute otherevent.php, get the login URL (or whatever test output it outputs), and print the login URL to the screen. How does one do that? Apparently it's not as simple as it seems.


Solution

Your error using php-cli around the 'use' keywords leads me to believe you have an old version of PHP.. but to address one part of your question, I suggest not using shell_exec for running other PHP code.. If you need to capture the output of the script, you can use an output buffer like this:

<?php

session_start();
$_SESSION['arg1'] = "whatever";
$_SESSION['arg2'] = "loginurl";

// Start capturing the output in a buffer
ob_start();
include 'otherevent.php';    
// Get the data and close the buffer
$output = ob_get_clean();
echo $output;

?>

There's no point to the output buffer if you're going to echo the output immediately afterwards.

Check your version of PHP. That SDK requires 5.4+.



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

Saturday, March 5, 2022

[FIXED] Fatal error: Maximum execution time of 300 seconds exceeded

 March 05, 2022     command-line-interface, php     No comments   

Issue

I keep getting this PHP error:

Fatal error: Maximum execution time of 300 seconds exceeded

I have tried setting my max_execution_time and my max_input_time settings in php.ini (both apache and cli) to 0, -1 and 4000 seconds each.

And i still get the error saying:

Fatal error: Maximum execution time of 300 seconds exceeded

As well my script runs over 300 seconds before i get this message

I am running the script through command line.

I also checked my phpinfo() so see which php.ini I am using.

Even more interesting I have tried setting max_execution_time and max_input_time settings to 5 second and my script will run way beyond 5 seconds before I get the:

Fatal error: Maximum execution time of 300 seconds exceeded


Solution

At the beginning of your script you can add.

ini_set('MAX_EXECUTION_TIME', '-1');


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

Sunday, February 20, 2022

[FIXED] How to converts the string to alternate upper and lower case in php (Laravel Zero)?

 February 20, 2022     command-line-interface, input, laravel, php, string     No comments   

Issue

i am working on Laravel Zero and created new command that will display the user input to show in uppercase and lowercase.

is there a way to also display the output alternate upper and lower case?

here is the command:

class UppercaseCommand extends Command
{
/**
 * The signature of the command.
 *
 * @var string
 */
protected $signature = 'converts';

/**
 * The description of the command.
 *
 * @var string
 */
protected $description = 'Converts the string to uppercase, lowercase, and alternate';

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $a = readline('Enter a string: ');
    echo "Output in uppercase: " , strtoupper($a). PHP_EOL;
    echo "Output in lowercase: " , strtolower($a);
}

/**
 * Define the command's schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
public function schedule(Schedule $schedule): void
{
    // $schedule->command(static::class)->everyMinute();
}
}

so how can i add new line to show the input for example like this: "hElLo wOrLd"?


Solution

The Answer:

$chars = str_split($a);
    foreach($chars as $char){
        if ($UpperLowerSwitch){
            
            echo strtolower($char);
            $UpperLowerSwitch = false;
        }else {
            echo strtoupper($char);
            $UpperLowerSwitch = true;
        }
    }

Output(if the user insert "hello world"):

hElLo wOrLd


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

Saturday, February 12, 2022

[FIXED] Silence PHP cURL output in CLI

 February 12, 2022     codeigniter, command-line-interface, curl, php     No comments   

Issue

I am working on a scraper (in PHP) and use cURL to fetch pages. The script can be run both in CLI & browser. This is my first time working with PHP on CLI and I was trying to make the screen pretty and have a nice data representation like scrape statistics show up.

I am able to generate the output the way I want it, well almost. But with every cURL request the server makes, it also outputs this the extra header information like this :

* About to connect() to imbd.com port 80 (#0)
*   Trying 123.111.222.333... * connected
> GET /categories/something.html HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20130401 Firefox/21.0
Host: imdb.com
Accept: */*

< HTTP/1.1 200 OK
< Server: nginx/1.4.1
< Date: Wed, 25 Dec 2013 02:17:06 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept-Encoding
< X-Powered-By: PHP/5.3.17
< Set-Cookie: mobileType=0%something; expires=Wed, 01-Jan-2014 02:17:06 GMT; path=/; domain=.imdb.com
< 
* Connection #0 to host imdb.com left intact
* Closing connection #0
...
Statistics
...

Function that uses cURL

    public function getHTML($url) 
    {
        $user_agent = "Mozilla/5.0 (Windows NT 5.1; U; zh-cn; rv:1.9.1.6) ...";
        
        $options = Array(
            CURLOPT_RETURNTRANSFER => TRUE,  
            CURLOPT_FOLLOWLOCATION => TRUE,  
            CURLOPT_AUTOREFERER => TRUE,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_USERAGENT => $user_agent,
            CURLOPT_URL => $url,
        CURLOPT_VERBOSE => true,
        CURLOPT_SSL_VERIFYPEER => false,
        );
        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

Now all I want to do is hide this information from the CLI as it does in the browser. Had it been cli curl, i would use -s to shut it up. But I am unable to find an PHP alternative for this. Also, CURLOPT_MUTE is depreciated. All Google gave me was to set CURLOPT_RETURNTRANSFER true, which I already have.

Also I would like to know how can I avoid setting any cookies to avoid tracking.

If it helps in any way I am using

  • OS : Ubuntu
  • Software : PHP5.5
  • Framework : CodeIgniter 3.0-dev
  • Extension: cURL
  • Interface : Command Line (Terminal)

Solution

Remove this.

CURLOPT_VERBOSE => true,

According to php manual

Set value to

TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.



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

Tuesday, February 8, 2022

[FIXED] How to update Laravel Installer "laravel/installer" to latest version?

 February 08, 2022     command-line-interface, composer-php, installation, laravel, php     No comments   

Issue

I tried to update my laravel/installer using the command:

composer global update laravel/installer

But it only upgraded its minor version (assuming that it uses Semantic Versioning).

Package operations: 0 installs, 1 update, 0 removals
  - Updating laravel/installer (v2.1.0 => v2.3.0): Downloading (100%)

Then I execute the update command again:

composer global update laravel/installer

But outputs:

Nothing to install or update

I now uses PHP 7.4.4 (cli) obtained using php -v so I assume that it should be able to upgrade to latest which is Laravel Installer 3.0.1.


Solution

If running composer global update laravel/installer is not enough to upgrade the the desired version, there might be package dependencies that restricts the upgrade to the latest.

I do not know if there is a composer option to do that on global scope but the following commands works for me:

# uninstall the package
composer global remove laravel/installer

# reinstall
composer global require laravel/installer

The 1st process outputs the outdated packages dependencies that are removed with the laravel/installer package.

Then the 2nd process installs the latest laravel/installer with the updates dependencies.

Laravel documentation does not include how to update the installer package yet.


Update: Adding Documentation link on how to update a composer package.

composer require specific version documentation.

php composer.phar require "vendor/package:2.*" vendor/package2:dev-master

As we can see, specific version could be supplied after the colon.

https://getcomposer.org/doc/03-cli.md#require



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

Monday, January 17, 2022

[FIXED] PHP Composer, command line (CLI) to add a class path to autoload PSR-4 / PSR-0 / file in composer.json

 January 17, 2022     autoload, command, command-line-interface, composer-php     No comments   

Issue

Does Composer have any Command from CLI to add to composer.json such entry?

{
    "autoload": {
        "psr-4": {
            "Monolog\\": "src/",
            "Vendor\\Namespace\\": ""
        }
    }
}

and add this:

{
    "autoload": {
        "psr-0": {
            "Monolog\\": "src/",
            "Vendor\\Namespace\\": "src/",
            "Vendor_Namespace_": "src/"
        }
    }
}

and this

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}

and this:

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

I looked here: Composer Command Line Documentation

but haven't found any dedicated command. Perhaps there is a workaround command like:

composer add-entry <key> <value>

or

composer set-key <key> <value>

but I don't know such, do you know any?


Solution

Unfortunately NO. 😢 At least in v1.8.4 and I also want this feature too.

I thought the closest command would be config.

$ composer config bin-dir bin/
$ composer config repositories.github.com '{"type": "vcs", "url": "https://github.com/[YOUR]/[REPO]", "//url": "https://github.com/[YOUR]/[REPO].git"}'

Since this will add the following in composer.json:

"config": {
    "bin-dir": "bin/"
},
"repositories": {
    "github.com": {
        "type": "vcs",
        "url": "https://github.com/[YOUR]/[REPO]",
        "//url": "https://github.com/[YOUR]/[REPO].git"
    }
}

Though, this command seems to work only for "config" and "repositories" keys.

And then I found an issue about this topic. Seems that the community won't add this feature.😭

Yup I don't think we really want to offer this from CLI it's gonna be a bunch of code for very limited use as typically this is done once on package creation.

  • From: Issue #3398
    • "[Feature] Adding processing autoloading sections to the command line interface" @ GitHub


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

Saturday, January 15, 2022

[FIXED] PHP MAMP and server conflicts

 January 15, 2022     command-line-interface, mamp, php     No comments   

Issue

I have a page that calls a php script. On MAMP everything works fine but when I upload it to a server I get the following error:

Call Request failed! Status code: 4000
Reason - Caught an HttpRequestValidationException due to some bad characters in the request. Make sure your post request is encoded as xml, preferable as UTF-8 ('Content-Type: text/xml; charset=utf-8'). Exception: A potentially dangerous Request.Form value was detected from the client (<?xml version="..."utf-8"?> <uclassify xmlns="ht...").

Has anyone seen anything like that?

you can check it yourself here just place a word like php or ios


Solution

It looks like your server is validating based on the content-type header. It seems to want text/xml, whereas you are sending application/x-www-form-urlencoded (which is the default for $.ajax).

Try explicitly setting the content type to text/xml in your $.ajax call. (reference)



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

Sunday, January 9, 2022

[FIXED] CLI MAMP PHP running slowly compared to OS X PHP

 January 09, 2022     command-line-interface, mamp, php     No comments   

Issue

Ive just started to encounter a problem with MAMP PHP running extremely slowly. Ive reinstalled MAMP and still having issues.

As a comparison (I thought maybe my local development OS X machine may have been having issues) i tried the following in terminal, and disabled php.ini with -n

/usr/bin/php --version -n

This returns with an output immediately.

/Applications/MAMP/bin/php/php5.5.14/bin/php --version -n 

This returns an output approx 3-5 seconds later.

I have tried running numerous other commands and scripts. All seem to have a delay of 3-5 seconds with MAMP PHP.

I have tried other MAMP PHP versions, and they still have the same issues.

I can't think of anything that has changed recently on my machine to cause this slow down (e..g no php.ini changes, no OS X updates)

I really have no idea whats causing this problem, or even how to investigate things further. Help greatly appreciated.

UPDATE

Strangely, the problem only seems to be when running MAMP PHP in command line. When loading a website using MAMP, there is no slow down. Even more confusing...


Solution

Solved. For some reason -n was not removing the .ini files. Deleting the .ini file altogether solved the issue.

Some googling lead me to the extension causing the issue. I commented out the following line in my .ini file

; extension=imap.so


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

Friday, January 7, 2022

[FIXED] How to call a class method of a composer package from PHP CLI?

 January 07, 2022     class, command-line-interface, composer-php, methods, php     No comments   

Issue

I tried to get it with the following command :

php -r 'require("./vendor/autoload.php");packagename\ClassName::myStaticMethod();'

but got :

Parse error: syntax error, unexpected end of file in Command line code on line 1

Any ideas? Thank you.


Solution

With your package packagist.org/packages/thipages/jsbuild

php -r "require './vendor/autoload.php';thipages\jsbuild\JSBuild::writeBuildModel();" is working on windows, switching " and '.



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

Sunday, January 2, 2022

[FIXED] Laravel 5 – Clear Cache in Shared Hosting Server

 January 02, 2022     command-line-interface, laravel, laravel-5, php     No comments   

Issue

The question is pretty clear.

php artisan cache:clear

Is there any workaround to clear the cache like the above command but without using CLI. I am using a popular shared hosting service, but as per my plan, I don't have control panel access.

I want to clear the views cache.

I saw a question almost the same like this, but it doesn't help me.


Solution

You can call an Artisan command outside the CLI.

Route::get('/clear-cache', function() {
    $exitCode = Artisan::call('cache:clear');
    // return what you want
});

You can check the official doc here http://laravel.com/docs/5.0/artisan#calling-commands-outside-of-cli


Update

There is no way to delete the view cache. Neither php artisan cache:cleardoes that.

If you really want to clear the view cache, I think you have to write your own artisan command and call it as I said before, or entirely skip the artisan path and clear the view cache in some class that you call from a controller or a route.

But, my real question is do you really need to clear the view cache? In a project I'm working on now, I have almost 100 cached views and they weight less then 1 Mb, while my vendor directory is > 40 Mb. I don't think view cache is a real bottleneck in disk usage and never had a real need to clear it.

As for the application cache, it is stored in the storage/framework/cache directory, but only if you configured the file driver in config/cache.php. You can choose many different drivers, such as Redis or Memcached, to improve performances over a file-based cache.



Answered By - Marco Pallante
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

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