How to parse a variable? - php

I have the following test line in my PHP which works fine as a way of posting to Twitter from within my PHP code.
$oauth->post('statuses/update', array('status' => "hello world"));
However I want to post the contents of a variable as opposed to Hello World
If I change the code as follows, then all that gets posted is $message
$oauth->post('statuses/update', array('status' => '$message'));
I also tried without the ' but then nothing got posted, ie
$oauth->post('statuses/update', array('status' => $message));
How can I correctly parse the contents of $message?
$message is created as follows
$message = "http://www.smartphonesoft.com/index.php?option=com_mtree&task=viewlink&link_id=" .$link_id . " " ."Windows Phone Software" . " " .$link_name . " " . $metadesc;
I added an echo $message which showed me what I expected, namely:
http://www.smartphonesoft.com/index.php?option=com_mtree&task=viewlink&link_id=33183073
Windows Phone Software Pocket Player
Pocket Player is a rockin' way to
enjoy music and video on your Windows
Mobile device. Through multiple media
and playlist formats, Internet
connectivity, plugin extensions, and
an intuitive interface, Pocket Player
means less taps, more music!
Thanks,
Greg

From the Twitter API doc for status/update:
status The text of your status update, up to 140 characters. URL encode as necessary.
So I'd say you have to shorten the $message, because yours has 369 characters.

The last code you quote is correct. Are you sure $message has meaningful content?
(Aside: The reason for '$message' posting "$message" verbatim is that single-quoted strings in PHP do not get variable interpolation nor escape characters: '\n' is literally "\n", whereas "\n" would result in a string containing the newline character.)

'$message' can't work because you're actually passing the string "'$message'", and not the $message variable.
If the second code you posted doesn't work, it's either because $message is not defined in your script, or because something else in your script is wrong, but we can't really tell that without seeing the rest of the code.

Since your URL is way too long for twitter, perhaps you'd like to shorten the url before posting it.
The bit.ly API documentation page will help you set up an account and your own api key.
You could then either devise your own code from the official documentation or follow this bit.ly api tutorial by David Walsh

Related

Using a mailto link, how do I prevent Gmail from stripping the = sign and everything after it from the URL's query string?

I am trying to format a mailto link that works with a variety of mail clients. This works with Mac's "Mail" and Thunderbird. However, when I click the link on my Android phone, the query string in the URL is stripped starting with the equals sign. I have tried to add code to specify the content type, to parse the query string and re-add it, etc. So far, nothing works. Here's my code:
<?php
ini_set('default_charset', 'UTF-8');
$BASEURL = strtok($_SERVER["REQUEST_URI"], '?');
echo '
<li><a href="mailto:?subject=An Article Worth Reading: ' . $ALTITLE . '&body=I found this article worthwhile and think you will too:%0D%0A %0D%0A
https://worldviewpublications.org' . htmlspecialchars($_SERVER['HTTPS_HOST']) . $BASEURL . "?" . htmlspecialchars($_SERVER['QUERY_STRING']) . "%0D%0A";
echo '">share with a friend</a></li>
';
?>
I'm pretty proficient in html/css but a beginner with PHP, so I am not at all sure about the efficacy of some of the PHP I added. I'd greatly appreciate any help.
I seem to have found the solution to the problem, which I'm posting below. I've removed the code shared in my initial post that didn't help (in case you're wondering, the nonbreaking space after the colon is for Thunderbird, which does not honor the new line code).
The solution was to encode the = sign. In order to do that, I first extracted the first and last parts of the URL: (1) the first part without the query string and (2) the query string after the = sign. Then I concatenated it back together, spelling out the middle part between the main URL and the unique code at the end of the query string — the question mark (encoded as %3f), the query code identifier (IDN), and the equal sign (encoded %3d). This solution passes the entire URL, including all of the query string, to my gmail client when I'm using my Android phone.
<?php
$BASEURL = strtok($_SERVER["REQUEST_URI"], '?');
$IDEN = ltrim(($_SERVER['QUERY_STRING']), 'IDN=');
echo '
<li><a href="mailto:?subject=An Article Worth Reading: ' . $ALTITLE . '&body=%0D%0AI found this article worthwhile and think you will too:
%0D%0A%0D%0A' . htmlspecialchars("\n\r") . 'https://worldviewpublications.org' . htmlspecialchars($_SERVER['HTTPS_HOST']) . $BASEURL . '%3fIDN%3d' . $IDEN;
echo '">share with a friend</a></li>
';
?>

