Rectangle 27 35

Are you sure the script doesn't contain any errors? This is what normally makes "execution terminates very quickly". First, append error_reporting(E_ALL); ini_set('display_errors', 1); at the top of your script to display any errors it may have, then you can use:

nohup php filename.php &

nohup runs a command even if the session is disconnected or the user logs out.

nohup php filename.php >/dev/null 2>&1 &

Same as above but doesn't create nohup.out file.

ignore_user_abort(1);

Set whether a client disconnect should abort script execution

set_time_limit(0);

Limits the script maximum execution time, in this case it will run until the process finishes or the apache process restarts.

php
filename.php
/usr/bin/php
/full/path/to/filename.php

Would echo statements cause the script to terminate if there is no output redirection?

linux - Running PHP script from command line as background process - S...

php linux command-line
Rectangle 27 2

UPDATED After few research, best solution was to use that info another stackoverflow thread to avoid ctrl+z input and also from the scree output. So, instead of php -a you should use call "php.exe" -f NAMED_SCRIPT.php

OLD Readline not possible under Windows, so none of existent php shells written in php will work. But there's a workaround using -a interactive mode.

2 commmon problems here. You cannot see result until executes CTRL Z command to indicate the final of code/file like EOF. When you do, result in most cases is printed result and fast closed window. Anyway, you will be returned to cmd not the -a interactive mode.

Save this content into a .bat file, and define your PHP PATH into Windows variables, or modify php.exe to "full path to exe" instead:

::
:: PHP Shell launch wrapper
::
@ECHO off
call "php.exe" -a

echo.
echo.

call "PHP Shell.bat"

This is a simple Batch launching -a mode of php.exe. When it launchs php, stop script even no pause is wrote because is "into" the interactive waiting for input. When you hit CTRL Z, gets the SIGSTEP (next step) not the SIGSTOP (close, CTRL+C usually), then read the next intruction, wich is a recursive call to .bat itself. Because you're always into PHP -a mode, no exit command. You must use CTRL+C or hit the exit cross with mouse. (No alt+f4)

How To Run PHP From Windows Command Line - Stack Overflow

php windows shell command-line wamp
Rectangle 27 18

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=yourusename" -F "j_password=yourpassword"  <NEWURL>

php - Is there a way to follow redirects with command line cURL - Stac...

php redirect curl command-line-interface
Rectangle 27 18

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

For me the obstacle was that the page required a login and then gave me through java script a new URL. Here is what I had to do:

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=yourusename" -F "j_password=yourpassword"  <NEWURL>

php - Is there a way to follow redirects with command line cURL - Stac...

php redirect curl command-line-interface
Rectangle 27 47

You can use sed with something like sed '1 s/^.*$/?php/' The 1 part only replaces the first line. Then, thanks to the s command, it replaces the whole line by ?php. To modify your files in-place, use the -i option of GNU sed. share|improve this answer edited Jan 29 '17 at 10:59 Stefan van den Akker 3,63262640 answered Feb 16 '12 at 10:52 Scharron 9,84513260
<!--

sed, replace first line - Stack Overflow

sed
Rectangle 27 4

I just recently ran into this same problem in trying to run phpunit from the command line in git bash on windows 7. After conducting some research into possible various solutions I decided to share the solution I chose to implement for myself, here.

You can filter out the ANSI color control characters from git bash. Create a file named phpunit (note: the actual phpunit script wasn't in my path and I was mainly running unit tests from intellij only) and put it anywhere in your $PATH (I prefer ~/bin myself but there's no rule about that):

#!/bin/sh
/path/to/phpunit "$@" 2>&1 | perl -pe 's/(?<=\e\[)2;//g'

The "$@" tells bash to take the rest of the arguments passed to the script and forward them to phpunit. The 2>&1 redirects stderr to stdout, ensuring that any control characters generated in producing error output will also be filtered out.

