could any one check why my script below is not working please?
<script src="http://maps.google.com/maps?file=api&v=2.x&key=
<?php
$this->googleMapsApiKey = $this->getValueFromDB("google", "googleMapsApiKey");
if ($_SERVER['HTTP_HOST']=='www.ABC.info') {
$this->googleMapsApiKey = "Googlemap-keys";
} elseif ($_SERVER['HTTP_HOST']=='www.CBA.com') {
$this->googleMapsApiKey = "Googlemap-keys";
}
?>" type="text/javascript"></script>
Thanks a lot!!
You can avoid this whole problem: Maps API keys now support multiple domains (and you can edit authorised domains at any time). See Obtaining an API key for more details.
I totally agree with Wrikken, it does not seem that you echoed the variable during the process. Maybe this approach would help:
<?php
print '<script src="http://maps.google.com/maps?file=api&v=2.x&key=';
$this->googleMapsApiKey = $this->getValueFromDB("google", "googleMapsApiKey");
switch ($_SERVER['HTTP_HOST'])
{
//Specific for a domain, but I think that the default handles it against your DB automatically
//case 'www.ABC.info' : $this->googleMapsApiKey = "Googlemap-keys";
// break;
//Same here
// case 'www.CBA.com': $this->googleMapsApiKey = "Googlemap-keys";
// break;
default: $this->googleMapsApiKey = "Googlemap-keys";
}
echo "$this->googleMapsApiKey type=\"text/javascript\"></script>";
?>
Related
I have two forms that sends data using ajax. Both forms have their own scripts and I thought that I would be able to access the same $_POST[] variables on the separate scripts, but this is not working. I tried using session_start() and include_once and for some reason I can't figure out why the variables are not passing from script to script. I've been at it for three days researching for a solution so if you know what I'm doing wrong or have an alternative please let me know thanks.
javascript.
$('.test-input').load("test.php", {
'sendTo':sendTo,
'carrier':carrier,
'testSubmit':testSubmit
})
$('#error-display').load("textsms.php", {
'date':scheduleDate,
'firstname':firstName,
'number':number,
'message':message,
'time':time,
'service':service,
'submit':submit
})
test.php
if (isset($_POST['testSubmit'])) {
$sendTo = $_POST['sendTo'];
$carrier = $_POST['carrier'];
$sendToInvalid = false;
$testEmpty = false;
$sendTo = "";
if (!preg_match('/^\(?\b\d{3}[-.)\s]?\s?\d{3}[-.)\s]?\d{4}\b$/', $sendTo) and $sendTo !== '') {
$sendToInvalid = true;
} elseif (empty($sendTo) || empty($carrier)) {
$testEmpty = true;
} else {
$sendTo = preg_replace('/[-.()\s]/','',$sendTo).$carrier;
$_SESSION['sendTo'] = $sendTo;
}
}
Trying to get $sendTo to pass to textsms.php down below.
else {
include 'test.php';
$sendTo = $_SESSION['sendTo'];
$number = preg_replace('/[-.()\s]/','',$number);
$number = "(".substr($number,0,3).") ".substr($number,3,3)."-".substr($number,6,4);
if ($sendTo !== "contactme#aboutryansam.com") {
$header = $name."\r\n#: ".$number;
$sendMsg = $userMsg."\r\nOn: ".$date.$time."\r\nService: ".$service;
//mail($sendTo, "You win!", $sendMsg, $header);
echo $sendTo;
echo "it worked";
}
Of course, on the page you initialize the ajax, include the "header.php" file that has inside session_start(). include_once('header.php') in the test.php as well. It should do the trick.
It's not a good practice nowadays, I better suggest you to use cookies and access them with $_COOKIE. Even better, use a library that takes care of cookies like this one. JQuery also has very good cookie management.
I am trying to change the logo based on what domain the visitor is using to view the website. I found some code in another topic on this site, but i was unable to make it work, so i was wondering if anyone of you can see what i'm doing wrong.
This is my code:
<?php
function logoSwap(){
switch($_SERVER['HTTP_HOST']) {
case 'liceng.dk':
$logo = "http://www.liceng.dk/images/liceng-logo.png";
break;
case 'www.liceng.dk':
$logo = "http://www.liceng.dk/images/liceng-logo.png";
break;
case 'licenergy.co.uk':
$logo = "http://www.liceng.dk/images/licenergy-logo.jpg";
break;
case 'www.licenergy.co.uk':
$logo = "http://www.liceng.dk/images/licenergy-logo.jpg";
break;
case 'http://licenergy.co.uk/':
$logo = "http://www.liceng.dk/images/licenergy-logo.jpg";
break;
default:
$logo = "http://www.liceng.dk/images/liceng-logo.png";
break;
};
return $logo;
}
?>
<?php
if(!empty($image)) {
echo '<h1>LIC Engineering A/S</h1>';
}
else {
echo '<img src="'.logoSwap().'" alt="LICeng logo">';
}
?>
Shouldn't it work? You can check the site here: www.liceng.dk
I've developed a web scraper on one server, which works and does what I want it to do. Now I have to implement it in another environment and I've stumbled on an issue I did not have when developing, which I am having a hard to identifying.
The only real error I have to go on is (from JS console):
POST http://my.cool.page/pro/company/scrape 502 (Bad Gateway)
The development server (where it works) is using PHP 5.4.16, implementation server is on PHP 5.4.45. I am using the same versions of external code on both servers.
The circumstances for launching the scraper are a bit different in implementation, it's now being loaded through Ajax rather than as its own page.
The ajax call:
$("#showScraperButton").click(function(){
$.post('/pro/company/scrape',
{
'url': url
},
function(result){
//code...
}
);
});
Function + case for scraping anchor tags, using Fabpot/Goutte:
function _getTagContent($crawler = '', $toScrape = '', $contentPatterns = '')
{
$tagContent = array();
ChromePhp::log("Hello _getTagContent");
foreach($toScrape as $tag) {
$i = 0;
switch ($tag) {
case 'a':
$n = $i;
$crawler->filter($tag)->each(
function ($node) use(&$tagContent, &$n, &$tag, &$crawler)
{
$nodeText = trim($node->text());
$tagContent[$tag][$n]['value'] = $nodeText;
$linksCrawler = $crawler->selectLink($nodeText);
try {
$link = $linksCrawler->link();
$magicDidHappen = true;
}
catch(Exception $e) {
$magicDidHappen = false;
}
if ($magicDidHappen) {
$uri = $link->getUri();
}
else {
$uri = $node->attr('href');
}
$tagContent[$tag][$n]['uri'] = $uri;
$n++;
});
break;
default:
break;
}
}
return $tagContent;
}
This results in the error described above.
By commenting out each line in the case, I found that the error does not show until
$n++;
is called. If
$n++;
is NOT included, the final a element is indeed present in $tagContent.
This led me to believe that the attempt at iteration is the problem in this case, and that the code otherwise does not throw errors. I then tried with a different html tag, using similar syntax:
case 'h3':
$n = $i;
$crawler->filter($tag)->each(
function ($node) use(&$tagContent, &$n, &$tag)
{
$tagContent[$tag][$n] = trim($node->text());
$n++;
});
break;
However, this works as intended, giving me all 40 instances of h3 on the page I'm scraping.
From this I have some questions: Please help? Could it be related to PHP versions? Is there a way to print the "standard" PHP errors when doing Ajax calls (instead of/in addition to http response codes), as I'm sure there is a hint to be found there as to what is failing. Thanks much for any help!
It now works using
case 'a':
$crawler->filter($tag)->each(
function ($node, $n) use (&$tagContent, &$tag, &$crawler)
{
$nodeText = trim($node->text());
$tagContent[$tag][$n]['value'] = $nodeText;
$linksCrawler = $crawler->selectLink($nodeText);
try {
$link = $linksCrawler->link();
$magicDidHappen = true;
}
catch(Exception $e) {
$magicDidHappen = false;
}
if ($magicDidHappen) {
$uri = $link->getUri();
}
else {
$uri = $node->attr('href');
}
$tagContent[$tag][$n]['uri'] = $uri;
$n++;
});
break;
Moved $n out of the using() statement and into the function parameters. I believe ChromePhp might have been causing some issues here. Still don't really know what went wrong. But now it works...
I have an issue that's stumped me.
I'm trying to automate a CLI login to a router and run some commands obtained via a webpage. However I don't know if the router has telnet or SSH enabled (might be one,the other, or both) and I have a list of possible username/password combos that I need to try to gain access.
Oh, and I can't change either the protocol type or the credentials on the device, so that's not really an option.
I was able to figure out how to login to a router with a known protocol and login credentials and run the necessary commands(included below), but I don't know if I should use an if/else block to work through the telnet/ssh decisions, or if a switch statement might be better? Would using Expect inside PHP be an easier way to go?
function tunnelRun($commands,$user,$pass, $yubi){
$cpeIP = "1.2.3.4";
$commands_explode = explode("\n", $commands);
$screenOut = "";
$ssh = new Net_SSH2('router_jumphost');
if (!$ssh->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$ssh->setTimeout(2);
$ssh->write("ssh -l username $cpeIP\n");
$ssh->read("assword:");
$ssh->write("password\n");
$ssh->read("#");
$ssh->write("\n");
$cpePrompt = $ssh->read('/.*[#|>]/', NET_SSH2_READ_REGEX);
$cpePrompt = str_replace("\n", '', trim($cpePrompt));
$ssh->write("config t\n");
foreach ($commands_explode as $i) {
$ssh->write("$i\n"); // note the "\n"
$ssh->setTimeout(2);
$screenOut .= $ssh->read();
}
$ssh->write("end\n");
$ssh->read($cpePrompt);
$ssh->write("exit\n");
echo "Router Update completed! Results below:<br><br>";
echo "<div id=\"text_out\"><textarea style=\" border:none; width: 700px;\" rows=\"20\">".$screenOut."</textarea></div>";
Update:
The solution I went with was a while/switch loop. I would of gone the Expect route, but I kept running into issues on getting the Expect module integrated into PHP on my server (Windows box.) If I had been using a Unix/Linux server Expect would of been the simplest way to achieve this.
I just made it into a working demo for now, so there are a lot of variations missing from the case statements still, and error-handling still needs to bef figured out, but the basic idea is there. I still want to move the preg_match statements around a bit more to do the matching at the top of the while loop (so I don't spam the whole case section with different preg_match lines), but that may prove to be more work than I want for now. Hope this might help someone else trying to do the same!
<?php
include('Net/SSH2.php');
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
ini_set('display_errors', 1);
$conn = new Net_SSH2('somewhere.outthere.com');
if (!$conn->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$prompt = "Testing#";
$conn->setTimeout(2);
$conn->write("PS1=\"$prompt\"");
$conn->read();
$conn->write("\n");
$screenOut = $conn->read();
//echo "$screenOut is set on the shell<br><br>";
echo $login_db[3][0]. " ". $login_db[3][1];
$logged_in = false;
$status = "SSH";
$status_prev = "";
$login_counter = 0;
while (!$logged_in && $login_counter <=3) {
switch ($status) {
case "Telnet":
break;
case "SSH":
$conn->write("\n");
$conn->write("ssh -l " . $login_db[$login_counter][0] . " $cpeIP\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/Permission denied.*/', $status) ? true : false):
$conn->write(chr(3)); //Sends Ctrl+C
$status = $conn->read();
if (strstr($status, "Testing#")) {
$status = "SSH";
$login_counter++;
break;
} else {
break 2;
}
case (preg_match('/[pP]assword:/', $status) ? true : false):
$conn->write($login_db[$login_counter][1] . "\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/yes\/no/', $status) ? true : false):
$conn->write("yes\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/(^[a-zA-Z0-9_]+[#]$)|(>)/', $status,$matches) ? true : false):
$conn->write("show version\n");
$status = $conn->read(">");
if(preg_match('/ADTRAN|Adtran|Cisco/', $status)? true:false){
$logged_in = true;
break;
}
default:
echo "<br>Something done messed up! Exiting";
break 2;
}
//echo "<pre>" . $conn->getLog() . "</pre>";
}
if ($logged_in === true) {
echo "<br> Made it out of the While loop cleanly";
} else {
echo "<br> Made it out of the While loop, but not cleanly";
}
echo "<pre>" . $conn->getLog() . "</pre>";
$conn->disconnect();
echo "disconnected cleanly";
}
?>
If statements might make your code become unreadable.
In that case I would suggest you to use switch-case blocks,
since switch case will allow you to write clearer code, and will allow you to catch exceptional values more efficiently.
Using Expect in php is simple:
<?php>
ini_set("expect.loguser", "Off");
$stream = fopen("expect://ssh root#remotehost uptime", "r");
$cases = array (
array (0 => "password:", 1 => PASSWORD)
);
switch (expect_expectl ($stream, $cases)) {
case PASSWORD:
fwrite ($stream, "password\n");
break;
default:
die ("Error was occurred while connecting to the remote host!\n");
}
while ($line = fgets($stream)) {
print $line;
}
fclose ($stream);
?>
There are some complication using the expect file_wrapper. If it were me, I'd just go for a simple socket connection for telnet and poll for the prompts (with a timeout) if the ssh connection fails.
On a casual inspection, the telnet client here seems to be sensibly written - and with a bit of renaming could provide the same interface as the ssh2 client extension (apart from the connect bit).
i have a php code and when i add some gets variables i get error, 500, i tested it with ajax and without ajax(directly writing the url on the adress bar)
When i go with localhost/ajax/test.php?did=1 everything is fine but when i go with localhost/ajax/test.php?did=1&task=1 the problem happens
all the functions are created before on the ../php/core.php
Here is the code
<?php
require '../php/core.php';
$did = floor($_GET['did']);
if (device_exist($did) && amlogedin() && intouch_get($uid, $did) == 2) {
$task = floor($_GET['task']);
$id = safestring($_GET['id']);
switch ($task) {
case 1:
if (feature_removefeature($did, $fid)) {
echo donemsg("Feature Removed");
}
break;
}
design_makefeturelist($did);
}
else {
echo 'Sorry, some thing is wrong';
}
Almost sure that you've got an error in the feature_removefeature or donemsg function. Because after you set task=1 it will enter the case 1: statement. You could replace the if with a simple echo "lala"; to check it out.
ps. Is $fid already set?