Calling a web service from php? - php

I am trying to call a publicly available web service from a PHP web page.
The web service is: http://www.webservicex.net/uszip.asmx?WSDL
My code:
<html>
<body>
<?php
$zip = $_REQUEST['zip'];
echo 'zip is'.$zip;
?>
<form action="wszip.php" method="post">
<table cellspacing="10" bgcolor="CadetBlue">
<tr>
<td><B>Enter Zip Code : </B><input type="text" name="zip" /></td>
<td></td>
<td><input type="Submit" value="Find It!"/></td>
</tr>
</table>
<BR><BR><BR><BR>
</form>
<?php
if($zip != "")
{
$wsdl = "http://www.webservicex.net/uszip.asmx?WSDL";
$client = new soapclient($wsdl, true);
$response = $client->GetInfoByZIP($zip);
}
?>
</body>
</html>

You're feeding the ZIP code in incorrectly, and your constructor syntax is also incorrect. Use this syntax instead:
$wsdl = "http://www.webservicex.net/uszip.asmx?WSDL";
$client = new soapclient($wsdl);
$response = $client->GetInfoByZIP(array('USZip' => $zip));
I just tested it, and it works fine. The documentation is here.

Related

PHP fOpen unsure where folders must be to be able to open them

Hi i am trying to create a web page that asks the user for two words then will replace the first word with the second word in a file. I have an html file that is working fine. I have a working ubuntu server 16.04 that i am running my html on.
The problem comes in when i try to use PHP to open a file but i am unsure if the file must be on my host desktop or on my virtual machine which i am unsure about.
My html code
<html>
<body>
<form action="replace.php" method="post" enctype="multipart/form-data">>
<table border="0">
<tr>
<td>Old String</td>
<td align="center"><input type="text" name="Old_string" size="30" /></td>
</tr>
<tr>
<td>New String</td>
<td align="center"><input type="text" name="New_string" size="30" /></td>
</tr>
<tr>
<input type="submit" value="Change Values" name="submit">
</tr>
<tr>
<td> Select File that will be changed:</td>
<input type="file" name="FiletoChange" id="FiletoChange">
</tr>
</table>
</form>
</body>
My PHP code
<html>
<head>
<title>Information Gathered</title>
</head>
<body>
<?php
$valid = true;
if (!empty($_POST["Old_string"])) {
$Old_string = $_POST["Old_string"];
} else {
$valid = false;
echo "Old string is Empty . Please Enter value to proceed";
}
if (!empty($_POST["New_string"])) {
$New_string = $_POST["New_string"];
} else {
$valid = false;
echo "New string is Empty . Please Enter value to proceed";
}
if ($valid) {
echo "all input correct";
}
//$myfile = fopen("C:\\Users\\ipadc\\Pictures\\pappa\\EXpert system taak.txt", "r+") or die("Unable to open file!");
//echo fread($myfile,filesize("C:\\Users\\ipadc\\Pictures\\pappa\\EXpert system taak.txt"));
//fclose($myfile);
?>
</body>
</html>
I have commented out my Open file code in the PHP cause i am not sure where this folder must be located for me to be able to access it. Please any help would be appreciated.

PHP YouTube Api V3 MaxResults Not Working

I just implemented Google Api into my app using the YouTube service to get youtube videos. It works as expected as far as getting the results but for some reason MAXRESULTS is not working. It will display results but if i set for example 15 then it shows a endless number of results on the page.
<?php
//Load The Google Api Client
//Added Google Api Support 01/21/2016
set_include_path(get_include_path().PATH_SEPARATOR.'vendor/google/apiclient/src');
//=================================================================================
//START GOOGLE API INTEGRATION
//=================================================================================
$htmlBody = <<<END
<form method="GET">
<div>
Search For YouTube Video<br>
<input type="search" id="q" name="q" placeholder="SEARCH" size="30">
</div>
<input type="submit" value="Search">
</form>
END;
if ( $_GET['q'] )
{
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
$DEVELOPER_KEY = 'REMOVED FOR OBVIOUS REASONS';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => 15,
'type' => 'video',
));
$videos = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos.
$i = 0;
foreach ($searchResponse['items'] as $searchResult)
{
switch ($searchResult['id']['kind'])
{
case 'youtube#video':
$videotitle = $searchResult['snippet']['title'];
$videoid = $searchResult['id']['videoId'];
$videoembed = '<iframe width="150" height="150" src="http://www.youtube.com/embed/'.$videoid.'?autoplay=0&hd=1&vq=hd720" frameborder="0" allowfullscreen></iframe>';
$htmloutput .= '
<table width="50%" align="center">
<tr>
<th colspan="2">'.$i.'. '.$videotitle.'</th>
</tr>
<tr>
<td width="40%">'.$videoembed.'</td>
<td width="60%" align="center">
<form action="index.php" method="post" id="conversionForm">
<input type="hidden" name="youtubeURL" value="'.$videoid.'">
<input type="hidden" value="320" name="quality">
<input type="submit" name="submit" value="Create MP3 File">
</form>
</td>
</tr>
</table>
';
$videos .= '<li>'.$htmloutput.'</li>';
break;
}
$i++;
}
$htmlBody .= <<<END
<h3>Videos</h3>
<ul>$videos</ul>
END;
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
//=================================================================================
//END GOOGLE API INTEGRATION
//=================================================================================
?>
Wow i must be tired. I figured it out.
Changed
$htmloutput .= '
To
$htmloutput = '
That fixed the problem i was having.
Thank You Guys!

