Bing API Invalid argument supplied for foreach() - php

This has been asked before but no solution given.
I have created an account with https://datamarket.azure.com/account/keys and I have a primary account key and a customer id.
I got the code below from https://msdn.microsoft.com/en-gb/library/dd440739.aspx
I have tried replacing <yourAppIdHere> with the values of both the primary account key and the customer id, but in each case get Invalid argument supplied for foreach().
What am I missing here? Please help.
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>PHP Bing</title>
</head>
<body><form method="post" action="<?php echo $PHP_SELF;?>">
Type in a search:<input type="text" id="searchText" name="searchText" value="<?php
if (isset($_POST['searchText'])){
echo($_POST['searchText']); }
else { echo('sushi');}
?>"/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit'])) {
$request = 'http://api.search.live.net/json.aspx?Appid=<YourAppIDHere>&sources=image&query=' . urlencode( $_POST["searchText"]);
$response = file_get_contents($request);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->SearchResponse->Image->Results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->Url . '">');
echo('<img src="' . $value->Thumbnail->Url. '"></li>');
}
echo("</ul>");
} ?>
</form>
</body>
</html>

Related

PHP post data to user custom url without as an array

simply i can use this below code to post any result as an array with message as json format for example:
array('result'=>"{'code':'101', 'message':'ok!!'}")
this format result for my users is not standard and they like to get the result only as an json format for example:
{'code':'101', 'message':'ok!!'}
I can't find other code to instead of my code for return the result
My code:
function redirect_to_customer($result = [], $redirect_url = "")
{
$html = '<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body onload="closethisasap();">
<form name="redirectpost" method="POST" action="' . $redirect_url . '">
';
if (!is_null($result)) {
$result = json_encode($result,true);
$html .= '<input type="hidden" name="result" value="' . str_replace('"', "'", $result) . '"> ';
}
$html .= "
</form>
</body>
<script type=\"text/javascript\">
function closethisasap() {
document.forms[\"redirectpost\"].submit();
}
</script>
</html>";
echo $html;
}
You can post an array in a html form, by using brackets in the field's name:
<form action="" method="post">
<input type="hidden" name="result[]" value="'code':'101'" />
<input type="hidden" name="result[]" value="'message':'ok!!'" />
<input type="submit" value="submit" />
</form>
Will output:
array(1)
["result"]=>
array(2) {
[0]=>
string(12) "'code':'101'"
[1]=>
string(16) "'message':'ok!!'"
}
}

Accessing PHP Session Variables in Multiple Files

