I'm yet a newbie to PHP development, so far I used NetBeans for the job. Unfortunately NetBeans is not the best IDE, and it is unreasonably slow on my Mac.
I'd like to use Eclipse PDT for PHP, as I know and like Eclipse a lot better (I'm coming from Java).
But I cannot set up a server in Eclipse... All docs and topics just showed ppl saving files in the htdocs folder of an external server (such as MAMP or XAMPP). As I don't need a database, I just want to use PHP's built-in server instead of installing and running a heawyweight app in vain.
I'd like to reproduce the only really good thing in NetBeans: I just click on the Run button, and I see the result in the Browser immediately.
How do you set that up?
Even if I am a bit late to help you, I want to write down my solution, cause I've faced the same problem today.
I think the only chance is to start the php built-in webserver manually. Open a terminal in the desired root directory and start the webserver with
php -S localhost:8000
Then you can add a new server with Base URL: http://localhost:8000 and the choosen document root and you'll have the same functionality like in Netbeans.
Put together this hackety-hack-hack to make this work (even works with xdebug remote debugging if you set it up!!!).
UPDATE: one caveat with this solution is when you terminate the running CLI in Eclipse, it's terminating the wrapper script, not the php server directly. I've added some trapping and forawding of signals to child (php server) process. Works in OSX.
Overview:
I'm running Eclipse Neon
Need a router file in document root you wish to serve from (see this: http://php.net/manual/en/features.commandline.webserver.php)
Create a wrapper bash script to call PHP in server mode and pass in details
Set script to have executable permissions
Add this bash script as a PHP executable
For the project, create a run configuration as PHP CLI, using this new executable, passing the router file in.
Here's the bash script php5.6-server:
#!/bin/bash
_sigterm() {
echo "Caught SIGTERM signal!"
kill -2 "$child"
}
_sigint() {
echo "Caught SIGINT signal!"
kill -14 "$child"
}
if [ $1 = "-v" ]; then
#This is needed for when eclipse trys to detect php version
/path/to/php -v
else
trap _sigterm SIGTERM
trap _sigint SIGINT
# This is why your router file needs to be in the doc root
ROUTER=${#: -1}
DIR=$(dirname $ROUTER)
/path/to/php -S localhost:8000 -t $DIR $ROUTER
child=$!
wait "$child"
fi
Here's a simple router.php just to get it working:
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} else {
echo "<p>Welcome to PHP</p>";
}
Now in Eclipse go to Eclipse->Preferences->PHP->PHP Executables and add a new server:
And that should be it. Now create a PHP CLI Run configurations using the wrapper executable as 'Alternate PHP' and for the php file specify the route file:
Then Run as CLI!!! A PHP server should now be listening on port 8000 on your localhost. I suspect this method may also work for HHVM's Proxygen server.
Related
I'm trying to add debugging to an old project that uses exec() to start a new session asynchronously from within another PHP script:
exec("php /var/www/html/validata/index.php",$result)
The normal PHP script is fully debugable with Xdebug but the script started with the exec command isn't because it can't map from file:///var/www/html/index.php to a local file location since it's started within CLI shell. The session started this way does trigger the debugger but can't find the file locally:
Cannot find file '/var/www/html/validata/index.php' locally.
To fix it set server name by environment variable PHP_IDE_CONFIG and restart debug session.
I've followed the instructions to add the PHP_IDE_CONFIG to the env. I've also added this to the server with 127.0.0.1 replaced with the desktop PC IP address (server is running in a docker container):
export XDEBUG_CONFIG="remote_enable=1 remote_mode=req remote_port=9000 remote_host=127.0.0.1 remote_connect_back=0"
Any pointers are greatly appreciated!
UPDATE
Solution:
Use the cli interpreter set to the docker container (in settings > Languages & Frameworks > PHP > CLI interpreter, add new, select docker and point it to the php binary) so that a debug session can be started with a new debugging configuration. I've copied the arguments from the exec command into the new configuration and it can now fully debug the script. I have to prepare a database table to make it fully testable but this is a working solution for me.
Thanks for all the replies!
You can solve the issue about the wrong php.ini file being loaded by specifying it in the command line:
exec("php -c " . escapeshellarg(php_ini_loaded_file()) .
" /var/www/html/validata/index.php",$result);
Though I doubt that would make much of a difference as far as xdebug is concerned.
I think a better solution would be to just require the file, which would cause xdebug to not become lost when you fork a new process.
require_once "/var/www/html/validata/index.php";
I've made a mistake how to refer to the server in PHP_IDE_CONFIG:
export PHP_IDE_CONFIG="serverName=SomeName"
should be run in the container where php runs, and SomeName should exactly match what is in PHPStorm/IntelliJ Settings > Languages & Frameworks > php > Servers > Name (not host). It's not a fqdn, just whatever is in the name field.
I am working on a webapp made by someone else which uses Bottle routing. I want to create a simple login page which requires some PHP. If I return the PHP page as a static_file, any HTML will be executed but PHP won't, for obvious reasons. How should I serve the PHP file so that it is dynamic?
Not working:
#route('/login')
def serve():
return static_file('login.php', root='.')
In order to server PHP files, you need to have PHP installed on the web server. Additionally, the webserver needs to be configured to detect PHP files and execute them.
Serving PHP files from Python is kinda useless and not recommended.
I'd recommend you to take the time to translate this script from PHP to Python.
I wanted to do the same thing yesterday, but the answers I got to my question made it clear it was either impossible or extremely difficult. I came up with writing a small python program to run the PHP built in server. NOTE: PHP needs to be able to run from the command line for this to work.
#Import the os package so that this code can run commands
import os
#Get the port that the user wants to host on
port = str(input("What port would you like to host on?"))
#Add wanted port to the command that hosts the php server
cmd = "php -S localhost:" + port
#Actually run the command to host php server
os.system(cmd)
#Now the PHP server will take over until you
#use ctrl + C to quit hosting
Just remember that the port needs to be 4 numbers. When you host this, you can return any file from the folder you ran this code in by simply typing it in the browser. Example:
localhost:8080/login.php
Returns login.php (if it is there) on the localhost port that you asked for.
I'm debugging my PHP app on CentOS7 using Apache.
My application is a Web GUI to manage the Torque batch system and I used the qmgr, which is a command line tool provided by Torque to do the management work.
Because only the root user can execute the qmgr and the Apache server cannot be running as root user, I have written a C program as a wrapper for anyone to execute commands as root user.
But the PHP application always give the following output:
socket_connect_unix failed: 15137
qmgr: cannot connect to server (errno=15137) could not connect to trqauthd
This means the PHP app cannot raise a socket connection to connect the Torque server.
Here is some additional information:
The command called by the PHP application can be executed correctly in the shell
The same PHP app can be executed correctly on a CentOS6 server with Apache
SELinux and the firewall are disabled
I have tried the two versions (5.1 and 4.10) of Torque, the result is the same
Apache and PHP are used with the default RPM's of CentOS7.
I thought there are some new security limits that maybe influence Apache on the CentOS7 server.
Please give me some suggestions, thank you!
I had the exact same problem.
The cause is that newer Apache.httpd versions default to having the systemd property PrivateTmp set to true. This causes the httpd service to see a private /tmp directory that is actually mapped to some other location in the file system, instead of the real /tmp directory. PHP, running in the Apache process, has the same /tmp directory as the Apache service, and so do any processes forked from PHP (e.g. using exec or system etc). So when PHP calls qsub (etc), that too will see the private /tmp directory.
This causes the error you mentioned because qsub internally uses the unix socket /tmp/trqauthd-unix to communicate with trqauthd. But qsub sees the "fake"/private /tmp directory instead of the real one, so it doesn't find the socket.
This explains why the command works when you run it manually in a console--in that case, qsub sees the real /tmp directory, as opposed to the private one it sees when forked from PHP (running the Apache service).
One solution is to simply change the PrivateTmp property in the file httpd.service from true to false. You can find this file under the /etc/systemd directory. The subfolder it is in probably depends on the linux distribution, so use the find command to locate it:
find /etc/systemd -name httpd.service
This really helped me!
I have been struggling a lot having a php script using exec()-command. For some reason I got permission denied. Having tried vary many things, including running my scripts in shell as the www-data user, but with no success, this was finally the solution to my problem.
BTW, for Ubuntu the apache service config file is located at cat /etc/systemd/system/multi-user.target.wants/apache2.service
I've installed Apache 2.4 with PHP 5.4 on Windows Server 2008 following instructions from this manual:
Apache installing manual.
Apache runs as a service now.
My application requires a php websocket script to run in the background. I'm running it manually with:
php myscript.php
The question is: Is there a way to start a background script automatically on system(apache) restart?
I found the following topic, but I didn't know where I could find an apache startup script for Windows.
Any help will be much appriciated.
I come up with a solution :)
Create an environment variable pointing to your Apache directory
APACHE_HOME = C:/PATH/TO_APACHE
Rename %APACHE_HOME%\bin\httpd.exe to %APACHE_HOME%\bin\httpdVendor.exe
Create a batch file and put the following code :
php myscript.php
%APACHE_HOME%\bin\httpdVendor.exe -k runservice
exit 0
Download/Install the free software BatToExeConverter (next, next, ...)
Open the installed converter and open your freshly created batch file
Click on the button Build EXE (let the default configuration)
Save the file : %APACHE_HOME%\bin\httpd.exe
Start your Apache Server
Tested on : Windows 7, Apache 2.4, Advanced Bat to Exe Converter 2.92
Use built in Windows Task Scheduler which triggers .bat script, which calls curl with defined url.
Download curl from http://curl.haxx.se/download.html and extract curl.exe on any directory, but we will use c:\backgroundtasks
Adjust script below to your needs:
cd c:\
cd c:\backgroundtasks
curl http://localhost/path/to/script.php
exit
Configure Task Scheduler to run as basic task:
General tab - as system account (to run when you are not logged in server)
Triggers tab - adjust frequency
Settings tab - at bottom set If the task is already running... to Stop the existing instance
The best method here would be to use Windows services dependencies.
Make a php-websocket-server.cmd file with any necessary environment settings (e.g. changing to a directory, setting PATH, etc...) with the last line:
php myscript.php
Install the Windows Server Resource Kit Tools, to get srvany and instsrv to create a user defined service. Note the install path as you'll need it in the next step.
Open a cmd shell and run:
<path_to_resource_kit>\instsrv PHPWebSocketServer <path_to_resource_kit>\srvany.exe
Next, create a file php-websocket-server.reg containing the following (update for your environment):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PHPWebSocketServer\Parameters]
"Application"="c:\\path\\to\\php-websocket-server.cmd"
Import it by double-clicking or regedit /s php-websocket-server.reg
Back in your cmd shell:
sc config Apache2.4 depend= PHPWebSocketServer
to make the Apache2.4* service depend on your php service. Now, when Apache is started, the php service will be brought up first. And likewise, if you stop the php service Apache will stop along with it.
*the howto indicates that the service is named "Apache2.4" but you may want to verify in your installation.
When running as service, you won't have the startup script.
Execute some service implementation that allows running other programs as services, and then make the new service (which is running your script) a dependency of the Apache service. However, this will not restart the script when apache restarts.
One possible solution using SrvStart, and another using ServiceEx.
Perhaps don't install Apache as a service, and then edit the startup/restart script, and use the above method to run Apache as service (instead of using Apache's own installer).
Create bat file,e eg 'myphp.bat' containing path/php myscript.php. Include the correct path to php if it's not path'd.
create a bat file, eg runmyphp.bat containing
AT 00:00 /every:M,T,W,Th,F "cmd /c /path/myphp.bat", again including the correct path.
Then use explorer to drag runmyphp into the startup folder, so it will always run on system startup.
Google 'windows at command' or 'windows cron' to get all the correct syntax for the 'at' command, but you can currently find a detailed explanation here.
I found another answer C:\wamp\scripts\wampserver.lib.php this file is run every time when your wamp starts
include your file path include_once("file_path"); to this file and its done . this is perfect solution which you want
Enjoy!!!!!!!!!
Although the solution of Halayem Anis is very creative, I think its important to note that you can never be sure that a PHP script keeps running in the background. So if you choose to start your script on "Apache start", then you probably end op resetting Apache quite often, simple to reboot your script.
I assume that's even how you came to this question, as on a normal server you never have to touch the Apache reset button. It starts on system start and then it just runs. If that was the case, you could simple run your php myscript.php command on start up.
Considering there is no way to make sure the script keeps running, I would use a different approach, where I check if it is running and if not, restart it.
So the first step is to make it possible to track if the script is running. I would go for the simple approach where your myscript.php writes a single byte to a file every 5seconds or so. This way I can use the last modified time on the file to see if it is still running, because last modified time + 5 seconds < now == not running.
You could also store the last access time in a database every 5 seconds or so. Might be slightly faster then accessing files if you have a lot of traffic.
The second part is to have each request check if the script is running. For this two work I would use the PHP.ini to prepend a php script on every request. You can do it with the auto_append_file option.
This prepend script would work like this:
<?php
$filename = 'checkonline.txt';
$cmd = "php myscript.php";
if (filemtime($filename)+5<time()) {
//run in background without freezing php
//based on code posted on PHP exec manual, linked below
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
?>
Make sure to check how filemtime and exec work and what you need to keep in mind. They work slightly different on Windows/*nix.
Wrap-up all your required processes in a batch file and use RunAsService
With some tweaking, you can ensure that your service starts before Apache.
I'm attempting to run an application on the server, invoking it from PHP using the following code.
$application = "D:\\Program Files (x86)\\ScanBoy\\DM ScanBoy.exe";
exec($application);
Right now the application is 'run' however it crashes instantly. If I just run the application (by double clicking the exe) it runs and everything is fine.
When the application crashes the only error I get is
"{application name} has stopped working. Windows is checking for a
solution to the problem"
I have had this problem with running application via c# backend to a ASP.NET page. The solution there was to set the Working Directory. However in php / exec I am unaware of how to set this option.
Any help please?
You can either:
Use exec("cd myworkdir/ && D:\\Program Files (x86)\\ScanBoy\\DM ScanBoy.exe"); to change the working directory for that exec command (only)
Use the php chdir() function to change the working directory of the php process.
You can find chdir documentation here:
http://php.net/manual/en/function.chdir.php
You can chdir() to change current working directory