Finally, all of the output produced by phpunit is piped through perl and run through the regular expression 's/(?<=\e\[)2;//g', which strips out the control characters.

The end result is that phpunit runs just fine, regardless of what <phpunit colors="" setting you are using.

php - What is wrong with control characters in PHPUnit command line to...

php command-line windows-xp phpunit
Rectangle 27 23

I have much easier solution for you - it is simple! Just add this command at the very start of the php source:

ob_start();

This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time! So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)

Great work - this worked exactly as hoped, many thanks!

PHP Page redirect problem - Cannot modify header information - Stack O...

php redirect error-handling http-status-code-301
Rectangle 27 23

I have much easier solution for you - it is simple! Just add this command at the very start of the php source:

ob_start();

This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time! So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)

Great work - this worked exactly as hoped, many thanks!

PHP Page redirect problem - Cannot modify header information - Stack O...

php redirect error-handling http-status-code-301
Rectangle 27 7

If you have Laravel 5 and looking permanent solution , applicable both php artisan command line usage and Apache server use this:

sudo chmod -R 777 vendor storage
echo "umask 000" | sudo tee -a /etc/resolv.conf
sudo service apache2 restart

php - 'Failed to open stream: Permission denied' error - Laravel - Sta...

php exception laravel laravel-4
Rectangle 27 2

Following a discussion in chat, one solution using PHP as a command line script would look like this -

#! /usr/bin/php 
<?php

    $options = getopt("f:r:");
    $inputFile = $options['f'];
    $replacement = $options['r'];
    // read entire contents of input file 
    $inputFileContents = file_get_contents($inputFile);
    // setup the regex and execute the search
    $pattern = '/.*link.*href=["|\']?(.*[\\\|\/]?.*)\.css["|\']?.*/';
    preg_match_all($pattern, $inputFileContents, $matches);
    // remove last occurance of regex 
    // these are the lines we'll want to hang onto
    $matchedLines = $matches[0];
    array_pop($matchedLines);
    // isolate the last css file name
    $matchedFileName = array_pop($matches[1]);
    // first substitution replaces all lines with <link> with 
    // an empty string (deletes them)
    $inputFileContents = str_replace($matchedLines,'',$inputFileContents);
    // second substitution replaces the matched file name
    // with the desired string
    $inputFileContents = str_replace($matchedFileName,$replacement,$inputFileContents);
    //*/
      // save to new file for debugging
      $outputFileName = "output.html";
      $outputFile = fopen($outputFileName,'w+');
      fwrite($outputFile,$inputFileContents);
      fclose($outputFile);
    /*/
      // save changes to original file
      $origFile = fopen($inputFile,'w+');
      fwrite($origFile,$inputFileContents);
      fclose($origFile);
    //*/
    exit();
?>

You would execute this script from the command line like so -

$ php thisScript.php -f "input.html" -r "hello-world"
  • -f is the input file that we are parsing.
  • -r is the replacement string for the css file name (in this example "hello-world").

If you don't want to read through all of it, Lix went out of his way to explain quite a bit to me and his solution results in the exact functionality of what the script needed to do. Now the fun part, porting it from PHP to perhaps a grep/sed or grep/sed/awk version.

fclose
fclose($outputFile);
fwrite...

regex - I'm trying to write a shell script to replace a few lines of t...

regex bash shell sed
Rectangle 27 7

If you're using PHP with GD support, you can try getimagesize().

GD will probably suffer from the same speed issue, since it will load the image in memory...

True. I don't know way other than writing it yourself and storing only part of the image in memory at a time, but this would be dependent on the image type.

Fastest way to determine image resolution and file type in PHP or Unix...

php image png imagemagick jpeg
Rectangle 27 4

identify -ping filename.png

Good call, it's about 20 times faster :) The description of that option makes me wonder why it's not the default behavior of identify? Anyway, problem solved and many thanks.

Fastest way to determine image resolution and file type in PHP or Unix...

