I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.
Related
I just wrote this and was thinking there must be an easier/more clean way to do this as it looks terrible doing it this way:
if(isset($_GET['m']) && isset($_GET['v'])) {
Router::Get($_GET['m'], $_GET['v']);
} elseif(isset($_GET['m'])) {
Router::Get($_GET['m'], "");
} else {
Router::Get("", "");
}
I'm looking for a cleaner way, like:
Router::Get(is('m'), is('v'));
Any suggestions to shorten/clean this kind of if-statements?
Can do,
$m = isset($_GET['m']) ? $_GET['m'] : "";
$v = isset($_GET['v']) ? $_GET['v'] : "";
Router::Get($m, $v);
You can encapsulate the logic:
Router::$query = $_GET;
Router::Get('m', Router::Get('v'))
class Router {
static public $query;
static function Get($name, $default = '') {
return isset(self::$query[$name]) ? self::$query[$name] : $default;
}
}
I am trying to validate a form. I have my code as follows:
if(isset($_POST['data'])) {
$id = $this->input->post('id');
$action = $this->input->post('action');
$table = $this->input->post('table');
$data = $this->input->post('data');
$out = array();
$out['id'] = $id;
$out['error'] = '';
$out['fieldErrors'] = '';
$out['data'] = array();
$out['row'] = $data;
if($action=="create" && $data['display_name'] === '') {
if (empty($data['display_name']))
{
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
}
Now this is working fine if there is no data inserted in the form, but if there is a space (whitespace) it doesn't work.
Any suggestion?
There are a few options to solve this:
Replace all whitespaces with nothing:
if (strlen(preg_replace('/\s/', '', $data['display_name'])) == 0)
{
Use trim to remove leading and trailing whitespaces:
if (strlen(trim($data['display_name'])) == 0)
{
Use str_replace() to get rid of invalid characters:
if (strlen(str_replace(array(' ', "\t"), array('', ''), $data['display_name'])) == 0)
{
Use regular expression to validate a name:
if (!preg_match('/^([A-Za-z0-9-_]+)$/', $data['display_name']))
{
=== checks for type as well along with value comparison, using trim function on variable containing values would give you expected results.
Try this. I have used the ctype_space function below to check for whitespaces
if($action=="create" && ($data['display_name'] === '' || ctype_space($data['display_name']))) {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
Just use trim function and check if its empty string:
if ($action=="create") {
if (trim($data['display_name']) == '') {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
I have an url whose format may be :
www.discover.com
http://discover.com
http://www.discover.com
http://www.abcd.discover.com
discover.com
And i have another url which may be any of below format:
www.discover.com/something/smoething
http://discover.com/something/smoething
http://www.discover.com/something/smoething
http://www.abcd.discover.com/something/smoething
discover.com/something/smoething
Now i want to compare this two urls to check whether domain name "discover.com" is present in the second url.
Am using below code :
$domain1 = str_ireplace('www.', '', parse_url($urlItem1, PHP_URL_HOST));
$domain2= str_ireplace('www.', '', parse_url($urlItem2, PHP_URL_HOST));
if(strstr($domain2, $domain1))
{
return $domain2;
}
Solution :
function url_comparison($url1, $url2) {
$domain1 = parse_url($url1,PHP_URL_HOST);
$domain2 = parse_url($url2,PHP_URL_HOST);
$domain1 = isset($domain1) ? str_ireplace('www.', '',$domain1) : str_ireplace('www.', '',$url1);
$domain2 = isset($domain2) ? str_ireplace('www.', '',$domain2) : str_ireplace('www.', '',$url2);
if(strstr($domain2, $domain1))
{
return true;
}
else
{
return false;
}
}
$url1 = "discover.com";
$url2 = "https://www.abcd.discover.com/credit-cards/resources/balance-transfer.shtml";
if(url_comparison($url1, $url2))
{
echo "Same Domain";
}
else
{
echo "Diffrent Domain";
}
Thanks.
Make use of the documentation, parse url
Then you should look at the hostname, and with use of strpos.
$url = parse_url('www.discover.com/something/smoething');
if (strpos($url['host'], 'discover.com') !== false) {
// do you thing
}
0 is also a valid value so the !== or === is needed
To check if two domain are equal you need to set some rules, because is www.example.com the same as example.com, and is https the same as http?
function url_comparison($url_1, $url_2, $www = false, $scheme = false) {
$url_part_1 = parse_url($url_1);
$url_part_2 = parse_url($url_2);
if ($scheme && $url_part_1['scheme'] !== $url_part_2['scheme']) {
return false;
}
if ($www && $url_part_1['host'] === $url_part_2['host']) {
return false;
} elseif(!$www && (strpos($url_part_1['host'], $url_part_2['host']) !== false || strpos($url_part_2['host'], $url_part_1['host']) !== false)) {
return false;
}
return true;
}
With the above function you should see the right direction, not tested so should be tweaked perhaps. The first 2 values should be an url. $www is a boolean if the 'www.' should be checked, and if $scheme = true also the https or http needs to be the same
I was trying to make this function more comprehensive to parse more of a url
Currently the function I have is this
function _pagepeeker_format_url($url = FALSE) {
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
return FALSE;
}
// try to parse the url
$parsed_url = parse_url($url);
if (!empty($parsed_url)) {
$host = (!empty($parsed_url['host'])) ? $parsed_url['host'] : '';
$port = (!empty($parsed_url['port'])) ? ':' . $parsed_url['port'] : '';
$path = (!empty($parsed_url['path'])) ? $parsed_url['path'] : '';
$query = (!empty($parsed_url['query'])) ? '?' . $parsed_url['query'] : '';
$fragment = (!empty($parsed_url['fragment'])) ? '#' . $parsed_url['fragment'] : '';
return $host . $port . $path . $query . $fragment;
}
return FALSE;
}
This function turns urls that look like this
http://www.google.com/url?sa=X&q=http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius/&ct=ga&cad=CAcQARgAIAEoATAAOABA3t-Y_gRIAlgBYgVlbi1VUw&cd=F7w9TwL-6ao&usg=AFQjCNG2rbJCENvRR2_k6pL9RntjP66Rvg
into this
http://www.google.com/url
Is there anyway to make this array return the entire url instead of just part of it ?
I have looked at the parse_url php page and it helps and searched the stackoverflow and found a couple of things I am just having a bit of trouble grasping the next step here.
Let me know if I can clarify in any way
thanks!!
return $url;
Or am I missing something?
this is what i use (getting rid of parse_url and such):
function get_full_url() {
// check SSL
$ssl = "";
if ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") || (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"]=="443"))
{ $ssl = "s"; }
$serverport = ($_SERVER["SERVER_PORT"]!="80"?":".$_SERVER["SERVER_PORT"]:"");
return "http".$ssl."://".$_SERVER["SERVER_NAME"].$serverport.$_SERVER["REQUEST_URI"];
}
just call get_full_url(); from anywhere in your script.
I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}