Converting Personal Messaging code from MYSQL into MYSQLi

I am trying to build a personal messaging system into my project. I have been using MYSQLi so far in the project, I just found this code for PMS. Now I don't know how to convert this mysql code into mysqli..
<?php
session_start();
$message = $_POST['forward2'];
if (isset($_POST['submit']))
{
// if the form has been submitted, this inserts it into the Database
$to_user = $_POST['to_user'];
$from_user = $_POST['from_user'];
$message = $_POST['message'];
mysql_query("INSERT INTO messages (to_user, message, from_user) VALUES ('$to_user', '$message', '$from_user')")or die(mysql_error());
echo "PM succesfully sent!";
}
else
{
// if the form has not been submitted, this will show the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h3>Send PM:</h3></td></tr>
<tr><td></td><td>
<input type="hidden" name="from_user" maxlength="32" value = <?php echo $_SESSION['username']; ?>>
</td></tr>
<tr><td>To User: </td><td>
<input type="text" name="to_user" maxlength="32" value = "">
</td></tr>
<tr><td>Message: </td><td>
<TEXTAREA NAME="message" COLS=50 ROWS=10 WRAP=SOFT></TEXTAREA>
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Send Message">
</td></tr>
</table>
</form>
<?php
}
?>
Get yourself a tutorial on mysqli.
Follow it through.
Create some simple mysqli-based application.
Make yourself familiar with mysqli
Then start with transition.

Getting TOKEN_INVALID when uploading to YouTube

I'm attempting to upload a video to YouTube via the API using Zend_Gdata (Zend Framework 1.12.0). I had no problems getting direct upload to work, but browser-based upload always gives me a 400 - INVALID TOKEN error. I'm pretty sure I must be missing something vital but small enough to not notice it.
There are two files involved in this:
index.php
<?php
$youTubeAPIKey = '<API_Key>';
$username = '<user>';
$password = '<pass>';
set_include_path(get_include_path().PATH_SEPARATOR.__DIR__."/vendor");
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
try
{
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username,
$password,
$service = 'youtube',
$client = null,
$source = 'BrowserUploaderTest', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$yt = new Zend_Gdata_YouTube($httpClient, "browser upload test", "Test version 0.1", $youTubeAPIKey);
$videoEntry = new Zend_Gdata_YouTube_VideoEntry();
$videoEntry->setVideoTitle("Test movie");
$videoEntry->setVideoDescription("This is a test movie");
$videoEntry->setVideoPrivate();
// #todo This must be a valid YouTube category, how to get a list of valid categories?
$videoEntry->setVideoCategory('Autos');
$videoEntry->setVideoTags('cars, funny');
// Get an upload token
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($videoEntry, $tokenHandlerUrl);
$token = $tokenArray['token'];
$url = $tokenArray['url'];
// print "Token value: {$tokenArray['token']}\n url: {$tokenArray['url']}\n";
$nextUrl = "http://" . $_SERVER['HTTP_HOST'] . "/uploadDone.php";
}
catch (Zend_Gdata_App_HttpException $httpException)
{
echo $httpException->getRawResponseBody();
}
catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
catch (Exception $e)
{
print $e->getTraceAsString();
}
?><!DOCTYPE html>
<html>
<head>
<title>Testing Youtube upload</title>
</head>
<body>
<table>
<tr>
<td>
Url:
</td>
<td>
<?= $url ?>
</td>
</tr>
<tr>
<td>
Token:
</td>
<td>
<?= $token ?>
</td>
</tr>
</table>
<form action="<?= $url ?>.?nexturl=<?= urlencode($nextUrl) ?>" enctype="multipart/form-data" method="post">
<input name="token" type="hidden" value="<?= $token ?>" />
<input name="file" type="file" />
<input type="submit" value="Upload file" />
</form>
</body>
</html>
and uploadDone.php
<?php
print nl2br(print_r($_GET, true));
print nl2br(print_r($_POST, true));
I've searched both on Stack Overflow and spent a couple of hours searching on Google but not found anything that solves it which leads me to believe I'm missing something dead simple. Any help would be appreciated.
A note:
This code is only to test the API usage and is taken mostly from Google's Developer's guide (https://developers.google.com/youtube/2.0/developers_guide_php#Browser_based_Upload) and with a little help from the Yii framework documentation (http://www.yiiframework.com/wiki/375/youtube-api-v2-0-browser-based-uploading/). The production code will be rewritten in a more structured manner but that's not important at the moment.
Your action="<?= $url ?>.?nexturl=<?= urlencode($nextUrl) ?>" looks suspicious; is that an errant . character in there right after your $url variable gets evaluated, messing up the URL?

How to make a PHP Error message popup instead of new page? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Currently on my website I have a form in which once it is submitted, you're taken to a blank screen with the appreciation message.
Instead of moving to a new page, I wish to keep my users on the same page. How might I go about creating a popup and keeping the user within the same page?
You can use javascript validation or HTML5.
If you don't want these ways you can just open a popup window and set your form's target to it. Like this :
<form method="post" action="anything.php" onsubmit="window.open('','my_form_target', 'width=300,height=200', true); this.target='my_form_target';" >
...
try this for validation
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Categories