I have a school project where I'm trying to use session variables to save a log in ID, however I can't seem to access the session variables across files. I'm relatively new to sessions, but have gotten them to work in simpler applications on the same server that I am using for this project. The program works as follows:
getData.php is the log in form where the user enters their ID and password.
front.php collects data from this form and forwards it to another server (of another group member) using php curl. Since this is not my part, I do not have this code.
After accessing a database, information from the database is forwarded back to me, also using curl and I format it in a table, in tList.php.
The problem is that the session variables do not seem to be accessible between the files on MY SERVER. The exact goal I am trying to accomplish is to access the session variables that I create in front.php on tList.php, however the variables are not set even though I assign them in front.php.
Any help would be greatly appreciated. Thank you.
getData.php:
<?php
session_start();
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/b.css">
<link href="../css/test.css" rel="stylesheet" type="text/css">
</head>
<body>
<script type="text/javascript">
function status_toggle() {
if(document.getElementById('stud').checked) {
document.getElementById('sl').style.display='block';
document.getElementById('tl').style.display='none';
} else if(document.getElementById('teach').checked) {
document.getElementById('sl').style.display='none';
document.getElementById('tl').style.display='block';
}
}
</script>
<!-- Status Selection -->
<form name="radio" class="nav selection_form" action="" align="center">
<div align="center" class="">
Are you a <br>
Student <input id="stud" type="radio" name="status" value="student" onclick="javascript:status_toggle();" checked>
&nbsp&nbsp&nbsp or &nbsp&nbsp&nbsp
Teacher <input id="teach" type="radio" name="status" value="teacher" onclick="javascript:status_toggle();">
</div>
</form>
<!-- Student Form -->
<form id="sl" name="student_login" action="front.php" class="input-block my_form" autocomplete="on" method="post">
<div align="center">
Username: <input type="text" name="txtUCID" size="15" /><br />
Password: <input type="password" name="txtPasswd" size="15" /><br />
<p><input class="btn-red" id="submit" type="submit" value="Login" /></p>
</div>
</form>
<form style="display:none" id="tl" name="teacher_login" action="front.php" class="input-block my_form" autocomplete="on" method="post">
<div align="center">
Username: <input type="text" name="teacherTxtUCID" size="15" /><br />
Password: <input type="password" name="teacherTxtPasswd" size="15" /><br />
<p><input class="btn-grn" id="submit" type="submit" value="Login" /></p>
</div>
</form>
<div align="center" class="alert_box input-block my_form">
<h2 align="center" type="text" id="local_db"> change me!</h2>
<h2 align="center" type="text" id="njit_db"> change me!</h2>
</div>
</body>
</html>
front.php:
<?php
session_start();
$un = $_POST["txtUCID"];
$pw = $_POST["txtPasswd"];
$_SESSION['id'] = $un;
$curl = curl_init('web.njit.edu/~mc332/cs_490/loginSTD.php');
$postData= array(
'txtUCID' => $un,
'txtPasswd' => $pw
);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 0,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_MAXREDIRS => 5
));
echo $_SESSION['id'];
$result = curl_exec ($curl);
curl_close ($curl);
tList.php
<?php
session_start();
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="list.css">
</head>
<body>
<div class="header">
Your Tests
</div>
<div class="list-view">
<?php
echo "SV: ".$_SESSION['id'];
$result = $_POST['tests'];
echo "<table>";
echo "<tr><th>Test ID</th><th>Test Name</th><th>Attempted</th><th>Score</th><th> Attempt Test </th></tr>";
$json = json_decode($result);
$i = 0;
while($i < count($json)) {
$id = $json[$i][0];
$name = $json[$i][1];
$tId = $id;
echo "<tr> <td> $id </td> <td> $name </td> <td> ? </td> <td> ?/100 </td> <td> <form method=\"post\" action=\"goToTest.php\" id=\"form$tId\"><button type=\"submit\">Take Test</button></input><input type=\"text\" style=\"display: none;\" name=\"poop\" value=\"$tId\"></input></form></td> </tr>";
$i++;
}
echo "</table>";
echo "end";
?>
</div>
</body>
</html>
Here is the working application:
file1:
<?php
session_start();
$_SESSION['test'] = "test";
echo "Click";
?>
file2:
<?php
session_start();
echo $_SESSION['test'];
?>
The session_start() function must appear BEFORE the tag
<?php session_start(); ?>
<html>
<body>
</body>
</html>
http://www.w3schools.com/php/php_sessions.asp
Try this to make sure you are passing valid values into the SESSION variable.
<?php
session_start();
if (!empty($_POST["txtUCID"])){
$_SESSION['id'] = $_POST["txtUCID"];
} else {
$_SESSION['id'] = 'no value set';
}
echo $_SESSION['id'];

Using Strip Tags and check for empty fields PHP

