xcode updating mysql remote database using PhP - php

I have been following this great tutorial and got my codes to working with most of the database transfers. Now I'd like to use the same method to update long text messages and images onto my server MySQL database, but it doesn't seem to work.
NSString *strURL = [NSString stringWithFormat:#"http://mydomain.com/sync.php?name=%#&message=%#&image=%#",nameField.text, messageField.text, image];
and then
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"StrResult is... %#", strResult);
Problem 1: When the messageField.text is a long text with blank spacing in between such as "This is a free text format with up to 1000 characters..." , it will cause strURL to have blank spaces as well, and thus strResult will become null.
Problem 2: image is of blob format which I already saved in the local sqlite. I'm not even sure if transferring this way is a good idea. But basically I want to upload the image from iPhone/iPad straight onto a server MySQL database.
Hope someone could help me with either one of these 2 problems. Or are there any better and easier alternatives to update MySQL on my server? Thank you!

Problem 1 : When you are sending parameters through a GET request, you need to escape your parameters to avoid illegal characters. By the way, you can not send unlimited data with this kind of request. For a large amount of data, you should rather use a POST request.
Problem 2 : ASIHTTPRequest is a wrapper used to communicate with remote servers. If you choose to use it (I encourage you to do), here is the documentation that you will need to POST a request . There is also an example to send an image to a remote server with NSData.

