I use WAMP and ever since I have learned PHP, I have been running my php scripts by going on the webpage itself to see the output. For example, to see the output on a script called script.php, I go on localhost/script.php.
Is there a better way to do this? I mean, in Java there's Eclipse and you can just click the green button and it'll run the code for you and see immediate output. Is there something like this for PHP?
It is possible to run PHP scripts from the command line without a web server. To do this add the following logic to your script:
if (defined('STDIN')) {
if (isset($argv)){
// handle your command line arguments here with getopt
}
}
// GET request parameter definitions //
else {
// handle your URL parameters (via GET or POST requests) here
}
When the script is run from the command line with the PHP interpreter
php myfile.php -s --longflag <argument>
STDIN is defined and you can handle command line switches, flags, and arguments with getopt in the if block.
The script reaches the else block when you access it by URL on a web server. The PHP code that you currently have can be placed in that block.
Here's an example from one of my projects that demonstrates how to handle the URL parameters as short or long command line options:
// Command line parameter definitions //
if (defined('STDIN')) {
// check whether arguments were passed, if not there is no need to attempt to check the array
if (isset($argv)){
$shortopts = "c:";
$longopts = array(
"xrt",
"xrp",
"user:",
);
$params = getopt($shortopts, $longopts);
if (isset($params['c'])){
if ($params['c'] > 0 && $params['c'] <= 200)
$count = $params['c']; //assign to the count variable
}
if (isset($params['xrt'])){
$include_retweets = false;
}
if (isset($params['xrp'])){
$exclude_replies = true;
}
if (isset($params['user'])){
$screen_name = $params['user'];
}
}
}
// Web server URL parameter definitions //
else {
// c = tweet count ( possible range 1 - 200 tweets, else default = 25)
if (isset($_GET["c"])){
if ($_GET["c"] > 0 && $_GET["c"] <= 200){
$count = $_GET["c"];
}
}
// xrt = exclude retweets from the timeline ( possible values: 1=true, else false)
if (isset($_GET["xrt"])){
if ($_GET["xrt"] == 1){
$include_retweets = false;
}
}
// xrp = exclude replies from the timeline (possible values: 1=true, else false)
if (isset($_GET["xrp"])){
if ($_GET["xrp"] == 1){
$exclude_replies = true;
}
}
// user = Twitter screen name for the user timeline that the user is requesting (default = their own, possible values = any other Twitter user name)
if (isset($_GET["user"])){
$screen_name = $_GET["user"];
}
} // end else block
I find this to be helpful for testing. Hope it helps.
Jetbrains PHP storm is a good debugging tool
If you use Sublime Text as text editor you can use XDebug
Related
I am opening two windows in one session, which should have different behaviours. As the windows open at the same time, they are using th same options and interfering with each other. Therefore I would need to check in the code, how they were opened.
If it was opened with something like
window.open(href, target='pdf');
I would want to check this
if(tab.target = "pdf")
{
$check_target = 1
}
else
{
$check_target = 2
}
now "tab.target" does not exist - can I achieve this somehow?
Thanks!
Max
I would add a something to the url like this:
window.open(href+'?mytarget=pdf', target='pdf');
Then in your php code:
if($_GET['mytarget'] == "pdf")
{
$check_target = 1;
}
else
{
$check_target = 2;
}
My script is working most of the times, but in every 8th try or so I get an error. I'll try and explain this. This is the error I get (or similar):
{"gameName":"F1 2011","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/81163/movie_max.webm?t=1447354814","gameId":"44360","finalPrice":1499,"genres":"Racing"}
{"gameName":"Starscape","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/900679/movie_max.webm?t=1447351523","gameId":"20700","finalPrice":999,"genres":"Action"}
Warning: file_get_contents(http://store.steampowered.com/api/appdetails?appids=400160): failed to open stream: HTTP request failed! in C:\xampp\htdocs\GoStrap\game.php on line 19
{"gameName":"DRAGON: A Game About a Dragon","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/2038811/movie_max.webm?t=1447373449","gameId":"351150","finalPrice":599,"genres":"Adventure"}
{"gameName":"Monster Mash","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/900919/movie_max.webm?t=1447352342","gameId":"36210","finalPrice":449,"genres":"Casual"}
I'm making an application that fetches information on a random Steam game from the Steam store. It's quite simple.
The script takes a (somewhat) random ID from a text file (working for sure)
The ID is added to the ending of an URL for the API, and uses file_get_contents to fetch the file. It then decodes json. (might be the problem somehow)
Search for my specified data. Final price & movie webm is not always there, hence the if(!isset())
Decide final price and ship back to ajax on index.php
The error code above suggests that I get the data I need in 4 cases, and an error once. I only wanna receive ONE json string and return it, and only in-case $game['gameTrailer'] and $game['final_price'] is set.
This is the php (it's not great, be kind):
<?php
//Run the script on ajax call
if(isset($_POST)) {
fetchGame();
}
function fetchGame() {
$gameFound = false;
while(!$gameFound) {
////////// ID-picker //////////
$f_contents = file("steam.txt");
$url = $f_contents[mt_rand(0, count($f_contents) - 1)];
$answer = explode('/',$url);
$gameID = $answer[4];
$trimmed = trim($gameID);
////////// Fetch game //////////
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed);
$game_json = json_decode($json, true);
if(!isset($game_json[$trimmed]['data']['movies'][0]['webm']['max']) || !isset($game_json[$trimmed]['data']['price_overview']['final'])) {
continue;
}
$gameFound = true;
////////// Store variables //////////
$game['gameName'] = $game_json[$trimmed]['data']['name'];
$game['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
$game['gameId'] = $trimmed;
$game['free'] = $game_json[$trimmed]['data']['is_free'];
$game['price'] = $game_json[$trimmed]['data']['price_overview']['final'];
$game['genres'] = $game_json[$trimmed]['data']['genres'][0]['description'];
if ($game['free'] == TRUE) {
$game['final_price'] = "Free";
} elseif($game['free'] == FALSE || $game['final_price'] != NULL) {
$game['final_price'] = $game['price'];
} else {
$game['final_price'] = "-";
}
}
////////// Return to AJAX (index.php) //////////
echo
json_encode(array(
'gameName' => $game['gameName'],
'gameTrailer' => $game['gameTrailer'],
'gameId' => $game['gameId'],
'finalPrice' => $game['final_price'],
'genres' => $game['genres'],
))
;
}
?>
Any help will be appreciated. Like, are there obvious reason as to why this is happening? Is there a significantly better way? Why is it re-iterating itself at least 4 times when it seems to have fetched that data I need? Sorry if this post is long, just trying to be detailed with a lacking php/json-vocabulary.
Kind regards, John
EDIT:
Sometimes it returns no error, just multiple objects:
{"gameName":"Prime World: Defenders","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/2028642/movie_max.webm?t=1447357836","gameId":"235360","finalPrice":899,"genres":"Casual"}
{"gameName":"Grand Ages: Rome","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/5190/movie_max.webm?t=1447351683","gameId":"23450","finalPrice":999,"genres":"Simulation"}
I'm currently putting together a small web-based GUI to generate kickstart-scripts. I got a confirmation page that's sending the relevant data via POST to the PHP-page where the actual shell script is called to build the iso. So far it's working, but the page seems to execute the script before it outputs anything else (for example, the 'echo' I put in at the beginning of the page ...), and I'm absolutely clueless why. Would anyone care to enlighten me?
Here's the code to the PHP-page that's executing the shell script ...
echo 'Generating your ISO; this might take a while...';
sleep(20);
if (!isset($_POST['auth'])) {
$ad = 'N';
}
else {
$ad = 'Y';
}
if (!isset($_POST['oracle'])) {
$oracle = 'N';
}
else {
$oracle = 'Y';
}
if ((!isset($_POST['ip'])) or (!isset($_POST['hostname'])) or (!isset($_POST['rhsel'])) or (!isset($_POST['submit'])) or (!isset($_POST['gw'])) or (!isset($_POST['nm']))) {
die('Please use the correct form !');
}
if (isset($_POST['ip'])) {
$ip = trim($_POST['ip']);
}
if (isset($_POST['gw'])) {
$gw = trim($_POST['gw']);
}
if (isset($_POST['nm'])) {
$nm = trim($_POST['nm']);
}
if (isset($_POST['hostname'])) {
$hostname = trim($_POST['hostname']);
}
if (isset($_POST['rhsel'])) {
$rhsel = $_POST['rhsel'];
}
passthru("/usr/bin/sudo /data/skripte/webconfig.sh $rhsel $oracle $ad $ip $gw $nm $hostname 2>&1");
PHP scripts accessed via a browser are request-response, meaning all processing is done on the server prior to headers and content being sent to the client. This means you will not get a continually updating output like you would see on the command line. There is no way around this. Sorry.
I don't know how to make this.
There is an XML Api server and I'm getting contents with cURL; it works fine. Now I have to call the creditCardPreprocessors state. It has 'in progress state' too and PHP should wait until the progess is finished. I tried already with sleep and other ways, but I can't make it. This is a simplified example variation of what I tried:
function process_state($xml){
if($result = request($xml)){
// It'll return NULL on bad state for example
return $result;
}
sleep(3);
process_state($xml);
}
I know, this can be an infite loop but I've tried to add counting to exit if it reaches five; it won't exit, the server will hang up and I'll have 500 errors for minutes and Apache goes unreachable for that vhost.
EDIT:
Another example
$i = 0;
$card_state = false;
// We're gona assume now the request() turns back NULL if card state is processing TRUE if it's done
while(!$card_state && $i < 10){
$i++;
if($result = request('XML STUFF')){
$card_state = $result;
break;
}
sleep(2);
}
The recursive method you've defined could cause problems depending on the response timing you get back from the server. I think you'd want to use a while loop here. It keeps the requests serialized.
$returnable_responses = array('code1','code2','code3'); // the array of responses that you want the function to stop after receiving
$max_number_of_calls = 5; // or some number
$iterator = 0;
$result = NULL;
while(!in_array($result,$returnable_responses) && ($iterator < $max_number_of_calls)) {
$result = request($xml);
$iterator++;
}
I was following this tutorial.
I need to use a php file's ouput in my HTML file to dynamically load images into a gallery. I call
function setOutput()
{
if (httpObject.readyState == 4)
document.getElementById('main').src = httpObject.responseText;
alert("set output: " + httpObject.responseText);
}
from
function doWork()
{
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "gallery.php?no=0", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
However, the alert returns the php file, word for word. It's probably a really stupid error, but I can't seem to find it.
The php file:
<?php
if (isset($_GET['no'])) {
$no = $_GET['no'];
if ($no <= 10 && $no >1) {
$xml = simplexml_load_file('gallery.xml');
echo "images/" . $xml->image[$no]->src;
}
else die("Number isn't between 1 and 10");
}
else die("No number set.");
?>
If the alert is returning the contents of the PHP file instead of the results of executing it, then the server is not executing it.
Test by accessing the URI directly (instead of going via JavaScript).
You probably need to configure PHP support on the server.
Your Server doesn't serve/parse PHP files! You could test your JavaScript code by setting the content of gallery.php to the HTML code you want to receive.