JSON Encode characters in PHP - php

I am trying to return a value using php and AJAX but I get the following returned when doing so. This part of my code has been functional in previous projects so I am a little stumped as to why it is happening now.
The returned value:
‹������«VÊÏV²2ÔQ*.)V²qjÜ¥5¼���
it should return something like this:
{"ok":1,"status":"ok"}
The PHP I am using:
$response = array('ok' => 0);
if($results)
{
$response['ok'] = 1;
$response['status'] = ($visible == 'visible') ? 'ok' : 'no';
}
ob_clean();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($response, true);
exit;
Now if I removed the code and put into its own file it works fine. I have all files and database set to UTF-8 also.

You have a duplicate closing parentheses on line 2.
It should be:
$response = array('ok' => 0);
if($results)
{
Fixing that, your code works for me:
{"ok":0}
And if I force $results = true; :
{"ok":1,"status":"no"}

I feel so stupid now, I was running ob_gzhandler within my ob_start();
Apologies to all.

Related

PHP generated calendar in Google Calendar - not valid URL

I am a bit new to PHP.
I am trying to filter a ICS file for events containing a certain string. The following script seems to do that job just fine:
<?php
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=fodda2009.ics');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
function icsFilter($paramUrl,$filterstring) {
$icsFile = file_get_contents($paramUrl);
$icsData = explode("BEGIN:", $icsFile);
foreach($icsData as $value) {
if (strpos($value, "VEVENT") === FALSE) {
echo "BEGIN:";
echo $value;
}
else {
if (strpos($value, $filterstring) !== FALSE) {
echo "BEGIN:";
echo $value;
}
}
}
}
?>
<?php echo icsFilter('http://cal.laget.se/ALMTUNAISHOCKEYSKOLA.ics','dda 2009'); ?>
VEVENT
DESCRIPTION:Dummy info
DTEND;TZID=W. Europe Standard Time:20001010T121500
DTSTAMP:20001005T192952Z
DTSTART;TZID=W. Europe Standard Time:20001010T110000
SUMMARY:Dummy event
UID:200abc01010T110000-8918999#stackoverflow.com
END:VEVENT
END:VCALENDAR
I am hosting the script at http://mydomain.dyndns.com/mycalendar.php. When I enter that URL into Google Calendar (other calendars -> add by URL) I receive a message "[your URL] is not a valid URL".
Is this caused by the script ending in .php?
Do I need to convince my server (Apache) to call the php script at a http://mydomain.dyndns.com/mycalendar.ics URL? How? Is there something else I am doing wrong?
OK, this is a little embarrassing...
The code above works just fine, the source of my error was that I left out the "http://" from the URL. Thus Google Calendar complained that it wasn't a good URL. cough Adding "http://" to my URL worked wonders :)
I'll leave the script here, maybe someone else wants to have a simple PHP script to filter an existing iCal file and serve it to Google Calendar.

(PHP) setcookie get error "Premature end of script headers"

I created a PHP script that reads the data from mysql database and returns an output in json format.
The script works fine, but now I want to save the output in my cookie.
When I add the function setcookie("Messages",base64_encode(serialize($messages)),157680000000);
I have a Server Error 500 : Premature end of script headers.
How can I save the array $messages in the cookie?
----------------- PHP CODE -------------------
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
include_once("include/common.php");
if (empty($uname)){
$uname = (!empty($_GET['u'])) ? $_GET['u'] : "";
$uname = (!empty($_POST['u'])) ? $_POST['u'] : $uname;
}
if (empty($limit)){
$limit = (!empty($_GET['limit'])) ? $_GET['limit'] : "";
$limit = (!empty($_POST['limit'])) ? $_POST['limit'] : $limit;
}
$isonline = is_online();
$user_obj = new User();
$user_info = $user_obj->getUserInfo($uname);
$msg_obj = new Message();
$msg_array = $msg_obj->getMessages($user_info[_USERID_COLUMN],$limit);
$messages = array();
$i = 0;
[...]
foreach( $msg_array as $id => $val ){
$messages[$i]['id_message']=$val['id_message'];
$messages[$i]['user']=$val['user'];
$messages[$i]['user_image']=$val['user_image'];
$messages[$i]['posted_time']=time2str($val['posted_time']);
if($options['link'] == "off"){
$messages[$i]['message']=htmlspecialchars_decode(cleaner($val['message']));
}else{
$messages[$i]['message']=htmlspecialchars_decode($val['message']);
}
$messages[$i]['mediatype']=$val['mediatype'];
$messages[$i]['mediaurl']=$val['mediaurl'];
$i++;
}
array_reverse($messages);
if(ceckCookie()){
setcookie("Messages",base64_encode(serialize($messages)),157680000000);
}
if( !$isonline && !empty($_COOKIE["Messages"]) ){
echo($_COOKIE["Messages"]);
}else{
echo(json_encode($messages));
}
is the data you are trying to save is huge ??
$_COOKIE can store under 4000 bytes...(Includes date, name, value, expiry) ..

php index.php, add to cart issue

I am having trouble executing this code in my index.php.
It says 'CartAction not set'
I need your help php gurus. I can display any files you need to fix this error.
Here is the code:
// Handle AJAX requests
if (isset ($_GET['AjaxRequest']))
{
// Headers are sent to prevent browsers from caching
header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // Time in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html');
if (isset ($_GET['CartAction']))
{
$cart_action = $_GET['CartAction'];
if ($cart_action == ADD_PRODUCT)
{
require_once 'C:/vhosts/phpcs5/presentation/' . 'cart_details.php';
$cart_details = new CartDetails();
$cart_details->init();
$application->display('cart_summary.tpl');
}
else
{
$application->display('cart_details.tpl');
}
}
else
trigger_error('CartAction not set', E_USER_ERROR);
}
else
{
// Display the page
$application->display('store_front.tpl');
}
It's because your code is expecting a parameter named 'CartAction' in the url
Example:
www.yoursite.com/?CartAction=ADD_PRODUCT
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Source
You check if $_GET['CartAction'] has a value ( from the above url this superglobal variable has the value 'ADD_PRODUCT' )
What #Mackiee (in comments) and your error message are both telling you is that the problem is that there is a query parameter missing. The URL that calls this needs to include either ?CartAction=ADD_PRODUCT or &CartAction=ADD_PRODUCT

File get content via json

I have a file text file in which i am saving user id via file_put_contents
i want to display that user id before sending it to view function
here is my code
i try myself bt not geting result....
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name)));
$response = array();
$response = json_decode(file_get_contents($filename));
if ($response->name==1){
echo $this->session->userdata('name');
}
echo json_encode($response);
this dont work that i want to display bt if i remove this if condition then i get my result in view file
if ($response->name==1){
echo $this->session->userdata('name');
}
thanks....
$response->name it will be a string, not an int.
Replace:
if ($response->name==1){
echo $this->session->userdata('name');
}
With:
if ($response->name){
echo $this->session->userdata('name');
}
Update:
You stated somewhere in the comments that you want to check for the user id, but in the code you check username. Also inside the if condition, you should use data from $response and not the one from session. That said:
if ($response->id == 1){
echo $response->name;
}
As a side note, are you sure that id and name exists in the session ?
im not clear why do you have
if ($response->name==1){
but any way try this
if you want to prezerve json object stucture you need the second param to be true
json_decode(file_get_contents($filename) ,true);
and you need some json headers that you can find in the botom
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
if(!empty($name)){
if(!is_file($filename)){
touch($filename);
chmod($filename,0777);
}
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name),true));
$response = array();
$response = json_decode(file_get_contents($filename) ,true);
if (empty($response->name)){
echo json_encode(array('error'=>'empty response name'),true);
die();
}else{
echo json_encode($response);
}
}else{
json_encode(array('error'=>'no username'),true)
}
there is my messaging system inside my admin its for codeigniter
http://dl.dropbox.com/u/72626795/messaging.zip