php image png imagemagick jpeg
Rectangle 27 2

NOTE: I have just read your comment, and as I can understand you don't have access to command line. Please check Solution Two, this will definitely work.

The only solution that will work for you (which work for me at 12GB database) is directly from the command line:

mysql -u root -p

set global net_buffer_length=1000000; --Set network buffer length to a large byte number

set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number

SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays, errors and unwanted behavior

source file.sql --Import your sql dump file

SET foreign_key_checks = 1; --Remember to enable foreign key checks when the procedure is complete!

If you have root access you can create bash script:

#!/bin/sh 

# store start date to a variable
imeron=`date`

echo "Import started: OK"
dumpfile="/home/bob/bobiras.sql"

ddl="set names utf8; "
ddl="$ddl set global net_buffer_length=1000000;"
ddl="$ddl set global max_allowed_packet=1000000000; "
ddl="$ddl SET foreign_key_checks = 0; "
ddl="$ddl SET UNIQUE_CHECKS = 0; "
ddl="$ddl SET AUTOCOMMIT = 0; "
# if your dump file does not create a database, select one
ddl="$ddl USE jetdb; "
ddl="$ddl source $dumpfile; "
ddl="$ddl SET foreign_key_checks = 1; "
ddl="$ddl SET UNIQUE_CHECKS = 1; "
ddl="$ddl SET AUTOCOMMIT = 1; "
ddl="$ddl COMMIT ; "

echo "Import started: OK"

time mysql -h 127.0.0.1 -u root -proot -e "$ddl"

# store end date to a variable
imeron2=`date`

echo "Start import:$imeron"
echo "End import:$imeron2"

