I have a file that opens a URL and reads it and does the parsing.
Now if that URL goes dwon and my file fails to open it then what i need is that an error mail should get generated but on terminal or konsole no error message should appear.
how can i do that?
Plz help!!
You can always do something like this (i'm assuming you are using file_get_contents)
$file = #fopen("abc.com","rb");
if(!$file) {
#mail(.......);
die();
}
//rest of code. Else is not needed since script will die if hit if condition
Use curl instead if you are retrieving files over the network. It has error handling built in and it will tell you the error that occurred. Using file_get_contents won't tell you what went wrong, it also won't follow redirects.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://domain.com/file');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
if ( $result == false ) {
$errorInfo = curl_errno($ch).' '.curl_error($ch);
mail(...)
} else {
//Process file, $result contains file contents
}
if (!$content = file_get_contents('http://example.org')) {
mail(...);
}
Related
I am using file_get_contents to get the json from URLs. The same URL works sometimes and sometimes it doesn't. When it doesn't, file_get_contents does not return any error and just stops the whole script. It's too confusing.
What's error you get? It's warning or Fatal Error?
if it's warning, please add # to befor file_get_contents like: #file_get_contents
if other, please check data before execute other process
$jsondata =#file_get_contents('YOur URl');
if($jsondata){
// Process your code
}else{
//do nothing
}
What a URL is returning when the correct data is not outputted ?
1)
$json_data =file_get_contents('URl');
if($json_data){
//parse the data
}else{
//show error
}
2 to find what exactly the url returns
$json_data =file_get_contents('URl');
var_dump($json_data);
3 use cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj)
I need to receive image send by PUT method. So I'm wrinting script for testing it. I want to receive and send it with the same script. How can I implement this? The following variant echoes nothing and string about Congratulations that http method was send ok.
<?php
//if they DID upload a file...
var_dump(file_get_contents("php://input"));
if($_FILES['photo']['tmp_name'])
{
echo $_FILES['photo']['error'];
if($_FILES['photo']['error']==0)
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
$message = 'Congratulations!!!!!!!.';
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'url.../1.jpg');
echo'Congratulations! Your file was accepted.';
$image = fopen('url.../1.jpg', "rb");
var_dump($image);
$ch = curl_init();
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://url.../upload.php");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $image);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($image));
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($image); //recommended to close the fileshandler after action
curl_close($ch);
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
else
{
echo"WORKS";
}
The most easiest way to send back the image to a browser is via using a URL.
Process the image
Save the image somewhere on your sever
Send the URL back to browser.
Use a tag at the browser and show your image.
<?PHP
$imgFile="";
if($_FILES['photo']['tmp_name'])
{
///Your existing code
$imgFile="http://" . $_SERVER['HTTP_HOST'] .'/Your image url here';
//Ex:\\ http://yourserver.com/images/1.jpg -
//you can take this from your move_upload_file
}
?>
<img src="<?PHP echo $imgFile; ?>" />
Useful links How to receive a file via HTTP PUT with PHP
Even for a restful service u can use json or xml to send the image url back. PUT is not a good idea unless u need to send back image data for some reason. May be u should rethink your logic?
The mistakes was:
strlen($image) strlen if wrong, must be filesize and in my url I had www. It's not netion in my post but it was mistake.
More experienced programmer helped me.
r.php to read stream:
$res = file_get_contents("php://input");
$file = fopen('1.txt', "w");
fputs($file, $res);
fclose($file);
var_dump($res);
s.php to get stream and to init r.php
$image = fopen('/var/www/testfiles/1.jpg', "rb");
var_dump($image);
$ch = curl_init();
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://url withot www/r.php");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $image);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('/var/www/testfiles/1.jpg'));
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($image); //recommended to close the fileshandler after action
curl_close($ch);
die("OK");
If you just enter the urls into the browser you can see that both work, cdon works even without javascript, have they blocked cURL somehow?
I'm trying to build a scraper to benifit legal movies online which would benifit them a whole lot, seems stupid blocking scrapers in general imho. Although I'm far from sure that's whats going on here! Might be just an error somewhere..
// Works
get_file1('http://sfanytime.com/sv-SE/Sokresultat/?field=all&q=The+Matrix', '/', 'sfanytime.html');
// Saves a blank 0 KB file
get_file1('http://downloads.cdon.com/index.phtml?action=search&search_terms=The+Matrix', '/', 'cdon.html');
function get_file1($file, $local_path, $newfilename) {
$out = fopen($newfilename, 'wb');
if ($out === FALSE) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$error = curl_error($ch);
if (strlen($error) > 0) {
echo "<br>Error is : ". $error;
return false;
}
curl_close($ch);
return true;
}
You should change the line
curl_setopt($ch, CURLOPT_FAILONERROR, true);
...to...
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
CURLOPT_FAILONERROR will cause a "silent fail" - which from what you say, is not what you want. I have replaced this with CURLOPT_FOLLOWLOCATION, because when I visit the second URL, I get redirected to a "choose your country" type page, which will be a response with an empty body - which is why you get an empty file.
There is no problem with your code as such, simply a problem with the way you handle the response from the second URL. You don't see an error because, technically, there wasn't one.
I have a slight issue whereby the API I'm using for part of my service uses a rsp stat to handle the success / error messages in XML.
So we use a form to post it data and it returns the data like the following example:
<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>
The following is most of the script used :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
// ToDo: Replace the placeholders in brackets with your data.
// For example - curl_setopt($ch, CURLOPT_UsERPWD, 'SMSUser:PassW0rD#');
curl_setopt($ch, CURLOPT_USERPWD, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
$xml = curl_exec($ch);
if (curl_error($ch)) {
print "ERROR ". curl_error($ch) ."\n";
}
curl_close($ch);
print_r($xml);
The only problem is that when it is parsed and displayed via the print_r command , it only displays via source code for some strange reason and we have no idea how to display it via the page
Basically we would like a system whereby if rsp stat="ok" then "Sent" else "unsent".
Well, a simple way could be:
if (strpos($xml, 'stat="ok"') !== false) {
echo "sent";
} else {
echo "unsent";
}
http://codepad.org/pkzsfsMk
This would replace print($xml);.
Put that code in a function, and have the function return your $xml.
Assuming you had a function called getRspStat() you could just do like:
echo getRspStat();
If you do something like that:
(see also on CodePad.org)
function xmlRequestWasSuccessful($xml) {
$result = simplexml_load_string($xml);
$result = (string)$result['stat'];
if ($result == 'ok') {
return true;
} else {
return false;
}
}
$xml = '<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>';
$stat = xmlRequestWasSuccessful($xml);
you will receive 'true' boolean in the result ($stat variable). Adapt it to support the case when there is an error. Since no details on how it looks when error occurs, this is how you can do it now:
if ($stat) {
// do something on success ('sent' something)
} else {
// do something on success (display 'unsent' message for example)
}
I need to implement a simple PHP proxy in a web application I am building (Its flash based and the destination service provider doesn't allow edits to their crossdomain.xml file)
Can any php gurus offer advice on the following 2 options? Also, I think, but am not sure, that I need to include some header info as well.
Thanks for any feedback!
option1
$url = $_GET['path'];
readfile($path);
option2
$content .= file_get_contents($_GET['path']);
if ($content !== false)
{
echo($content);
}
else
{
// there was an error
}
First of all, never ever ever include a file based only on user input. Imagine what would happen if someone would call your script like this:
http://example.com/proxy.php?path=/etc/passwd
Then onto the issue: what kind of data are you proxying? If any kind at all, then you need to detect the content type from the content, and pass it on so the receiving end knows what it's getting. I would suggest using something like HTTP_Request2 or something similar from Pear (see: http://pear.php.net/package/HTTP_Request2) if at all possible. If you have access to it, then you could do something like this:
// First validate that the request is to an actual web address
if(!preg_match("#^https?://#", $_GET['path']) {
header("HTTP/1.1 404 Not found");
echo "Content not found, bad URL!";
exit();
}
// Make the request
$req = new HTTP_Request2($_GET['path']);
$response = $req->send();
// Output the content-type header and use the content-type of the original file
header("Content-type: " . $response->getHeader("Content-type"));
// And provide the file body
echo $response->getBody();
Note that this code hasn't been tested, this is just to give you a starting point.
Here's another solution using curl
Can anyone comment??
$ch = curl_init();
$timeout = 30;
$userAgent = $_SERVER['HTTP_USER_AGENT'];
curl_setopt($ch, CURLOPT_URL, $_REQUEST['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
} else {
curl_close($ch);
echo $response;
}