So i have a form here, and I want on the to do some php so that if the field is empty, it will say once you submit the form after it loads to the post page, that sorry you entered no date. I also want to add strip tags, however I am unsure how, if they go on the posting_wall or if they go in the form.php? I want to use strip all tags.
I believe the empty validation was if(!empty(($date)) { echo "sorry you did not enter a date"; } but i could not get it to work.
Thank you in advance if you can help me with this. I will post the form.php and the posting wall below.
Form.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="index.php" method="get">
<div id="container">
Username:*<input type="text" name="name" pattern="{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail:* <input type="email" name="email" maxlength="20" required><br>
Post:*<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
Your favorite website is: <input type="text" name="website">
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p> Fields with * next to them are required </p>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting wall
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/heaader.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News </h1>
<h2> You're best place for the latest dorm news from campus </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
This event happened :<?php echo $_GET["date"]; ?><br>
Your gender is:<?php echo $_GET["gender"]; ?><br>
Your favorite website is: <?php echo $_GET["website"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$post_fields['gender'] = $gender;
$post_fields['website'] = $website;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<div id="logo"> Don't forget to tell all you're friends about Daily Dorm News! <br> The only dorm news website on campus!</div>
<p id="received">Here are all the posts we have received.</p>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
$gender = $post['gender'];
$website = $post['website'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>Your a '.$gender.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>You said your favorite website is '.$website.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php require 'footer.php' ?>
</body>
</html>
You can check through jquery in the submit function
var datepicker=$("#datepicker").val();
if(datepicker=='') { alert('Please enter date'); return false; }
It should be
if(empty(($date)) {
echo "sorry you did not enter a date";
}
NOT
if(!empty(($date)) {
echo "sorry you did not enter a date";
}
The first expression will print "sorry you did not enter a date" if the date field is empty. The second expression will print that message if the date field is not empty.
You can try the code below. It will print 'This is an empty string'
<?php
$date = '';
if (empty($date)) {
echo 'This is an empty string';
}
if (!empty($date)) {
echo 'The date is ' . $date;
}

Can I pass a variable in a Meta Http Equiv Refresh?

I just finished this script it works well, but I am struggling to pass along the $invite variable to the register.php page. Can someone please tell me how I can achieve this? I have it defined as $invite = $_POST['inviteinput'];
How do I get the users input from index.php to transfer to register.php? Thank you for your help!
HTML FORM:
<form action="index.php" method="post">
What is your Invite Code?<BR />
<input class="textbox" name="inviteinput" type="text" />
<BR />
<input type="hidden" name="formsubmitted" value="TRUE" />
<input name="Submit" type="submit" value="Verify" />
</form>
PHP:
<?PHP
include ('scripts/dbconnect.php');
if (isset($_POST['formsubmitted'])) {
if (empty($_POST['inviteinput'])) {
echo '<div class="errormsgempty"><u>ERROR</u>:<br>You must enter a valid invite code to proceed!</div>';
} else {
$invite = $_POST['inviteinput'];//else assign it a variable
$invite = stripslashes($invite);
$invite = mysql_real_escape_string($invite);
$sql = "SELECT yourMemberId FROM Register WHERE yourMemberId='$invite'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=register.php">';
} else {
echo '<div class="errormsgbox"><u>ERROR</u>:<br>The Invite Code you entered ' . $invite . ' is NOT a valid invite code!</div>';
//($notvalidcode = "The Invite Code you entered <strong>" . $invite . "</strong> is NOT a valid invite code!");
}
}
}
?>
Absolutely. Just add it to the URL:
<meta http-equiv="Refresh" Content="0; url=register.php?var=value&othervar=hello" />
Note that you may be better off using:
header("Location: register.php?var=value&othervar=hello");
exit;
There are a few ways
Save it in a session
session_start();
$_SESSION['invite'] = $invite;
2nd is you can pass it via get
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=register.php?invite=' . $invite . '">';
I would recommend option 2.
Also, why are you doing $invite = $_POST['inviteinput']; twice?

flickr.photos.search

I would like to ask for help. I got this homework to create a class in PHP with search method which returns 50 pictures from Flickr, but without use of official PHP Flickr libraries... Anyway with help of google I wrote following code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
class Flickr {
private $apiKey = 'aba429532a6606f2ee35e3f47a300716';
public function search($query = null) {
$search = 'http://flickr.com/services/rest/?method=flickr.photos.search&api_key=' . $this->apiKey . '&text=' . urlencode($query) . '&per_page=50&format=php_serial';
$result = file_get_contents($search);
$result = unserialize($result);
return $result;
}
}
?>
<form action="index.php" method="get">
<input type="text" name="text1" /><br />
<input type="submit" name="submit1" value="Send" /><br />
</form>
<?php
if(isset($_GET["submit1"])) {
$Flickr = new Flickr;
$data = $Flickr->search($_GET["text1"]);
foreach($data['photos']['photo'] as $photo) {
echo '<img src="http://farm' . $photo["farm"] . '.static.flickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '.jpg">';
}
}
?>
</body>
</html>
That code does what I need, but I am not sure whether I can use flickr.photos.search, so I was wondering if there is a way to avoid using flickr.photos.search.
You could just request http://www.flickr.com/search/?q={work_by_witch_you_search}&z=m pictures from here with curl and just parse received page. Then you definitely wount use anything even close to Flickr API.

Categories