Problem 1: there's a lot of ways to do this... one of them are when you put it into the database do this:
messageField.text = [messageField.text stringByReplacingOccurrencesOfString:#" " withString:#"_"];
Maked the text: "This is a free text format with up to 1000 characters..." to: "This_is_a_free_text_format_with_up_to_1000_characters..."
And then when you take it out of the database again use the code opposite:
messageField.text = [messageField.text stringByReplacingOccurrencesOfString:#"_" withString:#" "];
That makes it from: "This_is_a_free_text_format_with_up_to_1000_characters..." to "This is a free text format with up to 1000 characters..."
But remember thats one way to do it... you can also replace the "_" with Something else like"I" or whatever you want.. something the user won't type...
Problem 2: I don't know a lot about databases and images.. but se this: Blob
:)

Related

Save photo to SQLite database and have PHP read it and display it

I want to be able to take a photo with the camera or select one from photos and save it to an SQLite database. I then want to be able to have a PHP server show this image. I tried to convert the image to a string to save it to the SQLite database.
// convert image to String.
[UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
I want to have the PHP server show the image but for some reason it won't work. I think it's because the string is larger than 20 characters. Please help me find a solution.
Please check your php.ini file and modify following 2 parameters
upload_max_filesize
post_max_size
See the documentation here
or if you haven't access to php ini file try change them with ini_set function.
Convert UIImage to NSString:
NSData *dataObj = UIImagePNGRepresentation(image);
NSString *imgString= [dataObj base64Encoding]; //base 64 string conversion
Store this string to local database. Send this string to PHP server.
In PHP server convert this string to image using base64 encoding.

NSString Convert Emojis to HTML Entities

I have an iOS app and PHP web service that take a user submitted "password" and hash it.
The problem arises when you enter an emoji:
PHP hashes the salt + 😍
iOS hashes the salt + [heart-for-eyes smiley emoji]
Is there a way to convert the emoji on iOS to the corresponding HTML Entity (like PHP does automatically) so that the resulting hash values are the same?
stringWithUTF8String does not work
NSNonLossyASCIIStringEncoding converts it to "\ud83d\ude0d"
Here is a solution, perhaps there is a built-in:
NSString *emojiString = #"😍";
NSLog(#"emojiString: %#", emojiString);
NSData *codePointData = [emojiString dataUsingEncoding:NSUTF32LittleEndianStringEncoding];
u_int32_t codePoint = *((u_int32_t *)(codePointData.bytes));
NSString *escapedEmoji = [NSString stringWithFormat:#"&#%d", codePoint];
NSLog(#"escapedEmoji: %#", escapedEmoji);
NSLog output:
emojiString: 😍
escapedEmoji: &#128525
This based on the fact that the escaped emoji is the decimal number of the code point. The binary code point is the UTF-32 encoding of the unicode character.
Unfortunately I was not able to find a pre-existing solution.

Data Image base 64 [duplicate]

This question already has answers here:
Should I embed images as data/base64 in CSS or HTML
(7 answers)
Closed 9 years ago.
Could someone please explain how does this work?
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACDUlEQVR4Xu2Yz6/BQBDHpxoEcfTjVBVx4yjEv+/EQdwa14pTE04OBO+92WSavqoXOuFp+u1JY3d29rvfmQ9r7Xa7L8rxY0EAOAAlgB6Q4x5IaIKgACgACoACoECOFQAGgUFgEBgEBnMMAfwZAgaBQWAQGAQGgcEcK6DG4Pl8ptlsRpfLxcjYarVoOBz+knSz2dB6vU78Lkn7V8S8d8YqAa7XK83ncyoUCjQej2m5XNIPVmkwGFC73TZrypjD4fCQAK+I+ZfBVQLwZlerFXU6Her1eonreJ5HQRAQn2qj0TDukHm1Ws0Ix2O2260RrlQqpYqZtopVAoi1y+UyHY9Hk0O32w3FkI06jkO+74cC8Dh2y36/p8lkQovFgqrVqhFDEzONCCoB5OSk7qMl0Gw2w/Lo9/vmVMUBnGi0zi3Loul0SpVKJXRDmphvF0BOS049+n46nW5sHRVAXMAuiTZObcxnRVA5IN4DJHnXdU3dc+OLP/V63Vhd5haLRVM+0jg1MZ/dPI9XCZDUsbmuxc6SkGxKHCDzGJ2j0cj0A/7Mwti2fUOWR2Km2bxagHgt83sUgfcEkN4RLx0phfjvgEdi/psAaRf+lHmqEviUTWjygAC4EcKNEG6EcCOk6aJZnwsKgAKgACgACmS9k2vyBwVAAVAAFAAFNF0063NBAVAAFAAFQIGsd3JN/qBA3inwDTUHcp+19ttaAAAAAElFTkSuQmCC
And how does this generate an image and how to create it? I found this a lot of times in html.
Follow up question
How does this differ on a url as a src in terms of loading time and http request?
does this make loading time faster? How would it scale if i am to use, say 50 images?
Also.
if this is better
in uploading, converting images to base64 and saving it on database rather than a url would make a site better?
You can use it like this:
<img alt="Embedded Image" src="data:image/png;base64,{base64 encoding}" />
It's used to generate new images, or to store images as plain text. You can read more about base64 encoding here on Wikipedia:
http://nl.wikipedia.org/wiki/Base64
How does it work?
The characters are converted to binair
They take a group of 6 bits
The groups will be converted to decimal
For each decimal they take the number on the position n+1 which is in the base64 character table, the numbers variate between 0 and 63.
It does not always come out correctly, since the number of bits must be a multiple of 6. If this is the case, there will be, depending on the required number of additional bits, put 2 or 4 zeros at the end. If so, there will be added a = at the end.
Base64 character table
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
Different languages and usage
PHP
<?php
base64_encode($source);
// Or decode:
base64_decode($source);
Python
>>> import base64
>>> encoded = base64.b64encode('data to be encoded')
>>> encoded
'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
'data to be encoded'
Objective C
// Encoding
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(#"%#", base64String); // Zm9v
// Decoding
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedString); // foo
The bit after the "base64," is a base64 encoded version of the binary png. Since your question is tagged PHP, here's how you would do that in php:
<?php
$img = file_get_contents('img.png');
echo "data:image/png;base64,".base64_encode($img);
How does it generate an image?
First off, the src of the image is recognized by the browser as a Data URI. It then tries to parse the Data URI (see how chrome(ium) does it here. The parser parses the URI, finds that it is a base64 encoded image and decodes it using a base64 decoder into a binary object. This is equivalent to any normal image file. This binary object is used subsequently while rendering the page.
How does this differ on a URL as a src in terms of loading time and HTTP request?
Since there are no HTTP requests made and the image data is already in memory data URIs should load significantly faster.
Does this make loading time faster? How would it scale if i am to use, say 50 images?
The page loading time? Depends. Base64 encoding string is about 2-3 times larger than the original string. That means more data is transferred with the page load. Also, data URI images are not cached in the browser! So that means it has a clear disadvantage if you have to show this image on different pages - because you have to serve base64 content every time! Instead you could have simply set cache headers on your image data types and simply served it once, and let the browser take the image from memory/cache in subsequent page loads. It really depends on your specific usage. But, you now know the intricacies of base64 encoded data URIs.
Summing it up
+
Easier to generate/store
Has a fixed charset
Smaller perceived loading times
-
More data transferred
Require decoding by the browser
No caching
Format: data:[<MIME-type>][;charset=<encoding>][;base64],<data>
This method is called data URI scheme, it is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources. It is a form of file literal or here document (is a file literal or input stream literal). This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient.
Ref: http://en.wikipedia.org/wiki/Data_URI_scheme
Ref: http://en.wikipedia.org/wiki/Here_document

Correct way to pass string from web page, to php and then to Obj-C Command Line Tool

Preface:
I've a web page with a form and a text field.
1) On submission, the text in the field is sent with ajax to a php script (with GET method).
2) The php script gets the text and passes it as a parameter to a shell tool.
3) The shell C tool parses argc into an array of unichars (actually an NSString in my current implementation)
(4.. 5.. 6.. then the tool does his job, returns a result to stdout that the php script serves back as response to the web page...)
I'm looking for the correct / canonical / "unicode" way to do each step so that: content is properly encoded and preserved, no security issues come out.
What I'm doing now:
1) (JavaScript) the text is retrieved from the form this way
theText = $('#theField').attr('value');
and sent to the server this way
httpReq.open('GET','myScript.php?theText=' + encodeURIComponent(theText),true);
2) (PHP) I get the text
$theText=(isset($_GET["theText"])?$_GET["theText"]:"");
I call the C tool
$cmd = "/usr/bin/thetool -theText ".escapeshellarg($theText);
echo shell_exec( $cmd );
3) (Objective-C) I'm on MacOS X, so I take advantage of NSString and NSUserDefaults classes (but a plain C solution would be good for me as well, assumed that I'll end up with an array of unichars)
int main(int argc, const char * argv[])
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *theText = [userDefaults stringForKey: #"theText"];
Question(s)
Is this the good way?
Is escapeshellarg alone safe when invoking shell_exec?
Am I going to lose some characters along the way if the user types something peculiar?
Waiting from a competent reply, I've started making some empiric tests...
First I changed
echo shell_exec( $cmd );
to
echo $cmd;
to see what the command line invocation was turning out to be given various text entered in the form. It seem that escapeshellarg on the PHP side do a good job.
The text passed to the Tool seems to be always properly sealed between single quotes, with "dangerous" character well escaped. I found no way to tamper with the tool invocation.
Then I tested for the text passed to see if something was getting lost somewhere.
I set up the C tool this way and looked for the output
int main(int argc, const char * argv[])
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *theText = [userDefaults stringForKey: #"theText"];
int i;
unichar c;
for(i=0;i<[theText length];i++)
{
c = [searchString characterAtIndex:(NSUInteger) i];
printf("%d\n",c);
}
return 0;
}
Made various tries. It seems all ok. As the last test I entered a "MUSICAL SYMBOL G CLEF" in the form
http://www.fileformat.info/info/unicode/char/1d11e/index.htm
It turned out to correctly end into the tool as a couple* of unichars
55348
56606
(* being this a very special character whose code exceeds 65535 it need to be represented with a couple of surrogate unichars. This is the most edge case I found).
Anyway as I stated at the beginning these are just empiric tests. I don't like to assume that sensible code is good just beacuse passes a dozen of test. I'd very happy to receive comments or suggestions (or warnings!).
I tested on Mac OS X - Firefox on the client side - Mac OS X - Mamp on the server side.

Objective-C / Cocoa bridge in PHP?

Is there any good Objective-C or Cocoa Bridge/Connector for PHP? I'm interested in Mac development, but want to do it with PHP. It'd be also good if you could recommend me any PHP compiler for Mac.
Note: I already know Titanium-like apps, and that's not what I want.
Thanks.
Looks like there's one here: http://www.slideshare.net/wezfurlong/hot-chocolate-you-got-cocoa-in-my-php
(download link is in the slides)
There's little in PHP that is going to do you any favors with Mac development, though. If you want to do Mac development with a language that has a more familiar syntax and you don't want to deal as much with memory issues and such, doing your coding with MacRuby or RubyCocoa shouldn't be too much of a jump from previous PHP experience.
Unfortunately I wasn't able to get the wezfurlong-Bridge running under Mac OS X Lion. So I decided to use the flexibility of Objective-C to let PHP talk to my Cocoa application, even create objects and send messages with arguments to them.
You can get the source including the (very basic) sample application on http://github.com/cundd/pop/
I "bridge" PHP like this… simplicity is golden.. If you wanna get fancy, JSON encode things back and forth, and send raw data as base64 encoded strings…
- (NSString *)getSomethingFromPHP {
NSString *scriptPath = [[[NSBundle mainBundle]resourcePath]
stringByAppendingPathComponent:#"myPHPscript.php"];
NSString *standardIn = [myApp someData]
NSTask *php = [NSTask new];
NSPipe *pipe = [NSPipe new];
[php setLaunchPath:#"/usr/bin/php"];
[php setArguments:[NSArray arrayWithObjects:
#"-f", scriptPath, standardIn, nil]];
[php setStandardOutput:pipe];
NSFileHandle *handle = [pipe fileHandleForReading];
[php launch];
NSString *string = [[NSString alloc] initWithData:
[handle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
return string;
}

Categories