getting return data from url - php

I'm trying to submit user information to a URL using GET, and then get the errors (if there any) and use them to tell the customer what went wrong. So, currently I have a form that submits this customer info into an iframe (so the page is not redirected and I can see the response from my shopping cart software). when the info is submitted, this is the response I get from the shopping cart server:
errorFound=1&responseCode=329&...etc.
I need to get this response code, and was wondering what the most simple way would be to do it. Once I get it I can tell the customer what the problem is... Should I use java to read the
data in the iframe once it loads? or can I use something like Fopen to open the URL and get the return data (can't enable fopen on my server though, but something like it?).

Java != javascript
A quick way to do it:
$errorcodes = array("329" => "Wrong blabla");
if( isset( $_GET['errorFound'] ) && isset( $_GET['responseCode'] ) ){
$errorNr = (int) $_GET['responseCode'];
$error = getErrorFromDB();
//OR
//$error = isset( $erorCodes[ $errorNr ] )? $errorcodes[ $errorNr] : false;
if( $error !== false){
exit( "<script type='text/javascript'>
alert( '".htmlspecialchars($error)."' )
</script>");
}
}
function getError( $code )
{
$code = (int) $code;
$db = getYourPdoInstance();
$q = $db->prepare("SELECT `message` FROM `errorCodes` WHERE `errorCode` = ?");
$q->execute( array( $code) );
$return = $q->fetch(2);
return isset($return['message'])?$return['message']:false;
}

Related

Identify Which Item is the Non-Object (PHP Notice: Trying to get property of non-object)

I'm relatively new to PHP and WordPress and this one error message "PHP Notice: Trying to get property of non-object" has been plaguing me, and I'm sure there is an easy fix. Can anybody scan the following code and let me know what could be the source of this error? I'm confident I've narrowed it down to this block of code. Thanks in advance for any help!
// REDIRECT USERS IF THEY ARE IN THE WRONG SPOT
add_action ('template_redirect', 'bee_security');
function bee_security() {
// set the page that people end up on if they try to access the wrong page
$bee_redirecturl = '/private-page/home/';
// get basic user information
$bee_masteruserid = get_user_meta(get_current_user_id(), 'wpcf-user-masteruser', true);
$bee_temppost = get_post($post = get_the_id());
$bee_authorid = $bee_temppost->post_author;
// determine if the current post type is related to households
$bee_posttype_household = substr(get_post_type(), 0, 9);
if ( $bee_posttype_household == "household") {
$bee_posttype_household = true;
} else {
$bee_posttype_household = false;
}
// redirect the user if they are logged in and accessing the front page
if ( is_front_page() && is_user_logged_in() ) {
wp_redirect($bee_redirecturl);
exit;
// redirect the user if they try to access somebody else's househould besides their own
} elseif ( $bee_posttype_household == true ) {
if ( $bee_authorid != get_current_user_id() && $bee_authorid != $bee_masteruserid ) {
wp_redirect($bee_redirecturl);
exit;
}
// redirect the user if they try to make a review on someone else's behalf
} elseif ( get_the_id() == 347 ) {
$bee_childpost = get_post($_GET['childid']);
$bee_childauthor = $bee_childpost->post_author;
if ( $bee_childauthor != get_current_user_id() && $bee_childauthor != $bee_masteruserid ) {
wp_redirect($bee_redirecturl);
}
}
}
one of following values producing a error
$bee_authorid = $bee_temppost->post_author;
OR
$bee_childauthor = $bee_childpost->post_author;
get_post() not returning values, this is could be the reason
I think I finally figured it out. Of course, the minute I finally give up and ask for help, I figure it out! I changed this line:
$bee_authorid = $bee_temppost->post_author;
To this:
$bee_authorid = get_post_field( 'post_author', get_the_id() );
I guess on some pages where a post might not be loading the line was returning null instead of as an object.

Form Post Data As Array Value

I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.
I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.
Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}

Script doesn't get session variable

I made a website using WordPress, and on one page I've included my own script to guide users through a series of steps to calculate an outcome. The scripts are included in this order
Main page -> includes my Wizard.php -> Wizard.php include's Wizard_Step_xx.php
The Wizard reload's new steps every time from Step_01 until Step_10.php, this is done by a jQuery script.
Now my problem is that whenever a user finishis this "Wizard" he gets the option to log in and get redirected to his own page. Now when a user clicks the link to get to the "Wizard" I want to show the users personal page instead of showing him the first step of the wizard which would normally happen.
I've made this simple script that sets a $_SESSION variable when the user logs in :
//Validate Log In
if(isset($_POST['Validate'])) //submit login button
{
$inlog_naam = ( $_POST['inlognaam'] );
$wachtwoord = ( $_POST['wachtwoord'] );
$try = mysql_query("SELECT * FROM xxxx WHERE username = '$inlog_naam' AND password = '$wachtwoord'") or die (mysql_error() );
$result = mysql_num_rows($try);
if($result == 0)
{
$page = ( 8 );
$_SESSION['Invalid_Login_1'] = ( "true" );
}
else
{
$_SESSION['Invalid_Login_1'] = ( "false" );
$user_info = mysql_query("SELECT * FROM xxxxx WHERE username = '$inlog_naam' AND password = '$wachtwoord'") or die ( mysql_error() );
$user_info_result = mysql_fetch_array($user_info, MYSQLI_BOTH);
$user_lastname = ( $user_info_result['contact_Achternaam'] );
$user_id = ( $user_info_result['user_id'] );
$_SESSION['user_id_1'] = ( $user_id );
$_SESSION['user_name'] = ( $inlog_naam );
$_SESSION['user_lastname'] = ( $user_lastname );
$session_id = ( session_id() );
mysql_query("UPDATE xxxxx SET user_id = '$user_id', user_username = '$inlog_naam', user_lastname = '$user_lastname' WHERE session_id = '$session_id'") or die (mysql_error() );
$page = ( 9 );
$_SESSION['user_login'] = ( "true" );
$_SESSION['user_main_screen'] = ( "true" );
}
Now this part of the script works perferct, and the $_SESSION variables gets set.
But when I click on the link to go to the Wizard again I got this script in the Wizard.php file to show the users personal page instead of Wizard_Step_01.php which would normally happen.
if(isset($_SESSION['user_login']) && $_SESSION['user_login'] == 'true')
{
$page = 9;
}
else
{
echo $_SESSION['user_login'];
}
This script doesn't seem to see the $_SESSION variable, though when I click next on this page to go to Wizard_Step_02.php it DOES recognize it.
I've also noticed that for some reason, my site is running 2 PHPSESSID's , I thought I would prevent this by doing this :
<?php if(!isset( $_SESSION )) { session_start(); } ?>
but for some reason it still creates a second PHPSESSID.
If anyone has any idea on how to disable/delete/unset 1 of the 2 PHPSESSID's if this is where the problem lies, or any idea why this is happening....
To be clear: I want to know why my page doesn't find the setted $_SESSION['user_login'] when I load the page. Also any suggestions or any form of help is appreciated.
Thanks for reading.

Creating a client for a chat in PHP

I'm trying to create a PHP chat, so I have server.php that starts the server on the terminal, which is listen to client connections:
<?php
function chat_leave( $sock, $chat_id = 0 )
{
if( $chat_room_id[ $chat_id ] )
{
unset( $chat_room_id[ $chat_id ] );
return true;
}
socket_close($sock);
return false;
}
function client( $input )
{
/*
Simple php udp socket client
*/
//Reduce errors
error_reporting(~E_WARNING);
$server = '127.0.0.1';
$port = 9999;
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
//Communication loop
while(1)
{
//Send the message to the server
if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
//Now receive reply from server and print it
if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
return $reply;
}
}
/*
* chat_join
* a new user joins the chat
* #username: String
* #password: String
*
* add a new listener to the server
*
*/
function chat_join( $username = "", $password = "" )
{
$users = array(
"batman" => "batman123",
"robin" => "robin123",
"joe" => "joe123"
);
if( $users[$username] == $password )
{
return true;
}
return false;
}
function main()
{
$chat_room_id = array();
$username = stripslashes( $_POST['username'] );
$password = stripslashes( $_POST['password'] );
$action = stripslashes( $_POST['action'] );
$port = intval( $_POST['port'] );
$domain = stripslashes( $_POST['domain'] );
$chat_id = intval( $_POST['chat_room_id'] );
if( strcmp( $action, "login" ) == 0 )
{
$status = chat_join( $username, $password );
if( $status )
{
$chat_room_id[] = $chat_id;
echo json_encode( $status );
}
}
else if( strcmp( $action, "chat" ) == 0 )
{
$msg = stripslashes( $_POST['message'] );
// take the message, send through the client
$reply = client( $msg );
echo json_encode( $reply );
}
else if( strcmp( $action, "logout") == 0 )
{
}
else
{
echo json_encode( false );
}
return;
}
main();
?>
The function client() is the code I have from a client.php file, which when I execute on the terminal, is able to send and receive messages from the server.php. Now I would like to use my main.php file, so once the user is logged in he will send messages to the server, which will reply back the messages that user haven't seen.
When I run server.php and client.php from two different terminals, I'm able to send and receive messages, however I would like to do that using main.php, transform that reply message into a JSON object and send back to the html page where it will get appended to a textarea box.
My problem is: how can I get the reply that client.php received and send it back to the html page?
When I execute it on the terminal, I have:
Enter a message to send : hello
Reply : hello
I use AJAX to send the user input in the chat, so I wanted to be able to take that message, and send it to the server, which I started on the terminal and take the reply back and forward to the webpage and append that to the text box area.
How can I accomplish that? Should I start client.php as a service through main.php? Or should I use the client($input) function to send a message and then return what it sends, back?
However, I wanted that client to be running until the use logs out, because other clients may connect to the chat. How can I accomplish that is kind of fuzzy for me. The code in client( $input ) is the same as in client.php.
Sorry for off-topic, but if you can, it would be better to use XMPP ready solution like ejabberd server with http-bind module. Sure, there is some cons it such solution, but cons are greater. Just look in this solution, maybe it will solve your problem with low cost.
see related answer with brief desc on XMPP solution
I think I understand what's going on. Sounds like you might be missing a listener? Usually chat programs have client-side ajax that checks or "listens" for messages for a particular user at regular intervals.
For example, if someone left a message for user x in your database (or wherever you're storing messages), the you might have some javascript that calls a php script every second to see if there are any messages on the server for user x. If there are, you can echo the message or messages back and received them via your ajax callback function.
If you're familiar with jQuery, check out the $.get method: http://api.jquery.com/jQuery.get/
As i understand your question, you want to send a message from the client to the server and as soon as this message gets to the server it will reply to all clients... i'm correct???
I do some chat like using nodejs and other javascripts tech... and must say a great option here is using web sockets. Realize that browser support is limited, but since you not specified what browsers need to run this i think a great way to go.
Check this related links:
How to Use Sockets in JavaScript\HTML?
http://socket.io/
A possible way of doing that only using php + js is make some function and put in a setInterval to make request to the server every 12 seconds. I made some kind of asp chat in 2005 that uses this approach. And i must say the web socket is much better.
I don't know if that answers your question... let me know!
I developed something along these lines before using PHP and jQuery. The solution I went for was due to the restrictions on the server setup(out of my control). I used a PHP core script to create the whole layout of the page from message window to message submission box. Any user that came to the page was given a randomly generated user like user123234234 generated off a unix timestamp from the time they entered the chat page.
All messages submitted were stored in an XML file and a new XMl file was created daily. The user was kept in a message node like below with details of the user for every message using different node attributes.
The message window was refreshed every 5 seconds using jquery AJAX call to another PHP script that read in the XML that days XML file only from the time the user entered the chat page.
<messages>
<message user="user123456" ip="127.0.0.1" session="{users session ID here}" time="{unix timestamp}"><![CDATA[User message here]]></message>
</messages>
There is a lot more logic behind it but I found it the easiest to develop and maintain, I hope it help point you in the right direction. And it works on all major browsers and from IE7+.

How to automatically update google index when content website has changed

Yesterday, i post an 'ad' on an ebay site (marktplaats.nl) and the ad was immediately visible in google when i search for this ad on Google.
How do they do this?
Because it is a very large site, i don't think they repost the sitemap. I have made such function to update the sitemap but don't know this is a good method. What i have is this (part of my library):
// returns false when input invalid, returns a number (array index) when url is invalid or // request fails, returns true when complete:
function suSubmitSitemap( $sXmlUrl, $asSearchEnginePingUrl = 'http://www.google.com/ping?sitemap=%s', $bContinueOnError = false )
{
if( !suIsValidString( $sXmlUrl ) || ( !suIsValidString( $asSearchEnginePingUrl ) && !suIsValidArray( $asSearchEnginePingUrl )))
{ return false; }
$a = (is_array($asSearchEnginePingUrl))?$asSearchEnginePingUrl:explode(',', $asSearchEnginePingUrl );
$sXmlUrl = urlencode( $sXmlUrl );
$ret = false;
foreach( $a as $i=>$sUrl )
{
$sUri = str_replace( '%s', $sXmlUrl, $sUrl );
$bValid = (!is_bool( strpos( $sUrl, '%s' )) && suGetUrlContent( $sUri ));
if( !$bValid )
{
if( !$bContinueOnError )
{ return $i; }
if( !is_array( $ret ))
{ $ret = array(); }
$ret[$i] = $sUri;
}
}
return ret;
}
Is this a safe way to do this (Google will not ban you when frequently called), when this is not the way to do it, does anyone know how implement such index update functionality in PHP?
Google will constantly crawl frequently updated/popular sites and update their search results. This has the benefit of making Google more relevant.
Resubmitting your site map will not help you get crawled as fast as Ebay. Get more visitors and post content more frequently to get Google to visit your site more often.
Also, check out:
http://www.google.com/support/webmasters/bin/answer.py?answer=48620
http://www.searchenginejournal.com/10-ways-to-increase-your-site-crawl-rate/7159/

Categories