Remove certain part of Posted value with php - php

Hello everyone im trying to retrieve data from a form with a POST request.
This data is posted into another website.
On the website where the data is created i have a text field called website. The data filled in this field goes to the other website where the data is collected. Now i want to exclude the 'www' part. for example if the user enters www.hello.nl i want to receive hello.nl only.
What i tried:
function website () {
$str = $_POST['billing_myfield12'];
echo chop($str,"www");
}
// end remove www
// prepare the sales payload
$sales_payload = array(
'organization_id' => $organization_id,
'contact_id' => $contact_id,
'status' => 'Open',
'subject' => $_product->post_title." ".website(), <----- here i call it
This is not working. Is there a way to do this?

You can use trim() or specifically ltrim() to trim way the www. on the left side. Please don't forget the . after www.
echo ltrim($str, "www.");
Sample Code
echo ltrim("www.hello.nl", "www."); // hello.nl
Demo: http://ideone.com/bqMY7X
Looks like there are side effects with the above code. Let's go with the traditional str_replace method:
echo str_replace("www.", "", $str);
Also, we are sure that it should replace only from the first characters. So, we need to use a preg_replace instead, making it replace from the start.
echo preg_replace("/^www\./g", "", $str);
Verified the above code with: https://regex101.com/r/dv8N6d/1

Related

php remove URLs from form submission

I have a parish website that I am maintaining. The site has a parish registration form on it. Yesterday someone submitted the form with spam. The submitter supplied an inappropriate web address in one of the fields.
I'm fairly confident this was not a bot form submission as I use a recapcha and honeypot to fend off bots.
What I'm trying to figure out is how on the processing page to look at all the text entry fields and scrub URLs.
Since the language is PHP:
function scrubURL(field){
if($_POST[field] contains **SomeURL**){
$field = str_replace(***SomeURL***, "", $_POST[field])
} else{
$field = $_POST[field];
}
return $field;
}
I'm just not sure to check the field to see if it contains a URL.
I'm planning to scrub URLs by calling:
$first = scrubURL($first);
$last = scrubURL($last);
$address = scrubURL($address);
I will then use $first, $last & $address in the mail that gets sent to the parish office.
This function will recognize URLs and replace then with empty strings. Just realize that lots of thing, such as wx.yz look like valid URLs.
function scrubURL($field)
{
//return preg_replace('#((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)(?:[?&][^?$]+=[^?&]*)*#i', '', $_POST[$field]);
return preg_replace("#((https?://|ftp://|www\.|[^\s:=]+#www\.).*?[a-z_\/0-9\-\#=&])(?=(\.|,|;|\?|\!)?(\"|'|«|»|\[|\s|\r|\n|$))#iS", '', $_POST[$field]);
}
The parameter, $field, has to be a string, such as "email" corresponding to $_POST["email"]
<?php
$_POST = [
'email' => 'something www.badsite.com?site=21&action=redirect else',
];
function scrubURL($field)
{
return preg_replace('#((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)(?:[?&]\S+=\S*)*#i', '', $_POST[$field]);
}
echo scrubURL('email');
Prints:
something else
Regex is an easy way to evaluate fields for possible URL markers. Something like the following would remove much of it (though, given how many shapes URLs can come in, not everything):
$_POST = [
'first' => 'actualname',
'last' => 'something http://url.com/visit-me',
'middle' => 'hello www.foobar.com spammer',
'other' => 'visit https://spammery.us/ham/spam spamming',
'more' => 'spam.tld',
];
// Iterates all $_POST fields, editing the $_POST array in place
foreach($_POST as $key => &$val) {
$val = scrubUrl($val);
}
function scrubURL($data)
{
/* Removes anything that:
- starts with http(s):
- starts with www.
- has a domain extension (2-5 characters)
... ending the match with the first space following the match.
*/
$data = preg_replace('#\b
(
https?:
|
www\.
|
[^\s]+\.[a-z]{2,5}
)
[^\s]+#x', '-', $data);
return $data;
}
print_r($_POST);
Be aware that the last condition, looking for any TLD (.abc) -- and there are lots of them! -- may result in some false positives.
"sentence.Poor punctuation" would be safe. We're only matching [a-z].However, spam.Com would also pass! Use [a-Z] to match both cases, or add the "i" modifier to the regex.
"my acc.no is 12345" would be removed (potential spammer accountants from Norway?!)
The above process would give you the following filtered data:
Array (
[first] => actualname
[last] => something -
[middle] => hello - spammer
[other] => visit - spamming
[more] => -
)
The regex can definitely be further refined. ^_^
N.B. You may also want to sanitize the incoming data with e.g. strip_tags and htmlspecialchars to ensure the website is sending reasonably safe data to your parish.

Preg Replace text based on string

i am trying to figure out why this has no result.
I am fetching data from wp database
$global_notice2 = get_post_meta($post->ID,'_global_notice', true);
This contains an a href link i wish to manipulate using preg replace before displaying it for the user such as
preg_replace('/<a(.*?)href="(.*?)"(.*?)>/', '', $global_notice2 );
Now we display the data
$notice2 = "<p>$alternative_content$global_notice2</p>";
The data is unmodified, what am i doing wrong?
preg_replace don't modify the argument, you need to catch the return like this :
$global_notice2 = preg_replace('/<a(.*?)href="(.*?)"(.*?)>/', '', $global_notice2);
See preg_replace documentation

How would I replace all question marks after the first

So, a lot of my form systems redirect back to the previous page, although, they display a message in the process. The way I display a message is by simply using ?message=messageCode in the URL.
However, if they use the form from a page that already has a query string, it adds a second query string, messing everything up.
Example:
if I were to login from the navigation bar, on the URL "mywebsite.com/something?message=1", it would log in, but redirect to "mywebsite.com/something?message=1?message=2"
This results in no message being displayed.
What I am asking here is, how could I change all of the question marks AFTER the first question mark, to and signs?
Example:
From: mywebsite.com/page?blah=1?something=2?hi=3
To: mywebsite.com/page?blah=1&something=2&hi=3
I have searched around, as well as tried some methods of my own, but nothing seems to work properly.
What you should be doing is build a proper URL, appending ? or & when appropriate.
$url = 'mywebsite.com/something?message=1';
$new_url = sprintf('%s%s%s',
$url,
strpos($url, '?') === false ? '?' : '&',
http_build_query(['message' => 2])
);
Or, first parse the previous URL and merge the query string.
Use it like below:-
<?php
$str = 'mywebsite.com/something?message=1?message=2';
$pos = strpos($str,'?'); //check the last occurrence of ?
if ($pos !== false) {
$str = substr($str,0,$pos+1) . str_replace('?','&',substr($str,$pos+1));// replacement of ? to &
}
echo $str;
?>
Output:- https://eval.in/388308

Replace certain content in txt file and save it using PHP?

So I receive variable replace it in certain area in txt file and save it back. I get page number and according to it I get exploded data. Anyway I'll post a code below to make it more clear:
$pgnm = $_GET['page']; //This is the page number as I've said.
$conts = file_get_contents("content.txt");
the content of content.txt looks like this:
text1|text2|text3
I display this content in certain pages. For example on first page: text1, on second text2, etc.
Now i'm working on a form where I successfully change these. I get as I've said page number and text:
$text = "new text"; //this is the content which I want to be replaced instead of text2.
I make the content.txt file look like this after its saved: text1|new text|text2
So lets go on:
$exp = explode("|", $conts); //this explodes data into slashes.
$rep = str_replace($exp[$pgnm], $text, $conts);
file_put_contents("content.txt", $rep); // Saving file
All these above-mentioned operations work perfectly, but here's my problem now. This only works if content.txt has certain content, if it's empty it enters my new text and that's all: 'new text' and that's all. Maybe I want to add second page content 'new text2' and after I finish entering it and save I want the file to be displayed like this: new text|new text2. If the content of content.txt looks like this: 'new text|' str_replace doesn't replace empty string. So that's my another problem too.
I tried everything, but couldn't manage to anything about this two problems. Thank you in advance for your help!
Why don't you use your $exp array for building the content. I mean $exp contains all the blocks as an array() one by one. So you just change, or add new values to the array (no str_replace() needed). Then rebuild using implode('|',$exp);.
As for your code;
$exp = explode("|", $conts); //this explodes data into slashes.
$exp[$pgnm] = $text;
file_put_contents("content.txt", implode('|',$exp)); // Saving file
Instead of str_replace use this code:
$pgnm = 1;
$text = 'new text';
$conts = 'text1||text3';
$exp = explode('|', $conts);
$exp[$pgnm] = $text;
$rep = implode('|', $exp);
var_dump($rep); // string(20) "text1|new text|text3"

removing unneeded query from generated url string in php

I have the following string generating mp3 urls for a music player on my site.
<?php echo $song->getTitle() ?>
which results in /public/music_song/df/74/746b_2112.mp3?c=ec1e
I would like to remove the query from the string
resulting in /public/music_song/df/74/746b_2112.mp3
I've looked into how to split the url, but I'm nowhere near being a php genius just yet so I dont know weather to split or use preg_replace or how the heck to incorporate it into my existing string.
I have to get rid of these queries, they are unneeded and crashing my databases on a daily basis.
list($keep) = explode('?', '/public/music_song/df/74/746b_2112.mp3?c=ec1e');
$parsedInput = parse_url('/public/music_song/df/74/746b_2112.mp3?c=ec1e');
echo $parsedInput['path'];
// Results in /public/music_song/df/74/746b_2112.mp3
Edit: Since I havent worked with SocialEngine, Im guessing that what you need to do is:
<?php $parsed = parse_url($song->getFilePath());
echo $this->htmlLink($parsed['path'],
$this->string()->truncate($song->getTitle(), 50),
array('class' => 'music_player_tracks_url',
'type' => 'audio',
'rel' => $song->song_id )); ?>

Categories