Also, there is another option which is very good for those who are on shared hosting and don't have command line access. This solution worked for me on 4-5GB files:

  • MySQL Dumper: Download (You will able to backup/restore SQL file directly from "MySQL Dumper" you don't need phpmyadmin anymore).
  • Big Dump: Download (Just restore from Compress file and SQL file, need BIGDUMP PHP file editing for big import $linespersession = 3000; Change to $linespersession = 30000;)

This solution definitely works, it is slow but works.

Download Trial version of (32 or 64 bit): Navicat MySQL Version 12

Install -> and RUN as Trial.

After that Add your Computer IP (Internet IP, not local IP), to the MySQL Remote in cPanel (new database/hosting). You can use wildcard IP in cPanel to access MySQL from any IP.

Goto Navicat MySQL: click on Connection put a connection name.

In next "Hostname/IP" add your "Hosting IP Address" (don't use localhost). Leave port as it is (if your hosting defined a different port put that one here).

Now on the Main Screen you will see all the database connected with the username on the left side column.

Icon color of the database will change and you will see "Tables/views/function etc..".

Now right click on database and select "Execute SQL file" (http://prntscr.com/gs6ef1). choose the file, choose "continue on error" if you want to and finally run it. Its take some time depending on your network connection speed and computer performance.

I have tried this 2nd solution also but it will failed in between the download or return only half data

@Narayan try "MySQL Dump" with <code>$linespersession = 30000;</code>, i have just added the solution# 3 try this as well.

php - How to make a copy of large database from phpmyadmin? - Stack Ov...

php mysql database phpmyadmin cpanel
Rectangle 27 3

Sorry I can't add this as a comment to a previous answer but I don't have the rep. Doing some quick and dirty testing I also found that exec("identify -ping... is about 20 times faster than without the -ping. But getimagesize() appears to be about 200 times faster still.

So I would say getimagesize() is the faster method. I only tested on jpg and not on png.

$files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG');
foreach($files as $file){
  $size2 = array();
  $size3 = array();
  $time1 = microtime();
  $size = getimagesize($file);
  $time1 = microtime() - $time1;
  print "$time1 \n";
  $time2 = microtime();
  exec("identify -ping $file", $size2);
  $time2 = microtime() - $time2;
  print $time2/$time1 . "\n";
  $time2 = microtime();
  exec("identify $file", $size3);
  $time2 = microtime() - $time2;
  print $time2/$time1 . "\n";
  print_r($size);
  print_r($size2);
  print_r($size3);
}

But does GD provide a way to determine a file type according to its contents (and not its assigned extension)? Also you have to measure the time taken to load the image into GD too, as I'm not doing any processing other than determining the file size.

I've added the test to my answer. I don't know if GD loads the image file completely into memory or not as I'm not watching memory. But I am catching the complete time it takes for the command to run. Also getimagesize() also returns the mime type.

Thanks for all the efforts, I've tested it live and it's indeed 250 times faster than the -ping solution. So about 5000 times faster than the original method I was using, not bad :)

Fastest way to determine image resolution and file type in PHP or Unix...

php image png imagemagick jpeg
Rectangle 27 2

nohup php file.php > /dev/null 2>&1 &

The greater-thans (>) in commands like these redirect the programs output somewhere. In this case, something is being redirected to /dev/null, and something is being redirected to &1

There are three standard sources of input and output for a program. Standard input usually comes from the keyboard if its an interactive program, or from another program if its processing the other programs output. The program usually prints to standard output, and sometimes prints to standard error. These three file descriptors (you can think of them as data pipes) are often called STDIN, STDOUT, and STDERR.

Sometimes theyre not named, theyre numbered! The built-in numberings for them are 0, 1, and 2, in that order. By default, if you dont name or number one explicitly, youre talking about STDOUT.

the command above is redirecting the standard output to /dev/null, which is a place you can dump anything you dont want, then redirecting standard error into standard output (you have to put an & in front of the destination when you do this).

The short explanation, therefore, is all output from this command should be shoved into a black hole. Thats one good way to make a program be really quiet!

& at the end puts the command in background.

linux - Running PHP script from command line as background process - S...

php linux command-line
Rectangle 27 2

It's important to me that the file type is determined by looking at the file's headers and not simply the extension.

For that you can use 'file' unix command (orsome php function that implements the same functionality).

/tmp$ file stackoverflow-logo-250.png
stackoverflow-logo-250.png: PNG image data, 250 x 70, 8-bit colormap, non-interlaced

I've just tested this quickly in the command line and it seems quite slow as well, took a good second to determine the file type of the JPG. It does seem to cache the result but that's of little interest, as I'll test the image only once.

Part of it is probably the time it takes to parse the magic file. You can run file on a whole bunch of images at once. Or you could create a smaller magic file with just the common image file types.

Fastest way to determine image resolution and file type in PHP or Unix...

php image png imagemagick jpeg
Rectangle 27 17

Thanks! To save a step for those encountering this for the first time, the full syntax for the Command would be something like: /usr/local/bin/php /home/mydomainusername/public_html/index.php controller method

php - CodeIgniter + Command Line + Cron + Cpanel - Stack Overflow

php codeigniter cron cpanel
Rectangle 27 17

Thanks! To save a step for those encountering this for the first time, the full syntax for the Command would be something like: /usr/local/bin/php /home/mydomainusername/public_html/index.php controller method

php - CodeIgniter + Command Line + Cron + Cpanel - Stack Overflow

php codeigniter cron cpanel
Rectangle 27 552

Needed background on how PHP "integrates" with web servers:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

So PHP-FPM is not threaded? That solves the problem then since Fast CGI is used on nginx servers.

Awesome detail, I have been programming in PHP for years and never knew this.

@Xeoncross: Generally that's correct, and in practice it's one of the great reasons to manage PHP processes outside of Apache. I go over this aspect in my answer.

Is PHP's thread safety still "highly disputed" (in 2015 and version 7) ?

multithreading - What is thread safe or non-thread safe in PHP? - Stac...

php multithreading thread-safety packages threadcontext