I am trainee, learning PHP. As a small project I wrote some code.
I am trying to make a (test) website about cars. I want to show that each car has several options. I have a database in MySQL.
I wrote (this is just a part of the code):
foreach ($key['options'] as $options) {
$contents = str_replace("[OPTION]",$options['text'], $contents);
}
$result= '';
foreach ($key['motor'] as $motor) {
$nm = $motor['name'];
$cnt = $motor['count'];
$result .= $cnt ." " .$nm. " ";
}
return $result;
$paginas .= $contents;
echo $paginas;
So far the code. The thing is, after the result code, the script stops (which is normal).
But I don't want that the script stops, the only thing I want is that the final echo also echo's all my return $result options PLUS the echo of '$paginas'.
It is a bit hard to explain maybe, but I hope you guys understand.
Have you read the documentation of the return statement?
return returns program control to the calling module. Execution resumes at the expression following the called module's invocation.
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file.
No matter where it is used, it transfers the control to a different part of the code. The statement(s) following the return statement in the current context are not executed.
I edited the code to echo instead of return. That works.
I made blocks on the website where the information about the car is shown. 1 block per car
The thing is with the $result echo: Now I do not get a list of all different options in 1 block, but I get for every option a new 'block'. so for example:
Block: Steeringwheel. Block:Headlights. Block: Engine type
My goal is to get all these things into 1 block.
Related
Am trying to include two cURL command blocks. The second block depends on a value returned by the first block. I know that there could be network issues in trying to establish cURL calls between servers. The value returned by the first block will be saved in a database. What I want to know is how to write the syntax on the PHP file that will execute both cURL command blocks, so that when the value is returned by the first block I could start the second block, keeping in mind that there could be network problems. I know how to write the cURL command blocks. I just need that part that will avoid network issues. Here is what I was thinking: (inside the PHP file)
$default = "default value";
$a = $default;
//first block executes initializing $a
$a = "value returned by first block. Already saved to database";
//second block can't execute until this value is not set to default value
while($a != $default){
//second block executes
//somewhere to the end of second block
$result = curl_exec($ch); //where $ch is the handle for my cURL call
//exiting the while loop:
if(isset($result))exit(0); //don't know if this is the proper way of exit
//a while loop inside a PHP script
}
Please let me know if this seems to be correct or how can I improve it. One more thing, since I am fairly new to PHP, how do you comment out syntax lines in PHP?
Do you use // as in JAVA?
thank you
cURL is not asynchronous so you don't have to worry about making your code wait for it to finish. That is, PHP will not execute the lines after curl_exec() until the cURL request has completed. Something like this should work for you:
$result = curl_exec($ch);
if($result !== false){
//Do Stuff on successful curl
}
else{
echo curl_error($ch); //print the curl error
}
Also, the way to exit a while loop is break;, if you only want to skip the current iteration, use continue;
i have a long hours working foreach loop which outputs correctly at the end when all items are processed..
foreach ($matches[0] as $map_link) {
if ($map_link!='' && $i < $max_tags ) {
include('reg-process.php');
}
$i++;
}
infact for each $matches[0] which are over 600 matches it includes the
'reg-process.php' page which processes each match in turn and after over one hour it finishes and outputs all results ..
what i need is not to wait till the last item to see results, so while the loop is working after each item is processed it could be echoed..
so again i need every time the loop includes 'reg-process.php' page print out
the result , not to wail up to the last item then all print out at once.. something like continue?
include shouldn't be used in the way you use it, it should be used to include functionality or reduce single file complexity rather than to misuse it as a function. So first of all, get rid of the include as this will lead to problems at some point in time (i.e. you can't include one file multiple times in case it contains functions).
There are different ways to get what you want, here are just two possibilities:
1.) File-based logging:
<?php
// file: register_process.php
function registerProgress($map_link)
{
// YOUR CODE
// ...
// assuming that the result of your code is a string variable that can be logged
file_put_contents('registration.log', $logResult, FILE_APPEND);
}
include('register_progress.php');
foreach ($matches[0] as $map_link) {
if ($map_link!='' && $i < $max_tags ) {
registerProgress($map_link);
}
$i++;
}
2.) Switch to ajax:
in case you are running the script as part of a web application (rather than as console application), you could rewrite your code to execute one page request per map link.
Advantages: you'll get a visible result per executed call, reduced script memory usage, lesser risk of timeouts (due to PHP, webserver or browser timeouts).
Disadvantages: increased page requests and code refactoring required.
ob_flush() will not work as browsers do not parse content of a pending page request; instead you would have to use a network sniffer to read the partial flushed content.
You are not following foreach format with proper syntax. The ideal code are follows-
foreach ($arr as $value) {
$value = $value * 2;
}
Make sure that, $matches[0] is an array. Without array, it will not work. Just rewrite your code, hope will work properly.
Different from the other situations I found here on SO
I have the following code in the main php script
include("sql.php"); //holds all the data to mysql (and variable $db to connect)
$output = shell_exec('/usr/local/bin/php folder/another_script.php')
and in another_script.php I have this:
include_once("../sql.php"); //notice difference to previous include in the other script
$query = "some query";
$db->query($query)
$output in the first script is blank. The second script runs when alone and not called from another script. What am I missing?
The documentation says:
Execute command via shell and return the complete output as a string
It returns the output. You never use the output, hence nothing is shown. You could do this:
$output = shell_exec('/usr/local/bin/php folder/another_script.php')
echo $output;
Yet, I advise you to reconsider your design to create classes or functions to separate functionality instead of calling (quite expensive) shells to call PHP code.
I have a JavaScript functions which calls a PHP function through AJAX.
The PHP function has a set_time_limit(0) for its purposes.
Is there any way to stop that function when I want, for example with an HTML button event?
I want to explain better the situation:
I have a php file which uses a stream_copy_to_stream($src, $dest) php function to retrieve a stream in my local network. The function has to work until I want: I can stop it at the end of the stream or when I want. So I can use a button to start and a button to stop. The problem is the new instance created by the ajax call, in fact I can't work on it because it is not the function that is recording but it is another instance. I tried MireSVK's suggest but it doesn't worked!
Depending on the function. If it is a while loop checking for certain condition every time, then you could add a condition that is modifiable from outside the script (e.g. make it check for a file, and create / delete that file as required)
It looks like a bad idea, however. Why you want to do it?
var running = true;
function doSomething(){
//do something........
}
setInterval(function(){if(running){doSomething()}},2000); ///this runs do something every 2 seconds
on button click simply set running = false;
Your code looks like:
set_time_limit(0);
while(true==true){//infinite loop
doSomething(); //your code
}
Let's upgrade it
set_time_limit(0);
session_start();
$_SESSION['do_a_loop'] = true;
function should_i_stop_loop(){
#session_start();
if( $_SESSION['do_a_loop'] == false ) {
//let's stop a loop
exit();
}
session_write_close();
}
while(true==true){
doSomething();
should_i_stop_loop(); //your new function
}
Create new file stopit.php
session_start();
$_SESSION['do_a_loop'] = false;
All you have to do now is create a request on stopit.php file (with ajax or something)
Edit code according to your needs, this is point. One of many solutions.
Sorry for my English
Sadly this isn't possible (sort of).
Each time you make an AJAX call to a PHP script the script spawns a new instance of itself. Thus anything you send to it will be sent to a new operation, not the operation you had previously started.
There are a number of workarounds.
Use readystate 3 in AJAX to create a non closing connection to the PHP script, however that isn't supported cross browser and probably won't work in IE (not sure about IE 10).
Look into socket programming in PHP, which allows you to create a script with one instance that you can connect to multiple times.
Have PHP check a third party. I.E have one script running in a loop checking a file or a database, then connect to another script to modify that file or database. The original script can be remotely controlled by what you write to the file/database.
Try another programming language (this is a silly option, but I'm a fan of node). Node.js does this sort of thing very very easily.
I have a simple function1 that does a http request to a google api and returns the $result.
I then have another function2 that, if $result isset, should use $result to do some computing and then return $finalresult. .
My problem is that the call to the google api takes a couple of seconds and by the time $result is returned by function1, function2 has already returned $finalresult without taking into consideration $result.
What I am looking to do is to have function1 to run completely and return $result before function2 even begins.
Preferrably I am looking for a solution that is not simply using "sleep()" as this function will not guarantee that $result is actually returned. (Unless there is some way to loop a sleep(1) until $return isset, or something like that)
Sample code for the visual gals and guys
function1_geocode($address); // this function makes a http request to google and returns $result
function2_proximitysearch(){
if (isset($result)){
//inevitably by the time the script gets there, $result hasn't been returned yet therefore none of the "some stuff" code is executed.
//some stuff
}
else {
//some other stuff
}
}
PHP is not asynchronous. Functions are executed one after another.
why don't you have function 1 call function 2 when it is done?
additionally, Mchl is right. function 1 will have to complete before the code executes function 2. Maybe you should set up your code like so:
$foo = 0;
$foo = function1();
if($foo > 0)
function2();
function1()
{
if($something)
$foo = 1;
}
function2()
{
$something = $else;
}
That way it will only call function 2 if function 1 changed the value of $foo.
Of you could post your full code and we'll know what you're trying to do.
PHP isn't threaded, so if you call function1_geocode before function2_proximitysearch, $result should always be set.
It could be that function1_geocode($address) has a bug, or else you might be missing some documentation for how that function is used.
It's possible to kinda simulate asynchronous functionality by, for example saving results in a file to be dealt with by a second page load. But that would have to be specifically designed that way. Within one PHP page load, you can't have a process running in the background.