refresh a page and should post data each time it refreshes? - php

i want that this code refreshes itself & post the data to sendsms.php but should not redirect and remain on this page.tus each time it refreshes it download new data and post to sendsms.php. plz suggest me any idea?
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "15";
header("Refresh: $sec; url=$page");
$url=$_REQUEST['url'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$html= curl_exec($ch);
curl_close($ch);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$first = current(explode("|", $title));
$to="888888888";
header('Location: sendsms.php?to=' .$to .'&sms=' .$first);
?>

I would recommend running it through crontab.
You have two options, the first being the better:
Run the file directly on the server as a shell script.
Use curl or wget to access the file on a web server.
The first scenario would look something like this:
* * * * * /usr/bin/php /my/home/path/script.php
The second scenario would be similar:
* * * * * curl http://example.com/path/to/file/script.php
This is not exactly what you asked for, of course. If you wanted this page to simply sit in a web browser and reload every n seconds, you could use JavaScript and some jQuery AJAX:
<script type="text/javascript">
var timer = setInterval(function () {
$.post('/sendsms.php', { data: yourdata }, function (data) {
console.log(data);
});
}, 15000);
</script>
Hopefully this helps!

Any standard refresh will not re-post the data. Depending on browser it'll either make a usual GET request or the browser will ask you to confirm the POST data re-submit.
You can do what you need by creating a form in html and adding all variables you need in POST data into that form as < input type="hidden" >. Then you can submit that form using javascript (after the required delay - 15 seconds in your case).

Related

PHP script taking too much time

I have a script that fetches data from another API. The script is taking too much time while retrieving data from API around 1 hour and 30 minutes. The purpose of this script is to copy the reviews and send them to another account. The script first gathers the feedbacks and then based on order id obtained from feedback, iterates that feedback array and then performs curl request to some other API to obtain some data based on that order id. But that curl requests in loop taking too much time to return data.
The feedback are 3000 around.
How can i handle script to return data sooner?
$feedbacks = getFeedbacks();
if(count($feedbacks)>0){
foreach($feedbacks as $feedback){
$getData($feedback->order_id);
}
}
function getData($orderId)
{
$orderId = $orderId;
$api = "api address here";
$curl = curl_init($api);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
}
The problem here is when u call curl in loop the second call need the first to complete then the second can start and that take long time
To fix this u can use (pclose popen) the script will pass them in background and in second script u can manage your return data:
First script :
<?php
$feedbacks = getFeedbacks();
if(count($feedbacks)>0){
foreach($feedbacks as $feedback){
$getData($feedback->order_id);
}
}
function getData($orderId)
{
$orderId = $orderId;
pclose(popen('sudo /usr/bin/php /home/secondscript.php -o '.$orderId." >/dev/null &", 'r'));
}
Second script :
<?php
$command_line_args= getopt("o:");
$orderId=$command_line_args["o"];
$api = "api address here";
$curl = curl_init($api);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
{here u can use the json return ..}

how to get unknown string in $_GET method through URL

I want to pass a string from one PHP file to another using $_GET method. This string has different value each time it is being passed. As I understand, you pass GET parameters over a URL and you have to explicitly tell what the parameter is. What if you want to return whatever the string value is from providing server to server requesting it? I want to pass in json data format. Additionally how do I send it as Ajax?
Server (get.php):
<?php
$tagID = '123456'; //this is different every time
$tag = array('tagID' => $_GET['tagID']);
echo json_encode($tag);
?>
Server (rec.php):
<?php
$url = "http://192.168.12.169/RFID2/get.php?tagID=".$tagID;
$json = file_get_contents($url);
#var_dump($json);
$data = json_decode($json);
#var_dump($data);
echo $data;
?>
If I understand correctly, you want to get the tagID from the server? You can simply pass a 'request' parameter to the server that tells the server what to return.
EDIT: This really isn't the proper way to implement an API (like, at all), but for the sake of answering your question, this is how:
Server
switch($_GET['request']) {
case 'tagID';
echo json_encode($tag);
break;
}
You can now get the tagID with a URL like 192.168.12.169/get.php?request=tagId
Client (PHP with CURL)
When it comes to the client it gets a bit more complicated. You mention AJAX, but that will only work for JavaScript. Your php file can't use AJAX, you'll have to use cURL.
$request = "?request=tagID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '192.168.12.169/get.php' . $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
EDIT: added the working cURL example just for completeness.
Included cURL example from: How to switch from POST to GET in PHP CURL
Client (Javascript with AJAX)
$.get("192.168.12.169/get.php?request=tagId", function(data) {
alert(data);
});

PHP Cron job process with marker in URL

I want to process a script every minute using a cron on my server but I need to pass a variable in the URL or some other way. I have researched this and I've seen solutions using arguments in the cron but I don't think that works with what I'm doing.
Here is what I am trying to do:
script.php (runs every minute)
<?php
$marker = $_GET['marker'];
$accountObj = new etAccounts($consumer);
$request_params = new TransactionHistoryRequest();
$request_params->__set('count', 50); //how many will be shown
if($marker_get != ''){
$request_params->__set('marker', $marker_get); //starting point ex. 14293200140265
}
$json = $accountObj->GetTransactionHistory($account, $request_obj, $request_params );
echo $json; //shows most recent 50 transactions starting from marker value
//process json data here...
//included in json is a marker variable that will be used to return the next 50 json results
//after data is processed reload the page with marker in URL
header('Location: script.php?marker=14293200140265');
?>
I understand that cron is CLI on the server side and that it can't process redirections or header locations but how is this possible. I saw someone mention using CURL, how might this work? Example?
Simple example to send post variables to an url:
$fields = array(
'id' => $id,
'mail' => $mail,
);
$url = "yourdomain.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
Based on the comments, you don't need to redirect or use query variables.
You could use a loop that runs while your marker variable is not empty:
$your_marker_variable = '';
do {
$accountObj = new etAccounts($consumer);
$request_params = new TransactionHistoryRequest();
$request_params->__set('count', 50); //how many will be shown
if($marker_get != '') {
$request_params->__set('marker', $marker_get); //starting point ex. 14293200140265
}
$json = $accountObj->GetTransactionHistory($account, $request_obj, $request_params );
echo $json; //shows most recent 50 transactions starting from marker value
//process json data here...
//included in json is a marker variable that will be used to return the next 50 json results
// set the new value of $your_marker_variable
$your_marker_variable = ...
} while (!empty($your_marker_variable));
Note that the undefined and unused variables in the script you posted, make it hard to see what variable is used for what, so you would need to adapt this a bit.

Executing Javascript in an external file via php script

I have been trying to create a php file which basically is a mobile shortcode message. Since any output on the page automatically gets shown in the mobile SMS, I cannot use any html on the page. But I am having a problem in executing some google analytics javascript code before the text is outputted on the page. I create an external file and wrote the javascript there and tried to execute the file via curl, but curl does not execute the javascript. So my code for the main file SMSapi.php is something like this:
<?php
if(isset($_GET['mobile'])){
$number = $_GET['mobile'];
}
if(isset($_GET['text'])){
$data = $_GET['text'];
}
$brand = "mybrand";
$event = "MyEvent";
$deal = "MyDeal";
$url = "http://myurl.com/sms.php";
$post_string = "brand={$brand}&event={$event}&deal={$deal}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$success = curl_exec($ch);
curl_close($ch);
echo "Your discount code is XYZ123";
?>
The sms.php code is as follows:
<?php
if(isset($_POST) && !empty($_POST['event']) && !empty($_POST['brand']) && !empty($_POST['deal'])):
$event = urldecode($_POST['event']);
$brand = urldecode($_POST['brand']);
$deal = urldecode($_POST['deal']);
?>
<html>
<head>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-MyNum']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
_gaq.push(['_trackEvent', '<?php echo $event; ?>', '<?php echo $brand; ?>', '<?php echo $deal; ?>']);
</script>
</head>
</html>
<?php endif ?>
the main SMS api file makes a curl request to the sms.php file and while the file gets executed, the html and javascript gets returned back as text without any execution happening there. And hence the javascript shows up in the SMS.
Is there a way to implement a external url and all the javascripts in it there and there via php?
This link might be useful for you: http://curl.haxx.se/docs/faq.html#Does_curl_support_Javascript_or
I am presuming this is a script that runs on a call from an SMS provider, and you are tying to log this event in Google Analytics.
Firstly, I would have thought this would more easily be accomplished by logging to a database, rather than to Analytics. As the javascript is running server side, you won't get any extra information other that the event.
If you really do need to run the Google code then you need to try searching on "server side javascript google analytics". The solution is going to be highly dependant on what server platform you are running and what is/can be installed.
One interesting link though which may work for your PHP is:
http://code.google.com/p/serversidegoogleanalytics/
but I haven't used it so don't know how well this works.

php Curl clicked links

I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?
Thanks
Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..
Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination
<?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);
//Change link url
$link = $curl_response;
$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;
$link = str_replace($linkfind, $linkreplace, $link);
//Change js url
$js = $link;
$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;
$js = str_replace($jsfind, $jsreplace, $js);
//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;
$alink = str_replace($alinkfind, $alinkreplace, $alink);
//Echo page back
echo $alink;
?>
You could grab all the URLs using a regular expression
// insert general warning about how parsing HTML using regex is evil :-)
preg_match('/href="([^"]+)"/', $html, $matches);
$urls = array_slice($matches, 1);
// Now just loop through the array and fetch the URLs with cUrl...
While I can't imagine why you would do that I think you should use ajax.
Attach an event on every a tag and send them to a script on your server where the magic of curl would happen.
Anyway you should explain why you need to fetch data with curl.
As far as I can understand your question you need to get the contents of URL via CURL... so here is the solution
Click here to get via curl
Then attach an event with the above <a> tag, e.g. in JQuery
$("#my_link").click(function(){
var target_url = $(this).attr("href");
//Send an ajax call to some of your page like cURL_wrapper.php with target_url as parameter in get
});
then in cURL_wrapper.php do follwoing
<?php
//Get the $target_url here from $_GET[];
$ch = curl_init($your_domain");
$fp = fopen("$target_url", "r");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Categories