PHP Advanced Regex Splitting

I'm facing a slight issue with an idea.
I use a chat feature within an online forum on all my computing devices. I also use it mobily, which causes slight issues of formatting, input, etc. I've had the idea to relay all the chat from a relay account to my own mobile friendly site.
I haven't started on sending messages yet, although I know how to read messages. How to output them is the issue.
I sniffed outgoing packets on my computer as the chat uses ajax. I was then able to find the following url: http://server05.ips-chat-service.com/get.php?room=xxxx&user=xxxx&access_key=xxxx
The page outputs something similar to this: ~~||~~1419344231,1,kondaxdesign,Could somebody send a quick message for me__C__ please?,,10248~~||~~1419344237,1,tom.bridges,its a iso and a vm what more do we need to know?,,10880~~||~~
That string would output this in chat: http://i.stack.imgur.com/j7CM6.png
I unfortunately don't have much knowledge on regex, or any other function that would split this. Would anybody be able to assist me on getting the 1). Name, 2). Chat Data and 3). Timestamp?
As you can see, the string is something like this: ~~||~~[timestamp],1,[name],[data],,[some integer]~~||~~
Cheers.
After reading through the string output, when somebody leaves chat, this is sent: ~~||~~1419344521,2,wegface,TIMEOUT,2_10828,0~~||~~
The beginning of the log starts with 1,224442 before the first ~~||~~.
You would first explode each record, then use str_getcsv to read the string and parse it as you want. Here is a script that does that, without any formatting on output, and I've named the variables as named in the OP that describes what they are.
I wouldn't use a regular expression to parse the string, as better functionality is available (linked above)
$string = "~~||~~1419344231,1,kondaxdesign,Could somebody send a quick message for me__C__ please?,,10248~~||~~1419344237,1,tom.bridges,its a iso and a vm what more do we need to know?,,10880~~||~~";
//Split so we have each chat record to loop around
foreach( explode("~~||~~", $string) as $segments) {
//Read the CSV properly
$chat = str_getcsv($segments);
if( count($chat) <> 6 ) { continue; } //Skip any that don't have all the data
$timestamp = $chat[0];
$name = $chat[2];
$data = $chat[3];
$some_integer = $chat[5];
echo $name .' said - '. $data .'<br />';
}

Long e-mail link sent by PHP mailer gets broken

I need to send a very long link using PHP. Known problem: the link is getting broken by the e-mail clients. I've tried it with plain/text or html mails, I put the url in brackets () as proposed in other threads- nothing helps. I know about url shorteners and the possibilty of solving this problem with databases, BUT!!! It IS possible to send links with hundreds of characters; e.g. Ebay does, Amazon does... the link for comfirming the registration from stackoverflow contains more than 250 characters, so?! Looking at the source code of these mails all lines break after 76 characters by default. I've tried to do the same with PHP wordwrap. Result; the source code looks identical, but my links are broken, their links are not! Any ideas? I'd be very glad for help, cause that bothers me!!!! :)
I could solve the problem on my own. First, the special characters of the link must be encoded (e.g. Thunderbird will now accept the encoded link just like this). Second, set a line-break by default after 76 characters. To avoid that the link gets broken or won't be recognized as a link by the client program anymore, each line needs to end on "=" in order to be recombined...
<?php
$url = 'http://domainxy.com/index.php';
$ending = '?var1=gsgsdgsfgdhfjfgj&var2=sdferewerwrr&var3=jghjghjkloozzzz&var4=ghajsldahskhdhriehfsjndfnjnjjfnjsnjdfhksö&var5=öäüöü';
$ending = utf8_encode($ending);
$ending = rawurlencode($ending);
$link = wordwrap( $url . $ending, 75, "=<br />\n", true );
echo $link;
?>
/*
Encodes and devides the link like this:
http://domainxy.com/index.php%3Fvar1%3Dgsgsdgsfgdhfjfgj%26var2%3Dsdferewerw=
rr%26var3%3Djghjghjkloozzzz%26var4%3Dghajsldahskhdhriehfsjndfnjnjjfnjsnjdfh=
ks%C3%B6%26var5%3D%C3%B6%C3%A4%C3%BC%C3%B6%C3%BC
*/

php mail html format link remains inactive

