How do I use str_replace in an IF statement? - php

I have an input field that automatically inserts the value of 'www.' before anything the user types. The data in the input field then gets inserted into a table.
Using PHP, I am trying to remove/strip the instance of 'www.' IF an '#' symbol is typed into the input field. I cannot seem to get this to work, looking at what is output in my SQL Table. I'm using an empty variable in $var to replace the 'www.'
Here is my code:
if(strpos($_POST['Link'], '#') !== false) {
$webvar = 'Twitter';
str_replace('www.', '', $var);
$link = mysqli_real_escape_string($conn, '<a href='."'".'https://'.'twitter.com/'.$_POST['Link']."' ".'target='."'".'_blank'."'".'>'.$webvar.'</a>');
}

your question is unclear but something like this ?
if (strpos($_POST['Link'], '#')) {
$webvar = 'Twitter';
$link = mysqli_real_escape_string($conn, '<a href=' . "'" . 'https://' . 'twitter.com/' . str_replace('www.', '', $_POST['Link']) . "' " . 'target=' . "'" . '_blank' . "'" . '>' . $webvar . '</a>');
}

You should directly assign the value back to the variable (although it's not clear what $var is, it sounds like it should be $_POST['Link'])
$var = str_replace('www.', '', $_POST['Link']);

Related

PHP/MySQL Sanitation Issue

From LDAP I'm querying my users and this code sets them as a variable in the quoted format I need to run the MySQL query which would be 'username','other_username', etc...
foreach ($prefs as $who => $pref) {
if (strpos($who, 'public') === false) {
$team_users_string .='\'' . $who . '\',';
}
When I try to sanitize the command with the following code it converts the string to \'username\',\'other_username\', what can I do to correct this?
$team_users = rtrim($team_users_string, ",");
$start_date = $_POST['start_year'] . '-' . $_POST['start_month'];
$end_date = $_POST['end_year'] . '-' . $_POST['end_month'];
echo 'Welcome, <strong>' . $user . '</strong><br />';
echo '<br />';
echo '<strong>Selected Start Date:</strong> ' . $start_date . '<br />';
echo '<strong>Selected End Date:</strong> ' . $end_date . '<br />';
mysql_real_escape_string($team_users),
mysql_real_escape_string($start_date),
mysql_real_escape_String($end_date));
$query = "SELECT * FROM vacation WHERE user_name in ($team_users) AND day BETWEEN '$start_date-01' AND '$end_date-31'";
Your problem is that you're adding the quote characters before you pass the string to mysql_real_escape_string(). So the literal quotes become escaped by that function.
You could avoid this by using mysql_real_escape_string(), and then delimiting the result in quotes.
Also I'd use an array and implode() the array to get commas, instead of being forced to rtrim() the last comma.
foreach ($prefs as $who => $pref) {
if (strpos($who, 'public') === false) {
$team_users_array[] = "'" . mysql_real_escape_string($who) . "'";
}
}
$team_users = implode(",", $team_users_array); // no rtrim needed

do not write empty array fields

ik have a html form where i can select some options. I want to write those values comma separated to my database. This is the code i have
$genretotal = $_POST['genre'];
$genre0 = $genretotal[0];
$genre1 = $genretotal[1];
$genre2 = $genretotal[2];
$genre3 = $genretotal[3];
$genre4 = $genretotal[4];
$genre5 = $genretotal[5];
$genre6 = $genretotal[6];
$genre7 = $genretotal[7];
$genre = $genre0 . "," . $genre1 . "," . $genre2 . "," . $genre3 . "," . $genre4 . "," . $genre5 . "," . $genre6 . "," . $genre7;
How can i leave out the empty values?
Try with implode and array_filter
implode(',', array_filter($_POST['genre']));
Why so?
$genre = join(',', array_filter($_POST['genre'], function($sItem)
{
//here I assume your 'not empty' matches PHP empty() function
//if not, then add desired conditions
return !empty($sItem);
}));
$genretotal = $_POST['genre'];
if(isset($genretotal) && count($genretotal)>0)
{//This check array is null or not
$gen_arr = implode(",",$genretotal);
}//end if
echo $gen_arr;
//This is the code you avoid empty values

PHP iteration foreach, omitting characters from last iteration

I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }
Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
$a .= ",\n";
$i++;
return $a;
}
Many thanks for your experience,
orionrush
$a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
and use it by
return implode(",\n", $a);
You should really use json_encode().
$data = array();
foreach ($pages as $go) {
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$data[] = array(
'image' => BASEURL . GIMGS . '/' . $go['media_file'],
'title' => $title . ', ' . $caption,
'url' => BASEURL . GIMGS . '/' . $go['media_file']
);
}
echo json_encode($data);
foreach ($pages as $go){
$return[] = json_encode($go);
}
return implode(",\n", $return);
do what you like in the foreach, the implode will comma separate the lines like you want
just chop the end off with substr:
return substr($a, 0, -3);

Is it safe to turn urls into links?

I want to turn urls in the user comments, into links.
I don't have time to test bloated anti-xss libraries like HTML Purify, so I wouldn't be allowing any html tags.
I just want to make everything go through htmlentities() and nl2br(), and then use preg_replace() to find urls and turn them into links ('a' html tags).
Is it unsafe to grab the urls I find and put them inside href='' ?
If not, what can I do about it?
Yes, it should be safe. If you wonder how, here is a function I use for this (I simplified it for the purpose of this post):
function formatPost($string) {
return nl2br(
preg_replace_callback(
'~https?://([^/\s]+)(?:/((?>[/\w]+|\S(?!\s|$))*))?~',
function($matches) {
$url = $matches[0];
$host = $matches[1];
$path = isset($matches[2]) ? $matches[2] : '';
$follow = false;
if ('' == $path) {
$text = $host;
} elseif ($_SERVER['HTTP_HOST'] == $host) {
$text = $path;
$follow = true;
} else {
$text = $host . '/' . $path;
}
return '<a href="' . $url . '"' . (!$follow ? ' rel="nofollow"' : '') . '>' . $text . '</a>';
},
htmlspecialchars($string)
)
);
}

All symbols after "&" stripped

My query:
mysql::getInstance()->update('requests', array('response' => mysql_real_escape_string($_POST['status'])), array('secret' => $_POST['secret'])); ?>
If i wand to add string with "&" symbol, all symbols after "&" stripped.
Example:
string: !"№;%:?()_+!##$%^&()_+
in database i see only: !"№;%:?*()_+!##$%^
How to fix this?
update function, if anyone need:
function update($table, $updateList, $whereConditions)
{
$updateQuery = '';
foreach ($updateList as $key => $newValue) {
if (!is_numeric($newValue)) {
$newValue = "'" . $newValue . "'";
}
if (strlen($updateQuery) == 0) {
$updateQuery .= '`' . $key . '` = ' . $newValue;
} else {
$updateQuery .= ', `' . $key . '` = ' . $newValue;
}
}
return $this->query('UPDATE ' . $table . ' SET ' . $updateQuery . $this->buildWhereClause($whereConditions));
}
UPD:
echo mysql::getInstance()->getLastSQL() says:
UPDATE requests SET `response` = '!\"№;%:?*()_ !##$%^' WHERE `secret` = '52a4ab5f7f3e8491e60b71db7d775ee2'
so, problem with function update in mysql class?
Slaks, i need to use str_replace('&', '%28', $query); ?
You're probably passing a raw & character in the querystring, which causes everything after the & to be parsed as second parameter by PHP. (Before it gets into your variable)
You need to escape the & as %26.
EDIT: You need to escape it before you send it to the server. (When you make the HTTP request)

Categories