xmlhttprequest onlys gets to status 3

I have a simple search form with a search box and a result box.
When I type a search word a request is created like: http://www.site.com/php_handler.php?s=hello
In the php script and a result is given back to the script this way:
<?php return $s; ?>
The problem is that my htmlrequest stops at readyState 3 it doesn't get to 4.
The javascript looks like this:
var xmlhttp = sajax_init_object();
function sajax_init_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
if (!A)
sajax_debug("Could not create connection object.");
return A;
}
function getSearchItem()
{
gs=document.forms.mainform.resultsfield;
var searchword=document.forms.mainform.searchform.value;
if (searchword.length>=3)
{
setWaitCursor();
clearResults();
var uri = "http://site.com/ajax_handler.php?s="+searchword;
console.log(uri);
xmlhttp.open("GET", uri, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
processResults(xmlhttp.responseText);
removeWaitCursor();
}else{
console.log(xmlhttp.readyState);
}
}
xmlhttp.send(null);
}
else
{
alert("please add at least 3 characters .");
}
}
Can someone tell me why it stops at 3?
edit: here is also the php code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
session_start();
//include main file
require_once($_SESSION["FILEROOT"] . "xsite/init.php");
//check if formulier is posted
$zoekterm = C_GPC::getGETVar("s");
$s="";
if ($zoekterm != "") {
$query="SELECT number,name,city,zib,zip_annex FROM articles WHERE version='edit' AND (naam LIKE '%$school%' OR brinnummer='$school') ORDER BY name";
if ($rs=C_DB::fetchRecordSet($query)) {
while ($row=C_DB::fetchRow($rs)) {
if ($row["plaats"]!="") {
$s.=$row["name"].", ".$row["city"]."|".$row["number"]."\n";
} else {
$s.=$row["name"].", ".$row["zip"].$row["zip_annex"]."|".$row["number"]."\n";
}
}
}
}
return $s;
?>
edit:
I missed a semicolon in my php script and now the ready state only gets to 2
edit:
The problem is even different. It gets to 4 but it doesn't show the result text.
1> Don't send Cache-Control: post-check=0, pre-check=0. These don't do what you think they do, and they're entirely unnecessary.
2> Your AJAX results page needs to send a Content-Length or Connection: Close header.
3> Try adding a random to your request URL to ensure you're not looking at a stale cache entry.
ReadyState 3 => Some data has been received
ReadyState 4 => All the data has been received
Maybe the XMLHTTPRequest object is still waiting for some data.
Are you sure your php script ends correctly ?
Is the content-length alright ?
To debug this you have two options, type the URL directly into the browser [since you are using a GET] and see what is happening.
OR
You can use a tool such as Fiddler and see what is exactly happening with the XMLHttpRequest

Categories