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.
Related
I'm currently executing PhantomJS (from PHP) to render some HTML reliably (utilizing 3rd party js libraries that can't be easily replicated in PHP) and then sending the rendered HTML back to the client.
$fh = fopen('/dev/shm/graph-'.$sig.'.html', 'w');
fwrite($fh, $html);
fclose($fh);
$stime = microtime(true);
$res = exec('/usr/bin/phantomjs /home/me/www/js/render_svg.js '.
escapeshellarg($sig), $output, $return_var);
var_dump(microtime(true)-$stime); // 400 ms
print implode("\n", $output);
exit();
render_svg.js:
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
page.onLoadFinished = function() {
system.stdout.write(page.content);
phantom.exit(0);
};
content = '';
f = fs.open('/dev/shm/graph-'+system.args[1]+'.html', 'r');
content += f.read();
page.content = content;
The execution time for PhantomJS is around 400ms which is super, but probably too much of a delay to use in production. Is there any way of getting this down by e.g. not using exec to fire up phantomjs each time, but having it already running in the background?
You could try the webserver module:
http://phantomjs.org/api/webserver/
There is a tutorial on it here:
http://benjaminbenben.com/2013/07/28/phantomjs-webserver/
(If you try this, I'd love to hear how you get on and how latency compares to your current 400ms using exec.)
BTW, I think there was a recent change in the mongoose license, making it incompatible with the PhantomJS license. So it is possible this feature will disappear in future releases. (There was also talk of switching in an alternative library to mongoose, in which case it may not disappear!)
Answer thanks to Darren Cook:
$fh = fopen('/dev/shm/graph-'.$sig.'.full.html', 'w');
fwrite($fh, $html);
fclose($fh);
$stime = microtime(true);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:8080');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'sig='.$sig);
$output = curl_exec($ch);
curl_close($ch);
var_dump(microtime(true)-$stime); // 150ms
print $output;
exit();
render_svg.js:
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
var server = require('webserver').create();
var service = server.listen('127.0.0.1:8080', function(request, response) {
var stime = new Date();
content = '';
f = fs.open('/dev/shm/graph-'+request.post['sig']+'.full.html', 'r');
content += f.read();
page.content = content;
page.onLoadFinished = function() {
response.statusCode = 200;
response.write(page.content);
response.close();
};
});
In short, no. PhantomJS can't be run as a daemon or server so you'll need to execute this script every time. If you want to improve performance, you should try finding another method of rending the html.
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).
I'm using CURL to scrape a website like this:
<?php
$url = "http://www.bbc.com/news/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.bbc.com/news/$2$3', $curl_scraped_page);
echo $curl_scraped_page;
?>
As you can see the URL is set for BBC news. However, I would like the URL to be a variable instead. The variable would have to be the value of parent.document. In JQuery for example I would do this:
var value = $("input", parent.document.body).val();
How do I set something like that in PHP? I have Googled but I couldn't find anything about parent.document in PHP.
PHP is a server-side scripting language and therefore has no access to the current HTML page. It is processed before the HTML is sent to the client's browser, therefore parent.document doesn't even exist at the time the script is being processed.
If you would like to pass data from an HTML page to a PHP script, you can do so using an HTML <form> or through JavaScript/JQuery AJAX requests.
For example, the following code will pass the value of input to the PHP script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function pass(){
var value = $("input", parent.document.body).val();
$.ajax({
type: "POST",
url: "myscript.php",
data: { mydata: value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</head>
<body>
<input type="text" />
<button onclick="pass();return false;">Pass Value</button>
</body>
</html>
And the revised script (myscript.php):
<?php
$url = isset($_POST['mydata']) ? $_POST['mydata'] : '';
$curl_scraped_page = '';
if(!empty($url)){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1'.$url.'$2$3', $curl_scraped_page);
}
echo $curl_scraped_page;
?>
I would recommend using $(id) to retrieve the value of an <input> instead of $("input",context).
E.g.
var value = $('#txt').val();
And in the HTML:
<input type="text" id="txt" />
For more info on JQuery.ajax see here.
here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.
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);
?>