I wanted to make a mail function in php to let visitors create and activate a user account. For this I made a mail with a link which refers to the page that activates the account. Now the problem is that some people want to use characters that interfere with the code inside the email. for example: " " and ' '. I tried to escape these characters, but when such character appears, the link becomes inactive. The mail is sent, but the link is unclickable.
This is what the code looks like.
The variables are set in PHP
$New_user->Username = $db->real_escape_string($_POST['un']);
$RawUn = $_POST['un'];
$New_user->Password = $_POST['pw'];
$New_user->Email = $_POST['em'];
$CheckEmail = explode("#", $New_user->Email);
$New_user->Country = $_POST['cn'];
$New_user->City = $_POST['ct'];
//$NEW_USER IS AN OBJECT CREATED TO HOLD ACCOUNT INFORMATION SUCH AS USERNAME AND EMAIL
//$RAWUN IS A VARIABLE TO HAVE AN UNESCAPED VALUE OF THE USERNAME TO INSERT IN THE INPUT FIELD IF SOMETHING WENT WRONG
After checking the values, the mail is sent:
$message = array(
'Hello ' . $New_user->Username . ',<br/>',
'<br/>',
'Welcome to MakeAMemo.<br/>',
'To start working with your account you will have to activate it.<br/>',
'Just click on the link and you are ready to go.<br/>',
'Log in and check if it works. If not, please contact us(E-mail is on the website).<br/>',
'Your password: ' . $New_user->Password . '<br/>',
'<br/>',
'Kind regards,<br/>',
'<br/>',
'Administration');
$header = array(
'From: makeamemoofficial#gmail.com',
'Reply-To: makeamemoofficial#gmail.com',
'Content-type: text/html');
mail($New_user->Email,"MakeAMemo => New account",implode("\r\n", $message),implode("\r\n", $header));
I have made a connection to the datebase, so the escaping using $db->real_escape_string works fine.
The location of the link will be changed when the website is finished.
I checked if the code worked without the str_replace in the href. No succes. Neither I got succes trying to not escape the username.
The tags are invisible in the mail, so it is recognised. The link is not blocked, because it does work when I don't use special characters. When changing the double quotation marks into single quotation marks, you reverse the effect, which means that instead of " ", ' ' don't work.
I do not think the headers have something to do with it, because the link does work when using normal characters.
Any idea what the cause of my problem is?
Every answer is appreciated.
adear11: here is the generated tag:
link
"s avonds is an incorrect dutch word that contains some of the characters that need to be tested.
Rather than using str_replace in your email, you should use urlencode http://php.net/urlencode
This function is specifically for encoding strings for use in urls
As for the link not always working when it is formed properly, would be that the user isn't using HTML email.
Also, while not specific to your problem, this script is crazy insecure. You never ever ever need to use user supplied input ($_POST in your case) without sanitizing the input first. At a minimum, all of those assignments need to be run through htmlspecialchars.
Update
Given the trouble that you are having, I would consider not passing the actual data around in the URL. Rather, I would save the data to the DB and then generate a token to put in the url. If you generate a token with uniqid you won't have any trouble with these special characters because the string will be alphanumeric. Once the user clicks the link, just grab the data associated with the token and proceed as you would if the data was in the URL.

Undefined offset 1 in Android using PHP

I've looked around on here quite a bit for an answer to my problem but I can't seem to find anything that helps. I'm building an Android application that needs to access student classes through a php script on the server. Each class is made up of a subject, subject number, and section number stored in a mysql database. I send the subject and subject number separated by a '\n' character ("subject\nnumber") to the php script so that it can find and return all sections under that course. Here's the code my script runs:
$course = explode('\n', $_REQUEST['course']);
$sections=mysql_query("select section from class where subj = '".$course[0]."' and number = '".$course[1]."' order by section");
while($e=mysql_fetch_assoc($sections))
$output[]=$e;
print(json_encode($output));
When I pass in the subject and number through my browser with something like
getSections.php?course=CS\n101
It properly formats it into a JSON string and it works perfectly. But when I try to use it with my app, I get an undefined offset: 1 error at line 2. I've wrapped the input string in other characters to make sure that it was sending the same thing as what I try in my browser and it is. It's really boggling my mind why it's not working the way it should.
It's also saying that $output is undefined but I'm pretty sure that's because the while loop is failing.
Any help would be greatly appreciated.
You need to use double quotes for the explode \n ~ explode("\n", $_REQUEST['course']);
Escape characters like newline (\n) only work in double quotes:
echo '\n' prints \n
whereas echo "\n" will print a new line

Categories